vendetta / src / mpris_d_mpris.v
1430 lines · 1338 sloc · 50.56 KB
Raw
1@[has_globals]
2module main
3
4// This file is built only with -d mpris. Without it, mpris_notd_mpris.v takes
5// its place and libdbus is neither needed nor linked.
6//
7// libdbus is the session bus client. The declarations below follow
8// dbus-1.0's headers; the include path and library come from pkg-config.
9#pkgconfig dbus-1
10#flag -ldbus-1
11
12import libvendetta
13import math
14import net.urllib
15import os
16import sync
17import ui2
18
19// The MPRIS 2.2 D-Bus interface, so the desktop's media controls, applets and
20// global shortcuts see vendetta as a player. The spec:
21// https://specifications.freedesktop.org/mpris-spec/latest/
22
23const mpris_name = 'org.mpris.MediaPlayer2.vendetta'
24
25const mpris_root_iface = 'org.mpris.MediaPlayer2'
26const mpris_player_iface = 'org.mpris.MediaPlayer2.Player'
27const mpris_path = '/org/mpris/MediaPlayer2'
28const dbus_props_iface = 'org.freedesktop.DBus.Properties'
29const dbus_introspectable_iface = 'org.freedesktop.DBus.Introspectable'
30
31// D-Bus wire type codes from dbus-protocol.h.
32const dbus_type_string = i32(`s`)
33const dbus_type_object_path = i32(`o`)
34const dbus_type_double = i32(`d`)
35const dbus_type_boolean = i32(`b`)
36const dbus_type_int64 = i32(`x`)
37const dbus_type_variant = i32(`v`)
38const dbus_type_array = i32(`a`)
39const dbus_type_dict_entry = i32(`e`)
40
41// Name request flags and results from dbus-shared.h.
42const dbus_name_flag_do_not_queue = u32(0x4)
43const dbus_request_name_reply_primary_owner = 1
44const dbus_request_name_reply_already_owner = 4
45
46// Handler results from dbus-connection.h.
47const dbus_handler_handled = 0
48const dbus_handler_not_yet_handled = 1
49
50// Message types from dbus-protocol.h.
51const dbus_msg_method_call = 1
52
53// Bus type from dbus-shared.h.
54const dbus_bus_session = 0
55
56// Dispatch status from dbus-connection.h.
57const dbus_dispatch_data_remains = 0
58
59// Error names from dbus-protocol.h.
60const dbus_error_unknown_property = 'org.freedesktop.DBus.Error.UnknownProperty'
61const dbus_error_property_readonly = 'org.freedesktop.DBus.Error.PropertyReadOnly'
62const dbus_error_invalid_args = 'org.freedesktop.DBus.Error.InvalidArgs'
63
64// MprisCommand is one command the D-Bus thread queues for the UI thread,
65// tagged with the interface member that produced it.
66enum MprisCommandKind {
67 play
68 pause
69 toggle_play
70 stop
71 next
72 previous
73 seek
74 set_position
75 open_uri
76 quit
77 raise
78 volume
79 loop_status
80 shuffle
81}
82
83struct MprisCommand {
84 kind MprisCommandKind
85 // The argument of Seek (an offset in seconds, signed), SetPosition (an
86 // absolute position), Volume (0..1), LoopStatus (the loop code) or
87 // Shuffle (1 or 0).
88 arg f64
89 // The track id SetPosition was addressed with; empty for Seek.
90 track string
91 uri string
92}
93
94// MprisSnapshot is the state the D-Bus thread serves reads from. The UI
95// thread rebuilds it from the player on every change it is told about and
96// hands it over; the worker only ever reads it.
97struct MprisSnapshot {
98pub:
99 // PlaybackStatus: Paused, Playing or Stopped.
100 status string
101 // LoopStatus: None, Track or Playlist.
102 loop_status string
103 shuffle bool
104 // mpv's volume: 100 is unity gain, and the app's max may sit above it.
105 volume f64
106 has_file bool
107 can_play bool
108 can_pause bool
109 can_seek bool
110 can_go_next bool
111 can_go_prev bool
112 position f64
113 duration f64
114 title string
115 artist string
116 url string
117 // The playlist position and length, for CanGoNext/CanGoPrevious: mpv
118 // clamps the step commands itself, but the flags let the desktop grey
119 // out the buttons that would do nothing.
120 playlist_pos int
121 playlist_len int
122 // Rate: vendetta exposes speed as mpv holds it.
123 rate f64
124}
125
126// Mpris owns the D-Bus service. It lives in the app's Player, is created by
127// set_media_controls and torn down on quit. The worker thread holds no
128// reference to the Player: state arrives as snapshots, commands leave over a
129// channel, and shutdown rides a plain flag the worker polls, so the D-Bus
130// thread can never observe the player mid-teardown.
131struct Mpris {
132mut:
133 // The worker's queue of commands for the UI thread. The UI thread pops it
134 // dry once per frame; the D-Bus thread pushes. Chan push and pop are
135 // atomic, so no lock guards it.
136 commands chan MprisCommand
137 // The latest snapshot for reads. Swapped for a new one under the mutex;
138 // the worker copies the pointer out under the same mutex and answers
139 // from its own reference afterwards, so a rebuild during a read cannot
140 // tear the object and the UI thread never waits on D-Bus work.
141 snapshot &MprisSnapshot = unsafe { nil }
142 snapshot_mu &sync.Mutex = unsafe { nil } // Set by the UI thread to end the worker's loop; checked each tick.
143 stop_flag bool
144 // Seek tracking. mpv reports a seek when it starts and playback restarts
145 // once it lands; the next position report after the restart is where the
146 // seek landed, which is what Seeked carries.
147 seeking bool
148 landing bool
149 // The connection, once the object path and the bus name are ours.
150 conn voidptr
151 // The self-pipe the worker blocks on: snapshot updates and shutdown
152 // write a byte, so an idle service answers in milliseconds instead of
153 // on the next poll.
154 pipe_read_fd int = -1
155 pipe_write_fd int = -1
156}
157
158// ── libdbus ─────────────────────────────────────────────────────────────────
159
160// The declarations follow dbus-1.0's headers as installed; dbus_connection_
161// read_write_dispatch is deliberately absent: the worker polls with
162// read_write plus dispatch and sleeps on the wake pipe between cycles.
163fn C.dbus_error_init(&DBusError)
164fn C.dbus_error_free(&DBusError)
165fn C.dbus_bus_get(i32, voidptr) voidptr
166fn C.dbus_bus_request_name(voidptr, &char, u32, voidptr) i32
167fn C.dbus_connection_ref(voidptr) voidptr
168fn C.dbus_connection_unref(voidptr)
169fn C.dbus_connection_close(voidptr)
170fn C.dbus_connection_unregister_object_path(voidptr, &char) i32
171fn C.dbus_bus_release_name(voidptr, &char, voidptr) i32
172fn C.dbus_connection_register_object_path(voidptr, &char, voidptr, voidptr) i32
173fn C.dbus_connection_add_filter(voidptr, DBusFilterFn, voidptr, voidptr) i32
174fn C.dbus_connection_get_dispatch_status(voidptr) i32
175fn C.dbus_connection_dispatch(voidptr) i32
176fn C.dbus_connection_read_write(voidptr, i32) i32
177fn C.dbus_connection_send(voidptr, voidptr, voidptr) i32
178fn C.dbus_message_new_method_return(voidptr) voidptr
179fn C.dbus_message_new_error(voidptr, &char, &char) voidptr
180fn C.dbus_message_new_signal(voidptr, &char, &char) voidptr
181fn C.dbus_message_get_type(voidptr) i32
182fn C.dbus_message_get_interface(voidptr) &char
183fn C.dbus_message_get_member(voidptr) &char
184fn C.dbus_message_iter_init(voidptr, &DBusMessageIter) i32
185fn C.dbus_message_iter_init_append(voidptr, &DBusMessageIter)
186fn C.dbus_message_iter_get_arg_type(&DBusMessageIter) i32
187fn C.dbus_message_iter_get_basic(&DBusMessageIter, voidptr)
188fn C.dbus_message_iter_next(&DBusMessageIter) i32
189fn C.dbus_message_iter_recurse(&DBusMessageIter, &DBusMessageIter)
190fn C.dbus_message_iter_open_container(&DBusMessageIter, i32, &char, &DBusMessageIter) i32
191fn C.dbus_message_iter_close_container(&DBusMessageIter, &DBusMessageIter) i32
192fn C.dbus_message_iter_append_basic(&DBusMessageIter, i32, voidptr) i32
193fn C.dbus_message_append_args(voidptr, i32, voidptr, i32) i32
194fn C.dbus_message_unref(voidptr)
195fn C.dbus_message_set_serial(voidptr, u32)
196
197// The wake pipe drains through a non-blocking read, so the worker's
198// post-wake loop never waits for a byte that is not coming.
199const fcntl_f_setfl = 4
200
201// read and write come from the C library through builtin's declarations; the
202// wake pipe uses them directly.
203
204// DBusError is declared with its own shape instead of including dbus-headers.
205// The real struct is two const char* fields, five one-bit flags and a
206// padding pointer — 32 bytes; a short mirror lets dbus_error_init write
207// past it and smash the stack, so the bit word and the padding pointer are
208// spelled out.
209struct DBusError {
210 name &char = unsafe { nil }
211 message &char = unsafe { nil }
212 flagbits u32
213 padding1 voidptr = unsafe { nil }
214}
215
216// DBusMessageIter matches the opaque struct's real layout (dbus-message.h)
217// exactly: two pointers, a u32, nine ints and two padding pointers on
218// LP64 — 88 bytes. A short mirror would let init_append and friends write
219// past the local and corrupt the stack, so every field is spelled out even
220// though none is ever read.
221struct DBusMessageIter {
222 dummy1 voidptr
223 dummy2 voidptr
224 dummy3 u32
225 dummy4 i32
226 dummy5 i32
227 dummy6 i32
228 dummy7 i32
229 dummy8 i32
230 dummy9 i32
231 dummy10 i32
232 dummy11 i32
233 pad1 i32
234 pad2 voidptr
235 pad3 voidptr
236}
237
238type DBusFilterFn = fn (voidptr, voidptr, voidptr) i32
239
240// DBusObjectPathVTable matches dbus-connection.h's real layout: the two
241// handlers plus four reserved pointers libdbus copies wholesale, so the
242// mirror must carry them or the copy reads past the local.
243struct DBusObjectPathVTable {
244 unregister_function voidptr = unsafe { nil }
245 message_function DBusFilterFn = unsafe { nil }
246 pad1 voidptr = unsafe { nil }
247 pad2 voidptr = unsafe { nil }
248 pad3 voidptr = unsafe { nil }
249 pad4 voidptr = unsafe { nil }
250}
251
252// ── UI-thread side ──────────────────────────────────────────────────────────
253
254// mpris_new prepares the service. The bus connect and name request run on
255// the worker, so nothing here can block startup.
256fn mpris_new() &Mpris {
257 mut m := &Mpris{
258 commands: chan MprisCommand{cap: 32}
259 snapshot_mu: sync.new_mutex()
260 }
261 m.snapshot = mpris_snapshot_of_empty()
262 // The wake pipe: os.pipe gives both fds at once, and the read end is
263 // made non-blocking, so drain_pipe never waits for a byte that is not
264 // coming — a blocking second read would park the worker forever right
265 // after its first wake. A failure only costs latency: the worker's
266 // poll keeps the service alive on its tick.
267 if pipe := os.pipe() {
268 m.pipe_read_fd = pipe.read_fd
269 m.pipe_write_fd = pipe.write_fd
270 C.fcntl(m.pipe_read_fd, fcntl_f_setfl, C.O_NONBLOCK)
271 }
272 return m
273}
274
275// mpris_free asks the service to leave the bus. The worker sees the flag on its
276// next tick, releases the name and its object path, and returns. Called after
277// run_window_with_options returns, where every other thread but this one is
278// parked.
279fn (mut m Mpris) mpris_free() {
280 m.stop_flag = true
281 m.wake_worker()
282}
283
284// mpris_announce publishes the full state: at start, on a file change, and
285// wherever a caller would otherwise repeat a string of property pushes. The
286// snapshot arrives as a heap reference the caller built; the swap hands its
287// ownership to the worker.
288fn (mut m Mpris) mpris_announce(s &MprisSnapshot) {
289 m.replace_snapshot(s)
290 m.wake_worker()
291}
292
293// mpris_property publishes one changed property.
294fn (mut m Mpris) mpris_property(s &MprisSnapshot) {
295 m.replace_snapshot(s)
296 m.wake_worker()
297}
298
299// mpris_seek_started notes that mpv began a seek, from any source: the
300// keyboard, the slider, or a Seek or SetPosition from the desktop.
301fn (mut m Mpris) mpris_seek_started() {
302 m.seeking = true
303}
304
305// mpris_seek_landed is the restart mpv reports once a seek has landed. The
306// next position report carries the landed position.
307fn (mut m Mpris) mpris_seek_landed() {
308 if m.seeking {
309 m.seeking = false
310 m.landing = true
311 }
312}
313
314// mpris_on_position emits Seeked for a seek that has landed. Steady playback
315// moves the position without a seek, so nothing is announced for it.
316fn (mut m Mpris) mpris_on_position(pos f64) {
317 if m.landing {
318 m.landing = false
319 m.emit_seeked(pos)
320 }
321}
322
323// mpris_on_volume reacts to mpv's own volume writes (keys, wheel, the
324// strip's slider): the snapshot the next push carries carries the new
325// value, and the wake makes the worker announce it at once.
326fn (mut m Mpris) mpris_on_volume() {
327 m.wake_worker()
328}
329
330// mpris_track_position keeps the Position property current. Reads come from
331// the snapshot, and a client that adds an offset to a stale Position seeks
332// from the wrong place, so each position change swaps in a snapshot that
333// carries it. No signal goes out: the spec does not announce Position changes.
334fn (mut m Mpris) mpris_track_position(pos f64) {
335 m.replace_snapshot(m.current_snapshot().with_position(pos))
336}
337
338// with_position returns a copy of the snapshot at another position. The copy
339// is a heap literal like every snapshot, since the worker may still hold the
340// old one.
341fn (s &MprisSnapshot) with_position(pos f64) &MprisSnapshot {
342 return &MprisSnapshot{
343 status: s.status
344 loop_status: s.loop_status
345 shuffle: s.shuffle
346 volume: s.volume
347 has_file: s.has_file
348 can_play: s.can_play
349 can_pause: s.can_pause
350 can_seek: s.can_seek
351 can_go_next: s.can_go_next
352 can_go_prev: s.can_go_prev
353 position: pos
354 duration: s.duration
355 title: s.title
356 artist: s.artist
357 url: s.url
358 playlist_pos: s.playlist_pos
359 playlist_len: s.playlist_len
360 rate: s.rate
361 }
362}
363
364// registered reports whether the service is on the bus.
365fn (m &Mpris) registered() bool {
366 return m.conn != unsafe { nil }
367}
368
369// wake_worker interrupts the worker's poll through the self-pipe. The bytes
370// read back are an event counter, not data; several writes may collapse into
371// one drain, which only means one spurious poll.
372fn (mut m Mpris) wake_worker() {
373 if m.pipe_write_fd >= 0 {
374 one := u8(1)
375 C.write(m.pipe_write_fd, &one, 1)
376 }
377}
378
379// drain_pipe empties the wake pipe after each poll cycle.
380fn (mut m Mpris) drain_pipe() {
381 for {
382 mut b := u8(0)
383 n := C.read(m.pipe_read_fd, &b, 1)
384 if n <= 0 {
385 return
386 }
387 }
388}
389
390// replace_snapshot swaps the read state for a new one. The snapshot is
391// built by the UI thread as a heap literal; the swap hands the worker a
392// pointer the UI thread no longer holds, and the mutex is held only for
393// that swap.
394fn (mut m Mpris) replace_snapshot(s &MprisSnapshot) {
395 m.snapshot_mu.lock()
396 m.snapshot = s
397 m.snapshot_mu.unlock()
398}
399
400// current_snapshot copies the latest snapshot reference out. The read is
401// unsynchronized on purpose: the reference is pointer-sized, the object it
402// points at never changes once published, and the UI thread only ever
403// swaps the reference, so the worker sees either the old or the new
404// snapshot, both valid.
405fn (m &Mpris) current_snapshot() &MprisSnapshot {
406 return m.snapshot
407}
408
409// mpris_snapshot_of_empty is the state before any file: Stopped, nothing
410// playable, the step flags off.
411fn mpris_snapshot_of_empty() &MprisSnapshot {
412 return &MprisSnapshot{
413 status: 'Stopped'
414 rate: 1
415 }
416}
417
418// ── Worker-thread side ──────────────────────────────────────────────────────
419
420// mpris_worker owns the D-Bus connection for its whole life: it connects,
421// requests the name, registers the object path, then serves reads from the
422// snapshot and queues commands for the UI thread until the stop flag flips.
423// Only a V-spawned thread runs here, so the GC knows it and every V string
424// and array it touches is safe.
425fn mpris_worker(mut m Mpris) {
426 mut err := DBusError{}
427 C.dbus_error_init(&err)
428 conn := C.dbus_bus_get(dbus_bus_session, voidptr(&err))
429 if conn == unsafe { nil } {
430 if err.message != unsafe { nil } {
431 text := unsafe { cstring_to_vstring(err.message) }
432 eprintln('vendetta: media controls: no session bus: ${text}')
433 } else {
434 eprintln('vendetta: media controls: no session bus')
435 }
436 C.dbus_error_free(&err)
437 return
438 }
439 C.dbus_error_free(&err)
440 // The name is taken with DO_NOT_QUEUE: a second vendetta must not sit in
441 // the name queue waiting for the first to exit, because both would then
442 // answer calls meant for whichever owns the name. Losing is reported and
443 // the service idles; the connection stays until shutdown so the owner
444 // keeps its unique name for any caller that wants the player anyway.
445 rc := C.dbus_bus_request_name(conn, mpris_name.str, dbus_name_flag_do_not_queue, voidptr(&err))
446 if rc < 0 {
447 if err.message != unsafe { nil } {
448 text := unsafe { cstring_to_vstring(err.message) }
449 eprintln('vendetta: media controls: name request failed: ${text}')
450 } else {
451 eprintln('vendetta: media controls: name request failed')
452 }
453 C.dbus_error_free(&err)
454 return
455 }
456 if rc != dbus_request_name_reply_primary_owner && rc != dbus_request_name_reply_already_owner {
457 eprintln('vendetta: media controls: another player owns ${mpris_name}')
458 return
459 }
460 // The object path is registered before any call can arrive, so nothing
461 // lands that the vtable is not there to answer.
462 mut vtable := DBusObjectPathVTable{
463 unregister_function: voidptr(0)
464 message_function: mpris_message_handler
465 }
466 if C.dbus_connection_register_object_path(conn, mpris_path.str, voidptr(&vtable), voidptr(m)) == 0 {
467 eprintln('vendetta: media controls: object path registration failed')
468 return
469 }
470 // The Properties interface rides the same path under a different
471 // interface name; a filter answers its Get/Set/GetAll before the vtable
472 // even sees the message.
473 C.dbus_connection_add_filter(conn, mpris_filter, voidptr(m), unsafe { nil })
474 m.conn = conn
475 m.wake_worker()
476 for {
477 if m.stop_flag {
478 // The connection is shared process-wide and must not be closed,
479 // so the name and the path are given back here, on the thread that
480 // uses the connection.
481 C.dbus_bus_release_name(conn, mpris_name.str, unsafe { nil })
482 C.dbus_connection_unregister_object_path(conn, mpris_path.str)
483 return
484 }
485 // The per-wake work: dispatch what the bus delivered, then publish
486 // the signals the latest snapshot calls for.
487 for C.dbus_connection_get_dispatch_status(conn) == dbus_dispatch_data_remains {
488 C.dbus_connection_dispatch(conn)
489 }
490 s := m.current_snapshot()
491 if mpris_have_announced {
492 mpris_emit_diff(mut m, mpris_last_snapshot, s)
493 } else {
494 // The first snapshot announces everything at once.
495 mpris_emit_diff(mut m, mpris_snapshot_of_empty(), s)
496 mpris_have_announced = true
497 }
498 mpris_last_snapshot = s
499 // The sleep: read_write runs the socket work with a short timeout
500 // and doubles as the nap. The wake pipe is read after it, so a
501 // byte that arrived mid-nap cuts the next one short; C.read past a
502 // wake returns immediately, and the cycle restarts. A full
503 // read_write_dispatch would block in select on the bus sockets,
504 // which is exactly the wait the pipe cannot interrupt.
505 C.dbus_connection_read_write(conn, dbus_poll_ms)
506 m.drain_pipe()
507 }
508}
509
510// dbus_poll_ms is how long the worker's read_write may block on the bus
511// sockets between cycles: long enough that an idle service costs nothing,
512// short enough that the stop flag is honoured promptly.
513const dbus_poll_ms = 200
514
515// mpris_last_snapshot remembers what the signals last announced; worker-local
516// state, written and read only on the worker thread.
517__global mpris_last_snapshot = mpris_snapshot_of_empty()
518__global mpris_have_announced = false
519
520// ── Message plumbing ────────────────────────────────────────────────────────
521
522// queue hands one command to the UI thread and asks ui2 for a paint. The
523// window repaints only when asked, and the per-frame drain runs in the video
524// surface's draw, which a plain rebuild does not reach. The executor's own
525// state changes ask for a rebuild where they need one.
526fn (mut m Mpris) queue(cmd MprisCommand) {
527 m.commands <- cmd
528 ui2.request_paint()
529}
530
531// mpris_message_handler answers calls addressed to the object path. Runs on
532// the worker thread: the player is never touched, reads come from the
533// snapshot and writes go over the channel.
534fn mpris_message_handler(conn voidptr, msg voidptr, user_data voidptr) i32 {
535 mut m := &Mpris(user_data)
536 if C.dbus_message_get_type(msg) != dbus_msg_method_call {
537 return dbus_handler_not_yet_handled
538 }
539 iface := dbus_cstring(C.dbus_message_get_interface(msg))
540 member := dbus_cstring(C.dbus_message_get_member(msg))
541 if iface == mpris_root_iface {
542 return m.handle_root(msg, member)
543 }
544 if iface == mpris_player_iface {
545 return m.handle_player(msg, member)
546 }
547 if iface == dbus_introspectable_iface {
548 return m.handle_introspect(conn, msg)
549 }
550 return dbus_handler_not_yet_handled
551}
552
553// dbus_cstring reads a libdbus-owned C string, nil tolerated.
554fn dbus_cstring(ptr &char) string {
555 if ptr == unsafe { nil } {
556 return ''
557 }
558 return unsafe { cstring_to_vstring(ptr) }
559}
560
561// handle_root answers the org.mpris.MediaPlayer2 root interface's methods:
562// Raise and Quit. CanQuit, Identity and friends are property reads, served
563// by the filter below.
564fn (mut m Mpris) handle_root(msg voidptr, member string) i32 {
565 match member {
566 'Raise' {
567 m.queue(MprisCommand{ kind: .raise })
568 return m.reply_empty(msg)
569 }
570 'Quit' {
571 m.queue(MprisCommand{ kind: .quit })
572 return m.reply_empty(msg)
573 }
574 else {}
575 }
576 return dbus_handler_not_yet_handled
577}
578
579// handle_player answers the org.mpris.MediaPlayer2.Player interface's
580// methods. Each queues one command; the UI thread runs them where mpv lives.
581fn (mut m Mpris) handle_player(msg voidptr, member string) i32 {
582 match member {
583 'Play' {
584 m.queue(MprisCommand{ kind: .play })
585 return m.reply_empty(msg)
586 }
587 'Pause' {
588 m.queue(MprisCommand{ kind: .pause })
589 return m.reply_empty(msg)
590 }
591 'PlayPause' {
592 m.queue(MprisCommand{ kind: .toggle_play })
593 return m.reply_empty(msg)
594 }
595 'Stop' {
596 m.queue(MprisCommand{ kind: .stop })
597 return m.reply_empty(msg)
598 }
599 'Next' {
600 m.queue(MprisCommand{ kind: .next })
601 return m.reply_empty(msg)
602 }
603 'Previous' {
604 m.queue(MprisCommand{ kind: .previous })
605 return m.reply_empty(msg)
606 }
607 'Seek' {
608 x := dbus_iter_int64_arg(msg) or {
609 return m.reply_error(msg, dbus_error_invalid_args, 'Seek wants an offset in microseconds')
610 }
611 m.queue(MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 })
612 return m.reply_empty(msg)
613 }
614 'SetPosition' {
615 res := dbus_iter_set_position(msg) or {
616 return m.reply_error(msg, dbus_error_invalid_args, 'SetPosition wants (o trackid, x position)')
617 }
618 m.queue(MprisCommand{ kind: .set_position, arg: res.pos, track: res.track })
619 return m.reply_empty(msg)
620 }
621 'OpenUri' {
622 uri := dbus_iter_string_arg(msg) or {
623 return m.reply_error(msg, dbus_error_invalid_args, 'OpenUri wants a URI')
624 }
625 target := mpris_open_target(uri) or {
626 return m.reply_error(msg, dbus_error_invalid_args, 'Unsupported URI: ${uri}')
627 }
628 m.queue(MprisCommand{ kind: .open_uri, uri: target })
629 return m.reply_empty(msg)
630 }
631 else {}
632 }
633 return dbus_handler_not_yet_handled
634}
635
636// handle_introspect answers the XML desktop caches ask for once. The
637// Properties interface is included though it is answered by the filter, so
638// an introspecting caller sees the whole object.
639fn (mut m Mpris) handle_introspect(conn voidptr, msg voidptr) i32 {
640 reply := C.dbus_message_new_method_return(msg)
641 if reply == unsafe { nil } {
642 return dbus_handler_not_yet_handled
643 }
644 xml := mpris_introspection_xml()
645 C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml), 0)
646 C.dbus_connection_send(conn, reply, unsafe { nil })
647 C.dbus_message_unref(reply)
648 return dbus_handler_handled
649}
650
651// reply_empty answers a void method return.
652fn (mut m Mpris) reply_empty(msg voidptr) i32 {
653 reply := C.dbus_message_new_method_return(msg)
654 if reply == unsafe { nil } {
655 return dbus_handler_not_yet_handled
656 }
657 C.dbus_connection_send(m.conn, reply, unsafe { nil })
658 C.dbus_message_unref(reply)
659 return dbus_handler_handled
660}
661
662// reply_error answers with a D-Bus error: the name and a human message.
663fn (mut m Mpris) reply_error(msg voidptr, name string, text string) i32 {
664 reply := C.dbus_message_new_error(msg, name.str, text.str)
665 if reply == unsafe { nil } {
666 return dbus_handler_not_yet_handled
667 }
668 C.dbus_connection_send(m.conn, reply, unsafe { nil })
669 C.dbus_message_unref(reply)
670 return dbus_handler_handled
671}
672
673// ── Argument readers ────────────────────────────────────────────────────────
674
675// dbus_iter_string_arg reads a one-string or one-object-path message.
676fn dbus_iter_string_arg(msg voidptr) ?string {
677 mut iter := DBusMessageIter{}
678 if C.dbus_message_iter_init(msg, &iter) == 0 {
679 return none
680 }
681 return dbus_iter_read_string(&iter)
682}
683
684// dbus_iter_read_string reads a string or object path out of an iterator.
685fn dbus_iter_read_string(iter &DBusMessageIter) ?string {
686 typ := C.dbus_message_iter_get_arg_type(iter)
687 if typ != dbus_type_string && typ != dbus_type_object_path {
688 return none
689 }
690 mut ptr := voidptr(0)
691 C.dbus_message_iter_get_basic(iter, &ptr)
692 return dbus_cstring(unsafe { &char(ptr) })
693}
694
695// dbus_iter_int64_arg reads a one-int64 message.
696fn dbus_iter_int64_arg(msg voidptr) ?i64 {
697 mut iter := DBusMessageIter{}
698 if C.dbus_message_iter_init(msg, &iter) == 0 {
699 return none
700 }
701 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_int64 {
702 return none
703 }
704 mut v := i64(0)
705 C.dbus_message_iter_get_basic(&iter, &v)
706 return v
707}
708
709// SetPositionResult carries SetPosition's two arguments.
710struct SetPositionResult {
711 track string
712 pos f64
713}
714
715// dbus_iter_set_position unpacks (o trackid, x position) — two top-level
716// arguments, no container between them.
717fn dbus_iter_set_position(msg voidptr) ?SetPositionResult {
718 mut iter := DBusMessageIter{}
719 if C.dbus_message_iter_init(msg, &iter) == 0 {
720 return none
721 }
722 track := dbus_iter_read_string(&iter) or { return none }
723 if C.dbus_message_iter_next(&iter) == 0 {
724 return none
725 }
726 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_int64 {
727 return none
728 }
729 mut v := i64(0)
730 C.dbus_message_iter_get_basic(&iter, &v)
731 return SetPositionResult{
732 track: track
733 pos: f64(v) / 1_000_000.0
734 }
735}
736
737// mpris_open_target turns an OpenUri argument into what load() accepts.
738// file:// URIs decode back to paths, because mpv wants one; a link — any
739// other protocol prefix — goes through verbatim for mpv to stream. Neither
740// shape is an error reply, which is friendlier than a load that would fail
741// later with less context.
742fn mpris_open_target(uri string) ?string {
743 if uri.starts_with('file://') {
744 mut rest := uri.all_after('file://')
745 // A host part (file://localhost/path) is tolerated; the spec's empty
746 // host rides the same decode. Percent escapes decode into raw bytes,
747 // which is what a path is.
748 if rest.starts_with('localhost/') {
749 rest = rest.all_after('localhost')
750 }
751 return urllib.query_unescape(rest) or { return none }
752 }
753 if libvendetta.source_kind(uri) == .link {
754 return uri
755 }
756 return none
757}
758
759// ── Properties filter ───────────────────────────────────────────────────────
760
761// mpris_filter catches the Properties calls: Get, Set and GetAll arrive
762// addressed to the object path but to the properties interface, and the
763// vtable dispatches by interface, so the filter answers them here.
764fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 {
765 mut m := &Mpris(user_data)
766 if C.dbus_message_get_type(msg) != dbus_msg_method_call {
767 return dbus_handler_not_yet_handled
768 }
769 if dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface {
770 return dbus_handler_not_yet_handled
771 }
772 member := dbus_cstring(C.dbus_message_get_member(msg))
773 match member {
774 'Get' {
775 return m.props_get(msg)
776 }
777 'Set' {
778 return m.props_set(msg)
779 }
780 'GetAll' {
781 return m.props_get_all(msg)
782 }
783 else {}
784 }
785 return dbus_handler_not_yet_handled
786}
787
788// props_get answers Properties.Get with one property's value as a variant.
789fn (mut m Mpris) props_get(msg voidptr) i32 {
790 mut iter := DBusMessageIter{}
791 if C.dbus_message_iter_init(msg, &iter) == 0 {
792 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
793 }
794 iface := dbus_iter_read_string(&iter) or {
795 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
796 }
797 if C.dbus_message_iter_next(&iter) == 0 {
798 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
799 }
800 prop := dbus_iter_read_string(&iter) or {
801 return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)')
802 }
803 s := m.current_snapshot()
804 mut body := m.property_body(iface, prop, s) or {
805 return m.reply_error(msg, dbus_error_unknown_property, 'No such property: ${prop}')
806 }
807 reply := C.dbus_message_new_method_return(msg)
808 if reply == unsafe { nil } {
809 return dbus_handler_not_yet_handled
810 }
811 mut rit := DBusMessageIter{}
812 C.dbus_message_iter_init_append(reply, &rit)
813 m.append_prop(&rit, mut body)
814 C.dbus_connection_send(m.conn, reply, unsafe { nil })
815 C.dbus_message_unref(reply)
816 return dbus_handler_handled
817}
818
819// props_get_all answers Properties.GetAll with the interface's whole
820// property dictionary: a{sv}.
821fn (mut m Mpris) props_get_all(msg voidptr) i32 {
822 mut iter := DBusMessageIter{}
823 if C.dbus_message_iter_init(msg, &iter) == 0 {
824 return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name')
825 }
826 iface := dbus_iter_read_string(&iter) or {
827 return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name')
828 }
829 s := m.current_snapshot()
830 reply := C.dbus_message_new_method_return(msg)
831 if reply == unsafe { nil } {
832 return dbus_handler_not_yet_handled
833 }
834 mut rit := DBusMessageIter{}
835 C.dbus_message_iter_init_append(reply, &rit)
836 mut arr := DBusMessageIter{}
837 C.dbus_message_iter_open_container(&rit, dbus_type_array, c'{sv}', &arr)
838 for prop, mut body in m.property_table(iface, s) {
839 mut entry := DBusMessageIter{}
840 C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &entry)
841 dbus_append_text(&entry, dbus_type_string, prop)
842 m.append_prop(&entry, mut body)
843 C.dbus_message_iter_close_container(&arr, &entry)
844 }
845 C.dbus_message_iter_close_container(&rit, &arr)
846 C.dbus_connection_send(m.conn, reply, unsafe { nil })
847 C.dbus_message_unref(reply)
848 return dbus_handler_handled
849}
850
851// props_set answers Properties.Set: only the writable Player properties
852// exist here, and each maps to a command the UI thread runs.
853fn (mut m Mpris) props_set(msg voidptr) i32 {
854 mut iter := DBusMessageIter{}
855 if C.dbus_message_iter_init(msg, &iter) == 0 {
856 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
857 }
858 iface := dbus_iter_read_string(&iter) or {
859 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
860 }
861 if C.dbus_message_iter_next(&iter) == 0 {
862 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
863 }
864 prop := dbus_iter_read_string(&iter) or {
865 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
866 }
867 if C.dbus_message_iter_next(&iter) == 0 {
868 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
869 }
870 if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_variant {
871 return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)')
872 }
873 mut var := DBusMessageIter{}
874 C.dbus_message_iter_recurse(&iter, &var)
875 if iface != mpris_player_iface {
876 // The root interface has no writable properties; Fullscreen is
877 // optional and vendetta does not offer it.
878 return m.reply_error(msg, dbus_error_unknown_property, 'No writable property: ${prop}')
879 }
880 match prop {
881 'LoopStatus' {
882 value := dbus_iter_read_string(&var) or {
883 return m.reply_error(msg, dbus_error_invalid_args, 'LoopStatus wants a string')
884 }
885 code := mpris_loop_code(value) or {
886 return m.reply_error(msg, dbus_error_invalid_args, 'Not a LoopStatus: ${value}')
887 }
888 m.queue(MprisCommand{ kind: .loop_status, arg: code })
889 return m.reply_empty(msg)
890 }
891 'Shuffle' {
892 // A number is refused on purpose: the spec's type is a boolean, and
893 // a double-encoded value is not one.
894 if _ := dbus_iter_double_from(var) {
895 return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean')
896 }
897 b := dbus_iter_flag_from(var) or {
898 return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean')
899 }
900 m.queue(MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } })
901 return m.reply_empty(msg)
902 }
903 'Volume' {
904 value := dbus_iter_double_from(var) or {
905 return m.reply_error(msg, dbus_error_invalid_args, 'Volume wants a double')
906 }
907 m.queue(MprisCommand{ kind: .volume, arg: value })
908 return m.reply_empty(msg)
909 }
910 'Rate' {
911 return m.reply_error(msg, dbus_error_property_readonly, 'Rate follows the speed menu')
912 }
913 else {
914 return m.reply_error(msg, dbus_error_property_readonly, 'Read-only property: ${prop}')
915 }
916 }
917}
918
919// dbus_iter_double_from reads a double out of an iterator.
920fn dbus_iter_double_from(iter &DBusMessageIter) ?f64 {
921 if C.dbus_message_iter_get_arg_type(iter) != dbus_type_double {
922 return none
923 }
924 mut v := f64(0)
925 C.dbus_message_iter_get_basic(iter, &v)
926 return v
927}
928
929// dbus_iter_flag_from reads a boolean out of an iterator.
930fn dbus_iter_flag_from(iter &DBusMessageIter) ?bool {
931 if C.dbus_message_iter_get_arg_type(iter) != dbus_type_boolean {
932 return none
933 }
934 mut v := i32(0)
935 C.dbus_message_iter_get_basic(iter, &v)
936 return v != 0
937}
938
939// ── Property table ──────────────────────────────────────────────────────────
940
941// PropBody is one property ready to append: the variant's signature, the
942// wire type and the value in its C form.
943struct PropBody {
944pub:
945 signature string
946 typ i32
947 str string
948 boolean bool
949 num f64
950 items []string
951 entries []PropEntry
952}
953
954// PropEntry is one key/value pair of a dictionary property (Metadata).
955struct PropEntry {
956pub:
957 key string
958 value PropBody
959}
960
961// prop_string wraps a string or object-path value.
962fn prop_string(typ i32, value string) PropBody {
963 return PropBody{
964 signature: if typ == dbus_type_object_path { 'o' } else { 's' }
965 typ: typ
966 str: value
967 }
968}
969
970// prop_bool wraps a boolean value.
971fn prop_bool(value bool) PropBody {
972 return PropBody{
973 signature: 'b'
974 typ: dbus_type_boolean
975 boolean: value
976 }
977}
978
979// prop_double wraps a double value.
980fn prop_double(value f64) PropBody {
981 return PropBody{
982 signature: 'd'
983 typ: dbus_type_double
984 num: value
985 }
986}
987
988// prop_int wraps an int64 value.
989fn prop_int(value i64) PropBody {
990 return PropBody{
991 signature: 'x'
992 typ: dbus_type_int64
993 num: f64(value)
994 }
995}
996
997// prop_string_array wraps an array of strings.
998fn prop_string_array(items []string) PropBody {
999 return PropBody{
1000 signature: 'as'
1001 typ: dbus_type_array
1002 items: items
1003 }
1004}
1005
1006// prop_dict wraps a dictionary of string→variant entries (a{sv}).
1007fn prop_dict(entries []PropEntry) PropBody {
1008 return PropBody{
1009 signature: 'a{sv}'
1010 typ: dbus_type_array
1011 entries: entries
1012 }
1013}
1014
1015// append_prop appends one property as a variant into an open iterator: the
1016// form Properties.Get returns and each a{sv} entry carries.
1017fn (mut m Mpris) append_prop(iter &DBusMessageIter, mut body PropBody) {
1018 mut var := DBusMessageIter{}
1019 mut sig := body.signature
1020 C.dbus_message_iter_open_container(iter, dbus_type_variant, sig.str, &var)
1021 m.append_body(&var, mut body)
1022 C.dbus_message_iter_close_container(iter, &var)
1023}
1024
1025// dbus_append_text appends a string or object path. libdbus reads the text
1026// through the address of a char* that the call holds, so the pointer lives in
1027// a local for the call, and the append copies the bytes out before it returns.
1028fn dbus_append_text(iter &DBusMessageIter, typ i32, value string) {
1029 mut ptr := value.str
1030 C.dbus_message_iter_append_basic(iter, typ, voidptr(&ptr))
1031}
1032
1033// append_body appends the body's value into an open container.
1034fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) {
1035 // A failed open would leave the sub-iterator zeroed and the close would
1036 // walk off it, so opens are checked like the rest.
1037 match body.typ {
1038 dbus_type_string, dbus_type_object_path {
1039 dbus_append_text(iter, body.typ, body.str)
1040 }
1041 dbus_type_boolean {
1042 mut flag := i32(if body.boolean { 1 } else { 0 })
1043 C.dbus_message_iter_append_basic(iter, dbus_type_boolean, voidptr(&flag))
1044 }
1045 dbus_type_double {
1046 mut v := body.num
1047 C.dbus_message_iter_append_basic(iter, dbus_type_double, voidptr(&v))
1048 }
1049 dbus_type_int64 {
1050 mut v := i64(body.num)
1051 C.dbus_message_iter_append_basic(iter, dbus_type_int64, voidptr(&v))
1052 }
1053 dbus_type_array {
1054 if body.entries.len > 0 {
1055 // a{sv}: a dict entry per pair, the key a string, the value
1056 // a variant. The dict entry's own signature is the pair
1057 // 'sv'; the array's is the wrapped '{sv}'.
1058 mut arr := DBusMessageIter{}
1059 mut sig := body.signature.all_after('a')
1060 if C.dbus_message_iter_open_container(iter, dbus_type_array, sig.str, &arr) == 0 {
1061 return
1062 }
1063 for mut entry in body.entries {
1064 mut de := DBusMessageIter{}
1065 C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de)
1066 dbus_append_text(&de, dbus_type_string, entry.key)
1067 m.append_prop(&de, mut entry.value)
1068 C.dbus_message_iter_close_container(&arr, &de)
1069 }
1070 C.dbus_message_iter_close_container(iter, &arr)
1071 } else {
1072 // as: one string per element.
1073 mut arr := DBusMessageIter{}
1074 mut elem := body.signature.all_after('a')
1075 if C.dbus_message_iter_open_container(iter, dbus_type_array, elem.str, &arr) == 0 {
1076 return
1077 }
1078 for item in body.items {
1079 dbus_append_text(&arr, dbus_type_string, item)
1080 }
1081 C.dbus_message_iter_close_container(iter, &arr)
1082 }
1083 }
1084 else {}
1085 }
1086}
1087
1088// property_body is property_table reduced to one property; none is the
1089// Properties.Get error case.
1090fn (m &Mpris) property_body(iface string, prop string, s &MprisSnapshot) ?PropBody {
1091 return m.property_table(iface, s)[prop]
1092}
1093
1094// property_table builds the property dictionary an interface serves: the
1095// root's static block, or the Player's from the snapshot.
1096fn (m &Mpris) property_table(iface string, s &MprisSnapshot) map[string]PropBody {
1097 mut table := map[string]PropBody{}
1098 if iface == mpris_root_iface {
1099 table['CanQuit'] = prop_bool(true)
1100 table['Fullscreen'] = prop_bool(false)
1101 table['CanSetFullscreen'] = prop_bool(false)
1102 table['CanRaise'] = prop_bool(false)
1103 table['HasTrackList'] = prop_bool(false)
1104 table['Identity'] = prop_string(dbus_type_string, 'Vendetta')
1105 table['DesktopEntry'] = prop_string(dbus_type_string, 'vendetta')
1106 // The spec wants URI schemes the player can open, not file
1107 // extensions, and prefers schemes over suffix lists.
1108 table['SupportedUriSchemes'] = prop_string_array(['file', 'http', 'https', 'ftp', 'rtsp',
1109 'srt', 'sftp'])
1110 table['SupportedMimeTypes'] = prop_string_array(['video/mp4', 'video/x-matroska', 'video/webm',
1111 'video/x-msvideo', 'video/quicktime', 'video/mpeg', 'audio/mpeg', 'audio/ogg', 'audio/flac',
1112 'audio/x-wav', 'audio/x-m4a', 'audio/aac'])
1113 return table
1114 }
1115 if iface != mpris_player_iface {
1116 return table
1117 }
1118 table['PlaybackStatus'] = prop_string(dbus_type_string, s.status)
1119 table['LoopStatus'] = prop_string(dbus_type_string, s.loop_status)
1120 table['Shuffle'] = prop_bool(s.shuffle)
1121 table['Metadata'] = m.metadata_body(s)
1122 table['Volume'] = prop_double(mpris_volume_fraction(s.volume))
1123 table['Rate'] = prop_double(if s.rate > 0 { s.rate } else { 1.0 })
1124 table['MinimumRate'] = prop_double(0.01)
1125 table['MaximumRate'] = prop_double(100.0)
1126 table['Position'] = prop_int(i64(s.position * 1_000_000.0))
1127 table['CanPlay'] = prop_bool(s.can_play)
1128 table['CanPause'] = prop_bool(s.can_pause)
1129 table['CanSeek'] = prop_bool(s.can_seek)
1130 table['CanControl'] = prop_bool(true)
1131 table['CanGoNext'] = prop_bool(s.can_go_next)
1132 table['CanGoPrevious'] = prop_bool(s.can_go_prev)
1133 return table
1134}
1135
1136// metadata_body builds the Metadata a{sv}: the fixed ids plus xesam fields
1137// filled from what mpv holds. An empty file contributes the empty
1138// dictionary, which is what the spec names for no track.
1139fn (m &Mpris) metadata_body(s &MprisSnapshot) PropBody {
1140 mut entries := []PropEntry{}
1141 if s.has_file {
1142 // The trackid is an object path that must change when the track
1143 // does; the playing file's URL under /org/vendetta/track serves.
1144 entries << PropEntry{
1145 key: 'mpris:trackid'
1146 value: prop_string(dbus_type_object_path, mpris_track_path(s.url))
1147 }
1148 entries << PropEntry{
1149 key: 'xesam:url'
1150 value: prop_string(dbus_type_string, s.url)
1151 }
1152 if s.title.len > 0 {
1153 entries << PropEntry{
1154 key: 'xesam:title'
1155 value: prop_string(dbus_type_string, s.title)
1156 }
1157 }
1158 if s.artist.len > 0 {
1159 entries << PropEntry{
1160 key: 'xesam:artist'
1161 value: prop_string_array([s.artist])
1162 }
1163 }
1164 if s.duration > 0 {
1165 entries << PropEntry{
1166 key: 'mpris:length'
1167 value: prop_int(i64(s.duration * 1_000_000.0))
1168 }
1169 }
1170 }
1171 return prop_dict(entries)
1172}
1173
1174// mpris_track_path names a track by a hash of its URL. An object path may
1175// only hold [A-Za-z0-9_] between slashes, so the URL itself cannot ride in it.
1176// The hash is stable for a URL, which is what SetPosition's stale check
1177// compares. No URL is the spec's NoTrack path, since an empty path is not a
1178// valid object path.
1179fn mpris_track_path(url string) string {
1180 if url.len == 0 {
1181 return '/org/mpris/MediaPlayer2/TrackList/NoTrack'
1182 }
1183 mut h := u64(0xcbf29ce484222325)
1184 for c in url.bytes() {
1185 h ^= u64(c)
1186 h *= u64(0x100000001b3)
1187 }
1188 return '/org/vendetta/track/${h:x}'
1189}
1190
1191// mpris_volume_fraction turns mpv's volume into the Volume the interface
1192// carries. mpv's 100 is unity gain, which the spec calls 1.0 (0 dB), so the
1193// desktop's percentage matches the app's own number whatever max the user
1194// set. The spec allows values above 1.0, so only the floor is clamped.
1195fn mpris_volume_fraction(volume f64) f64 {
1196 return math.max(0.0, volume / 100.0)
1197}
1198
1199// mpris_loop_code translates a LoopStatus value into the loop code the
1200// command carries: 0 none, 1 track, 2 playlist.
1201fn mpris_loop_code(name string) ?f64 {
1202 return match name {
1203 'None' { f64(0) }
1204 'Track' { f64(1) }
1205 'Playlist' { f64(2) }
1206 else { none }
1207 }
1208}
1209
1210// ── Seeked signal ───────────────────────────────────────────────────────────
1211
1212// emit_seeked sends a Seeked signal carrying the position in microseconds.
1213fn (mut m Mpris) emit_seeked(pos f64) {
1214 conn := m.conn
1215 if conn == unsafe { nil } {
1216 return
1217 }
1218 msg := C.dbus_message_new_signal(mpris_path.str, mpris_player_iface.str, c'Seeked')
1219 if msg == unsafe { nil } {
1220 return
1221 }
1222 // Seeked carries one x: the position the seek landed on. mpv's property
1223 // does not move until the seek completes, so the signal rides the
1224 // position property change that follows.
1225 mut iter := DBusMessageIter{}
1226 C.dbus_message_iter_init_append(msg, &iter)
1227 mut var := DBusMessageIter{}
1228 C.dbus_message_iter_open_container(&iter, dbus_type_variant, c'x', &var)
1229 pos_us := i64(pos * 1_000_000.0)
1230 C.dbus_message_iter_append_basic(&var, dbus_type_int64, voidptr(&pos_us))
1231 C.dbus_message_iter_close_container(&iter, &var)
1232 C.dbus_connection_send(conn, msg, unsafe { nil })
1233 C.dbus_message_unref(msg)
1234}
1235
1236// mpris_emit_diff emits the PropertiesChanged signals the move from last to
1237// next calls for. One signal per concern: playback state, capability flags.
1238// Desktops coalesce the bursts, and Metadata alone would otherwise arrive
1239// as half a dozen signals on a file change.
1240fn mpris_emit_diff(mut m Mpris, last &MprisSnapshot, next &MprisSnapshot) {
1241 mut changed := []PropEntry{}
1242 if last.status != next.status {
1243 changed << PropEntry{
1244 key: 'PlaybackStatus'
1245 value: prop_string(dbus_type_string, next.status)
1246 }
1247 // Position stays out of this signal: the spec says Position changes
1248 // do not emit PropertiesChanged, and clients read it on demand.
1249 }
1250 if last.loop_status != next.loop_status {
1251 changed << PropEntry{
1252 key: 'LoopStatus'
1253 value: prop_string(dbus_type_string, next.loop_status)
1254 }
1255 }
1256 if last.shuffle != next.shuffle {
1257 changed << PropEntry{
1258 key: 'Shuffle'
1259 value: prop_bool(next.shuffle)
1260 }
1261 }
1262 if mpris_volume_fraction(last.volume) != mpris_volume_fraction(next.volume) {
1263 changed << PropEntry{
1264 key: 'Volume'
1265 value: prop_double(mpris_volume_fraction(next.volume))
1266 }
1267 }
1268 if last.rate != next.rate {
1269 changed << PropEntry{
1270 key: 'Rate'
1271 value: prop_double(if next.rate > 0 { next.rate } else { 1.0 })
1272 }
1273 }
1274 // Metadata changes wholesale: trackid, title, artist, url and length
1275 // move together on a file change, and the empty file state empties the
1276 // dictionary.
1277 if last.has_file != next.has_file || last.url != next.url || last.title != next.title
1278 || last.artist != next.artist || last.duration != next.duration {
1279 changed << PropEntry{
1280 key: 'Metadata'
1281 value: m.metadata_body(next)
1282 }
1283 }
1284 if changed.len > 0 {
1285 m.emit_properties_changed(mpris_player_iface, mut changed, [])
1286 }
1287 // The capability flags move with the file state: a stop takes Play away,
1288 // a load brings it back, the playlist edges grey the step buttons.
1289 if last.has_file != next.has_file || last.can_play != next.can_play
1290 || last.can_pause != next.can_pause || last.can_seek != next.can_seek
1291 || last.can_go_next != next.can_go_next || last.can_go_prev != next.can_go_prev
1292 || last.playlist_pos != next.playlist_pos || last.playlist_len != next.playlist_len {
1293 mut caps := []PropEntry{}
1294 caps << PropEntry{ key: 'CanPlay', value: prop_bool(next.can_play) }
1295 caps << PropEntry{ key: 'CanPause', value: prop_bool(next.can_pause) }
1296 caps << PropEntry{ key: 'CanSeek', value: prop_bool(next.can_seek) }
1297 caps << PropEntry{ key: 'CanGoNext', value: prop_bool(next.can_go_next) }
1298 caps << PropEntry{ key: 'CanGoPrevious', value: prop_bool(next.can_go_prev) }
1299 m.emit_properties_changed(mpris_player_iface, mut caps, [])
1300 }
1301}
1302
1303// emit_properties_changed sends one PropertiesChanged signal: the interface,
1304// the changed properties as a{sv}, and the invalidated names as as. The
1305// signal rides the session bus to whoever subscribed.
1306fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry, _ []string) {
1307 conn := m.conn
1308 if conn == unsafe { nil } || changed.len == 0 {
1309 return
1310 }
1311 msg := C.dbus_message_new_signal(mpris_path.str, dbus_props_iface.str, c'PropertiesChanged')
1312 if msg == unsafe { nil } {
1313 return
1314 }
1315 mut iter := DBusMessageIter{}
1316 C.dbus_message_iter_init_append(msg, &iter)
1317 dbus_append_text(&iter, dbus_type_string, iface)
1318 // The changed dictionary.
1319 mut arr := DBusMessageIter{}
1320 mut opened := C.dbus_message_iter_open_container(&iter, dbus_type_array, c'{sv}', &arr)
1321 if opened == 0 {
1322 C.dbus_message_unref(msg)
1323 return
1324 }
1325 for mut entry in changed {
1326 mut de := DBusMessageIter{}
1327 opened = C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de)
1328 if opened == 0 {
1329 break
1330 }
1331 dbus_append_text(&de, dbus_type_string, entry.key)
1332 m.append_prop(&de, mut entry.value)
1333 C.dbus_message_iter_close_container(&arr, &de)
1334 }
1335 C.dbus_message_iter_close_container(&iter, &arr)
1336 // The invalidated array: empty, because every property here is reported
1337 // with its new value and nothing needs a re-read.
1338 mut inv := DBusMessageIter{}
1339 C.dbus_message_iter_open_container(&iter, dbus_type_array, c's', &inv)
1340 C.dbus_message_iter_close_container(&iter, &inv)
1341 C.dbus_connection_send(conn, msg, unsafe { nil })
1342 C.dbus_message_unref(msg)
1343}
1344
1345// ── Introspection ───────────────────────────────────────────────────────────
1346
1347// mpris_introspection_xml is the object's D-Bus introspection. Properties
1348// are listed on their interfaces; the signals and methods match what this
1349// file answers, so an introspecting desktop sees a complete MPRIS object.
1350fn mpris_introspection_xml() string {
1351 return '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
1352"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
1353<node>
1354 <interface name="org.freedesktop.DBus.Introspectable">
1355 <method name="Introspect">
1356 <arg direction="out" name="data" type="s"/>
1357 </method>
1358 </interface>
1359 <interface name="org.freedesktop.DBus.Properties">
1360 <method name="Get">
1361 <arg direction="in" name="interface" type="s"/>
1362 <arg direction="in" name="property" type="s"/>
1363 <arg direction="out" name="value" type="v"/>
1364 </method>
1365 <method name="Set">
1366 <arg direction="in" name="interface" type="s"/>
1367 <arg direction="in" name="property" type="s"/>
1368 <arg direction="in" name="value" type="v"/>
1369 </method>
1370 <method name="GetAll">
1371 <arg direction="in" name="interface" type="s"/>
1372 <arg direction="out" name="properties" type="a{sv}"/>
1373 </method>
1374 <signal name="PropertiesChanged">
1375 <arg name="interface" type="s"/>
1376 <arg name="changed_properties" type="a{sv}"/>
1377 <arg name="invalidated_properties" type="as"/>
1378 </signal>
1379 </interface>
1380 <interface name="org.mpris.MediaPlayer2">
1381 <method name="Raise"/>
1382 <method name="Quit"/>
1383 <property access="read" name="CanQuit" type="b"/>
1384 <property access="read" name="Fullscreen" type="b"/>
1385 <property access="read" name="CanSetFullscreen" type="b"/>
1386 <property access="read" name="CanRaise" type="b"/>
1387 <property access="read" name="HasTrackList" type="b"/>
1388 <property access="read" name="Identity" type="s"/>
1389 <property access="read" name="DesktopEntry" type="s"/>
1390 <property access="read" name="SupportedUriSchemes" type="as"/>
1391 <property access="read" name="SupportedMimeTypes" type="as"/>
1392 </interface>
1393 <interface name="org.mpris.MediaPlayer2.Player">
1394 <method name="Play"/>
1395 <method name="Pause"/>
1396 <method name="PlayPause"/>
1397 <method name="Stop"/>
1398 <method name="Next"/>
1399 <method name="Previous"/>
1400 <method name="Seek">
1401 <arg direction="in" name="Offset" type="x"/>
1402 </method>
1403 <method name="SetPosition">
1404 <arg direction="in" name="TrackId" type="o"/>
1405 <arg direction="in" name="Position" type="x"/>
1406 </method>
1407 <method name="OpenUri">
1408 <arg direction="in" name="Uri" type="s"/>
1409 </method>
1410 <signal name="Seeked">
1411 <arg name="Position" type="x"/>
1412 </signal>
1413 <property access="read" name="PlaybackStatus" type="s"/>
1414 <property access="readwrite" name="LoopStatus" type="s"/>
1415 <property access="readwrite" name="Shuffle" type="b"/>
1416 <property access="read" name="Metadata" type="a{sv}"/>
1417 <property access="readwrite" name="Volume" type="d"/>
1418 <property access="read" name="Rate" type="d"/>
1419 <property access="read" name="MinimumRate" type="d"/>
1420 <property access="read" name="MaximumRate" type="d"/>
1421 <property access="read" name="Position" type="x"/>
1422 <property access="read" name="CanControl" type="b"/>
1423 <property access="read" name="CanPlay" type="b"/>
1424 <property access="read" name="CanPause" type="b"/>
1425 <property access="read" name="CanSeek" type="b"/>
1426 <property access="read" name="CanGoNext" type="b"/>
1427 <property access="read" name="CanGoPrevious" type="b"/>
1428 </interface>
1429</node>'
1430}
1431