vendetta / src / player.v
2467 lines · 2387 sloc · 72.38 KB · 5c1ae2cbe8d0cfd767a2095c9bcc7636896d78a7
Raw
1import os
2import ui2
3import libvendetta
4import libvendetta.mpv
5import math
6import sokol.sapp
7import time
8
9// The app's observed property ids, as reply userdata on the widget's mpv
10// context. Both this app and the widget match property events by userdata on
11// the one context, so the id spaces must not overlap: the widget owns the low
12// ids (its observers at 1-9, its commands at 10-20 and 213), and these used
13// to sit at 7 and up — where aid events, read by the widget as its path
14// observer, replaced current_path with the audio track id. The seek preview
15// then spent every capture trying to loadfile that id as a file. The app's
16// observers start at 1000, above everything else either side numbers on this
17// context.
18const obs_aid = u64(1000)
19const obs_sid = u64(1001)
20const obs_vid = u64(1002)
21const obs_audio_device = u64(1003)
22const obs_ao = u64(1004)
23const obs_playlist_pos = u64(1005)
24
25// The media controls' own position observer. The widget observes time-pos
26// for its seek bar under its own id; the app needs the same events to
27// announce jumps as Seeked signals, which is a second observer on the
28// property, not a fight over one.
29const obs_mpris_pos = u64(1006)
30const obs_duration_mpris = u64(1007)
31const obs_mpris_volume = u64(1008)
32const obs_mpris_loop = u64(1009)
33const obs_mpris_loop_playlist = u64(1010)
34const obs_media_title = u64(1011)
35const obs_media_artist = u64(1012)
36
37// Playback statistics properties, observed for the statistics popup.
38const obs_fps = u64(1013)
39const obs_vf_fps = u64(1014)
40const obs_display_fps = u64(1015)
41const obs_avsync = u64(1016)
42const obs_avsync_change = u64(1017)
43const obs_vsync_jitter = u64(1018)
44const obs_vsync_ratio = u64(1019)
45const obs_video_speed_corr = u64(1020)
46const obs_audio_speed_corr = u64(1021)
47const obs_decoder_dropped = u64(1022)
48const obs_display_dropped = u64(1023)
49const obs_video_bitrate = u64(1024)
50const obs_audio_bitrate = u64(1025)
51const obs_cache_time = u64(1026)
52const obs_cache_duration = u64(1027)
53const obs_cache_buffering = u64(1028)
54const obs_video_w = u64(1029)
55const obs_video_h = u64(1030)
56const obs_hwdec_current = u64(1031)
57
58// mpv flags the menus show as toggles: their state is mpv's, read back
59// through the observed properties.
60const obs_interpolation = u64(1032)
61
62const obs_pitch_correction = u64(1033)
63
64const obs_audio_exclusive = u64(1034)
65
66// The picture-quality, dropping and pacing half of the menu flag set.
67const obs_video_sync = u64(1035)
68
69const obs_framedrop = u64(1036)
70
71const obs_fast_decode = u64(1037)
72
73const obs_correct_downscaling = u64(1038)
74
75const obs_linear_downscaling = u64(1039)
76
77const obs_sigmoid_upscaling = u64(1040)
78
79const obs_deband = u64(1041)
80
81const obs_dither = u64(1042)
82
83const obs_blend_subtitles = u64(1043)
84
85// Reply userdata on the player's mpv context. Almost every write is fire and
86// forget, and nothing matches its reply by id, so an id only says what the
87// write was for and a family may share one (the picture-quality writes all use
88// 97). The runtime option writes are the exception: option_written matches their
89// replies, so they take ids from opt_write_base up, and the queue's loadfile
90// appends count up from loadfile_base, out of reach of any queue. Matching a
91// reply by id anywhere else needs a range reserved here first.
92const opt_write_base = u64(1) << 32
93const loadfile_base = u64(1) << 20
94const option_unset_userdata = u64(86)
95
96// The hidden thumbnail instance's async command ids.
97const thumb_load_userdata = u64(210)
98const thumb_seek_userdata = u64(211)
99const thumb_shot_userdata = u64(212)
100
101// The thumbnail pipeline is short-lived; a stuck stage is abandoned after this.
102const thumb_state_loading = 1
103const thumb_state_seeking = 2
104const thumb_state_shooting = 3
105const thumb_timeout_ms = i64(4000)
106
107struct Track {
108 kind string
109 id string
110 label string
111 selected bool
112}
113
114struct AudioDevice {
115 name string
116 description string
117}
118
119struct Chapter {
120 title string
121 at f64
122}
123
124// Notice is one queued toast: the text, a serial that keys its element id,
125// and the dwell timer that removes it.
126struct Notice {
127 text string
128 serial u64
129 wake u64
130}
131
132// Player is vendetta's player. The embedded libvendetta widget owns the mpv
133// handle, the render path and the observed playback state; the rest is the
134// app's own state for menus, settings, the queue and statistics.
135struct Player {
136 libvendetta.Player
137mut:
138 tracks []Track
139 chapters []Chapter
140 devices []AudioDevice
141 audio_device string = 'auto'
142 // The audio server mpv's sound runs through: 'auto' leaves the choice to
143 // mpv's autoprobing, a name pins one. The observed 'ao' property keeps it
144 // in step with whatever wrote the option last.
145 ao string = 'auto'
146 sub_visible bool = true
147 sub_delay f64
148 audio_delay f64
149 aspect string = 'no'
150 rotate string = '0'
151 zoom f64
152 deinterlace bool
153 hwdec bool
154 // The pinned UI scale (View > UI scale). 0 follows the platform, which on
155 // Android means the phone-sized default in ui_scale_automatic.
156 ui_scale f64
157 // mpv flags the menus show as toggles. They mirror the observed
158 // properties, not vendetta's own idea of the state, and nothing writes them
159 // at start: until the user clicks, mpv's own defaults rule.
160 interpolation bool
161 pitch_correction bool
162 audio_exclusive bool
163 // More mpv flags the menus run as toggles and submenus: picture quality,
164 // frame dropping and sync pacing. Like the ones above, nothing writes
165 // them at start; the observers carry mpv's current values, and only a
166 // click or --mpv-opt changes them.
167 video_sync string
168 framedrop string
169 fast_decode bool
170 correct_downscaling bool
171 linear_downscaling bool
172 sigmoid_upscaling bool
173 deband bool
174 dither bool
175 blend_subtitles bool
176 loop_playlist bool
177 ab_a f64 = -1
178 ab_b f64 = -1
179 loop bool
180 max_volume_open bool
181 max_volume_text string
182 custom_open bool
183 // The File > Open URL... dialog: what is typed here is a link by
184 // construction, so it rides the same open path as the picker's files
185 // without any existence check.
186 url_open bool
187 url_text string
188 fullscreen bool
189 windowed_menu_hidden bool
190 fullscreen_menu_hidden bool = true
191 preview_visible bool
192 preview_time f64 = -1
193 preview_state int
194 preview_t0 i64
195 preview_index int
196 preview_pending_path string
197 preview_pending_time f64
198 preview_show_path string
199 preview_show_time f64
200 preview_show_w f64
201 preview_show_h f64
202 preview_over bool
203 thumb_path string
204 thumb_ctx voidptr
205 speed_text string
206 playlist []string
207 show_stats bool
208 show_queue bool
209 // The seek-bar hover preview. The thumbnail mpv instance behind it is
210 // only created while this is on: --no-preview or the saved setting
211 // keeps the second mpv core out of low-end machines entirely.
212 show_preview bool = true
213 // The notice queue: toasts over the video, each shown for notice_dwell
214 // seconds before it leaves.
215 notices []Notice
216 notice_serial u64
217 queue_open bool
218 queue_paths []string
219 queue []string
220 // The queue sidebar's reorder container: its controlled state, the
221 // generated keys behind the rows (paths can repeat, so they cannot name
222 // a row), the scroll feedback, and the frame the sidebar was last built
223 // with — the handlers rebuild rows from that same shape. See queue_config
224 // in view.v.
225 queue_state ui2.ReorderState
226 queue_keys []string
227 queue_scroll f64
228 queue_serial u64
229 queue_frame ui2.Rect
230 theme Theme
231 theme_name string = default_theme_name
232 // The theme editor panel: the theme the edits start from, the fields'
233 // texts, and each colour row's chooser.
234 theme_editor_open bool
235 theme_edit_base Theme
236 theme_edit_name string
237 theme_edit_texts map[string]string
238 theme_pickers map[string]ThemePicker
239 low_quality bool
240 // The window title's two halves, each the Options bar's own check row:
241 // the playback status is the '(paused)' suffix while the file is paused,
242 // and the playing file's name follows the app name after ' - '.
243 show_playback_status bool = true
244 show_title_filename bool = true
245 // The WM_CLASS write ran: sokol's X11 display exists only after its loop
246 // opens the window, and the write is once-per-session work.
247 window_class_set bool
248 // The window's redraw policy: with it on, ui2 repaints the retained tree
249 // every vsync and rebuilds on ask, so the seek bar glides and hovers
250 // answer within a frame. It is the View menu's Continuous redraw row, and
251 // performance mode takes it away until turned off.
252 continuous bool
253 last_frame_t0 i64
254 // The render thread (this one) must never wait on the mpv core while
255 // advanced control is on, so the track, chapter and device lists are read
256 // on a worker thread and arrive over this channel.
257 media_chan chan MediaData
258 media_read_busy bool
259 media_dirty bool
260 // A device-list read rented while a media read was in flight (see
261 // refresh_media_async): the next read carries the devices with it.
262 media_devices_wanted bool
263 // The thumbnail capture poll's ui2 timer: re-armed while a generation is
264 // in flight, so the on-demand loop asks for frames until it finishes.
265 thumb_wake u64
266 save_timer u64
267 // The settings file's text as last written, so an unchanged state is not
268 // written again (save_settings).
269 settings_text string
270 // The queue snapshot's debounced write timer (settings_changed's shape).
271 queue_timer u64
272 // Whether the restored queue still waits for the first frame to hand its
273 // entries to mpv's playlist without starting them (resume_pending_queue).
274 queue_resume_pending bool
275 // The statistics popup re-renders its numbers once a second through this
276 // timer. Between runs it keeps the previous frame scheduler snapshot, so
277 // the renderer line reports what the last period did, plus the heap sizes.
278 stats_wake u64
279 stats_last_callbacks u64
280 stats_last_builds u64
281 stats_last_draws u64
282 stats_last_coalesced u64
283 stats_callbacks u64
284 stats_builds u64
285 stats_draws u64
286 stats_coalesced u64
287 stats_heap u64
288 stats_unmapped u64
289 queue_name_open bool
290 queue_name_text string
291 // The save-playlist dialog's state: the queue save's shape writing an
292 // mpv-format m3u slot instead of a JSON queue file.
293 playlist_name_open bool
294 playlist_name_text string
295 open_mode string = 'ask'
296 want_fullscreen bool
297 // mpv options the user configured through --mpv-opt or the Options
298 // menu. They persist through the settings file and are mirrored into mpv
299 // on start, after everything mpv itself needs.
300 mpv_opts map[string]string
301 // Runtime option writes mpv has not answered yet, by their reply userdata
302 // (send_mpv_option, option_written).
303 opt_writes map[u64]OptionWrite
304 opt_write_serial u64
305 mpv_option_open bool
306 mpv_option_name_text string
307 mpv_option_value_text string
308 // Options presets: named bundles of the Options bar saved under
309 // ~/.config/vendetta/presets. The name records the preset applied last,
310 // so the menu can check it; the other two are the save dialog's state.
311 preset_name string
312 preset_name_open bool
313 preset_name_text string
314 // The desktop media controls (MPRIS): the service and its worker live
315 // here; nil means never started, media_controls is the on/off choice
316 // the setting and the menu row drive.
317 mpris &Mpris = unsafe { nil }
318 media_controls bool
319 // The media title and artist the metadata observers report, for the
320 // MPRIS Metadata dictionary.
321 media_title string
322 media_artist string
323 // Playback statistics observed from mpv, shown in the statistics popup.
324 hwdec_current string = '?'
325 video_w f64
326 video_h f64
327 container_fps f64
328 vf_fps f64
329 display_fps f64
330 avsync f64
331 avsync_change f64
332 vsync_jitter f64
333 vsync_ratio f64
334 video_speed_corr f64
335 audio_speed_corr f64
336 decoder_dropped f64
337 display_dropped f64
338 video_bitrate f64
339 audio_bitrate f64
340 cache_time f64
341 cache_duration f64
342 cache_buffering f64
343 windowed_overlay bool
344 fullscreen_overlay bool = true
345 playlist_index int
346}
347
348// update_window_title mirrors what mpv plays into the window title, in the
349// form 'Vendetta (paused) - filename': the pause suffix appears under the
350// Options bar's Show playback status row while playback is paused, and the
351// name is the file's own name for a local file or mpv's media-title for a
352// stream, shown under the Show filename row. With both rows off the title
353// stays plain 'Vendetta'. The media-title and pause property events run it,
354// so a file change and a pause flip repaint the title out of the mirrors the
355// observers already hold; neither call needs its own mpv read.
356fn (mut p Player) update_window_title() {
357 name := if !p.has_file {
358 ''
359 } else if p.current_kind == .file && p.current_path.len > 0 {
360 os.file_name(p.current_path)
361 } else {
362 p.media_title
363 }
364 mut title := 'Vendetta'
365 if p.show_playback_status && p.paused {
366 title += ' (paused)'
367 }
368 if p.show_title_filename && name.len > 0 {
369 title += ' - ' + name
370 }
371 apply_window_title(title)
372}
373
374// on_mpv_event follows the events the menus and lists show. The widget has
375// already taken the playback state from each one.
376fn (mut p Player) on_mpv_event(ev voidptr) {
377 match mpv.event_id(ev) {
378 mpv.event_file_loaded {
379 // The tracks and chapters follow the file; the device list does
380 // not (and its read would initialize the audio output here).
381 p.refresh_media_async(false)
382 // The playlist came together: the step flags and metadata
383 // follow, announced with the rest.
384 p.mpris_announce()
385 ui2.set_menu_bar(p.menus())
386 }
387 mpv.event_end_file {
388 p.tracks = []Track{}
389 p.chapters = []Chapter{}
390 p.ab_a = -1
391 p.ab_b = -1
392 // The file left: Stopped or the next file's state. The path
393 // property change announces what follows; an end without one
394 // (the last file stopped) still has to retract the metadata.
395 p.mpris_push()
396 ui2.set_menu_bar(p.menus())
397 }
398 mpv.event_property_change {
399 p.apply_app_property(ev)
400 }
401 mpv.event_set_property_reply {
402 p.option_written(ev)
403 }
404 mpv.event_seek {
405 p.mpris_seek_started()
406 }
407 mpv.event_playback_restart {
408 p.mpris_seek_landed()
409 }
410 else {}
411 }
412}
413
414// apply_app_property takes the properties the app shows in its menus and
415// statistics. The few it shares with the widget are read again here so the menus
416// refresh when they change.
417fn (mut p Player) apply_app_property(ev voidptr) {
418 name := mpv.property_name(ev)
419 $if debug_cadence ? {
420 eprintln('CAD prop ${name}')
421 }
422 match name {
423 'aid', 'sid', 'vid' {
424 // Track selections change the track list, not the devices.
425 p.refresh_media_async(false)
426 ui2.set_menu_bar(p.menus())
427 }
428 'audio-device' {
429 if v := mpv.property_string(ev) {
430 p.audio_device = v
431 ui2.set_menu_bar(p.menus())
432 }
433 }
434 'ao' {
435 if v := mpv.property_string(ev) {
436 // An empty list is mpv's autoprobing; the menu names that 'auto'.
437 p.ao = if v.len == 0 { 'auto' } else { v }
438 ui2.set_menu_bar(p.menus())
439 }
440 }
441 'pause' {
442 if v := mpv.property_flag(ev) {
443 $if debug_cadence ? {
444 eprintln('CAD pause=${v}')
445 }
446 p.paused = v
447 p.mpris_push()
448 p.update_window_title()
449 ui2.set_menu_bar(p.menus())
450 }
451 }
452 'mute' {
453 if v := mpv.property_flag(ev) {
454 p.muted = v
455 p.mpris_push()
456 ui2.set_menu_bar(p.menus())
457 }
458 }
459 'interpolation' {
460 if v := mpv.property_flag(ev) {
461 p.interpolation = v
462 ui2.set_menu_bar(p.menus())
463 }
464 }
465 'audio-pitch-correction' {
466 if v := mpv.property_flag(ev) {
467 p.pitch_correction = v
468 ui2.set_menu_bar(p.menus())
469 }
470 }
471 'audio-exclusive' {
472 if v := mpv.property_flag(ev) {
473 p.audio_exclusive = v
474 ui2.set_menu_bar(p.menus())
475 }
476 }
477 'video-sync' {
478 if v := mpv.property_string(ev) {
479 p.video_sync = v
480 ui2.set_menu_bar(p.menus())
481 }
482 }
483 'framedrop' {
484 if v := mpv.property_string(ev) {
485 p.framedrop = v
486 ui2.set_menu_bar(p.menus())
487 }
488 }
489 'vd-lavc-fast' {
490 if v := mpv.property_flag(ev) {
491 p.fast_decode = v
492 ui2.set_menu_bar(p.menus())
493 }
494 }
495 'correct-downscaling' {
496 if v := mpv.property_flag(ev) {
497 p.correct_downscaling = v
498 ui2.set_menu_bar(p.menus())
499 }
500 }
501 'linear-downscaling' {
502 if v := mpv.property_flag(ev) {
503 p.linear_downscaling = v
504 ui2.set_menu_bar(p.menus())
505 }
506 }
507 'sigmoid-upscaling' {
508 if v := mpv.property_flag(ev) {
509 p.sigmoid_upscaling = v
510 ui2.set_menu_bar(p.menus())
511 }
512 }
513 'deband' {
514 if v := mpv.property_flag(ev) {
515 p.deband = v
516 ui2.set_menu_bar(p.menus())
517 }
518 }
519 // The choice options arrive as strings; the menu needs the check
520 // semantics, which is "anything mpv holds that works".
521 'dither' {
522 if v := mpv.property_string(ev) {
523 p.dither = v != 'no'
524 ui2.set_menu_bar(p.menus())
525 }
526 }
527 'blend-subtitles' {
528 if v := mpv.property_string(ev) {
529 p.blend_subtitles = v != 'no'
530 ui2.set_menu_bar(p.menus())
531 }
532 }
533 'speed' {
534 if v := mpv.property_double(ev) {
535 p.speed = v
536 p.mpris_push()
537 ui2.set_menu_bar(p.menus())
538 }
539 }
540 'fps' {
541 if v := mpv.property_double(ev) {
542 p.container_fps = v
543 }
544 }
545 'video-params/w' {
546 if v := mpv.property_double(ev) {
547 p.video_w = v
548 }
549 }
550 'video-params/h' {
551 if v := mpv.property_double(ev) {
552 p.video_h = v
553 }
554 }
555 'hwdec-current' {
556 if v := mpv.property_string(ev) {
557 p.hwdec_current = v
558 }
559 }
560 'playlist-pos' {
561 if v := mpv.property_string(ev) {
562 p.playlist_index = v.int()
563 p.mpris_push()
564 }
565 }
566 // The media controls' position observer: jumps become Seeked
567 // signals, steady playback updates nothing (the desktop reads
568 // Position when it wants it).
569 'time-pos' {
570 if v := mpv.property_double(ev) {
571 p.mpris_on_position(v)
572 }
573 }
574 'duration' {
575 if v := mpv.property_double(ev) {
576 p.mpris_push()
577 }
578 }
579 'volume' {
580 if v := mpv.property_double(ev) {
581 // The write the property reports is mpv's truth, so the
582 // player's mirror follows it too (the strip slider writes
583 // through mpv, not through the app).
584 p.volume = v
585 p.mpris_push()
586 }
587 }
588 'loop-file' {
589 p.mpris_push()
590 }
591 'loop-playlist' {
592 p.mpris_push()
593 }
594 'media-title' {
595 if v := mpv.property_string(ev) {
596 p.media_title = v
597 p.mpris_push()
598 p.update_window_title()
599 }
600 }
601 'metadata/by-key/artist' {
602 p.media_artist = mpv.property_string(ev) or { '' }
603 p.mpris_push()
604 }
605 'estimated-vf-fps' {
606 if v := mpv.property_double(ev) {
607 p.vf_fps = v
608 }
609 }
610 'estimated-display-fps' {
611 if v := mpv.property_double(ev) {
612 p.display_fps = v
613 }
614 }
615 'avsync' {
616 if v := mpv.property_double(ev) {
617 p.avsync = v
618 }
619 }
620 'total-avsync-change' {
621 if v := mpv.property_double(ev) {
622 p.avsync_change = v
623 }
624 }
625 'vsync-jitter' {
626 if v := mpv.property_double(ev) {
627 p.vsync_jitter = v
628 }
629 }
630 'vsync-ratio' {
631 if v := mpv.property_double(ev) {
632 p.vsync_ratio = v
633 }
634 }
635 'video-speed-correction' {
636 if v := mpv.property_double(ev) {
637 p.video_speed_corr = v
638 }
639 }
640 'audio-speed-correction' {
641 if v := mpv.property_double(ev) {
642 p.audio_speed_corr = v
643 }
644 }
645 'decoder-frame-drop-count' {
646 if v := mpv.property_double(ev) {
647 p.decoder_dropped = v
648 }
649 }
650 'drop-frame-count' {
651 if v := mpv.property_double(ev) {
652 p.display_dropped = v
653 }
654 }
655 'video-bitrate' {
656 if v := mpv.property_double(ev) {
657 p.video_bitrate = v / 1000
658 }
659 }
660 'audio-bitrate' {
661 if v := mpv.property_double(ev) {
662 p.audio_bitrate = v / 1000
663 }
664 }
665 'demuxer-cache-time' {
666 if v := mpv.property_double(ev) {
667 p.cache_time = v
668 }
669 }
670 'demuxer-cache-duration' {
671 if v := mpv.property_double(ev) {
672 p.cache_duration = v
673 }
674 }
675 'cache-buffering-state' {
676 if v := mpv.property_double(ev) {
677 p.cache_buffering = v
678 }
679 }
680 'path' {
681 if v := mpv.property_string(ev) {
682 p.current_path = v
683 if v.len > 0 {
684 p.load_thumb_file()
685 }
686 // A new file means new metadata; the service announces it
687 // all, capability flags included.
688 p.mpris_announce()
689 }
690 }
691 else {}
692 }
693}
694
695// queue_new_key returns the next key a queue row is named with. The queue can
696// hold the same path twice, so the paths themselves cannot be the keys; a
697// monotonic serial is unique for the run and stable as rows swap places.
698fn (mut p Player) queue_new_key() string {
699 p.queue_serial++
700 return '${p.queue_serial}'
701}
702
703// queue_reset_keys re-keys the queue wholesale: load_paths replaced every
704// entry, so old keys — and with them the drag and keyboard cursor state —
705// mean nothing anymore.
706fn (mut p Player) queue_reset_keys() {
707 p.queue_keys = []string{cap: p.queue.len}
708 p.queue_state = ui2.ReorderState{}
709 p.queue_scroll = 0
710 for _ in 0 .. p.queue.len {
711 p.queue_keys << p.queue_new_key()
712 }
713}
714
715// queue_index finds a queue row by its key; -1 when the row is gone.
716fn (p &Player) queue_index(key string) int {
717 return p.queue_keys.index(key)
718}
719
720// queue_apply_step stores what a drag or an Alt-key move did and applies the
721// move: the queue array and its row keys shift the same way, mpv's playlist —
722// whose order the sidebar mirrors — moves the same one entry, and the playlist
723// mirror follows so the desktop tracklist reads the new order.
724fn (mut p Player) queue_apply_step(step ui2.ReorderStep) {
725 p.queue_state = step.state
726 if !step.moved {
727 return
728 }
729 p.queue = ui2.reorder_move(p.queue, step.from, step.to)
730 p.queue_keys = ui2.reorder_move(p.queue_keys, step.from, step.to)
731 // mpv counts the move target before the entry is taken out, so a move
732 // down needs one more: queue_up_ kept its plain target for a step up,
733 // queue_down_ moved to index + 2 for a from -> from + 1. A key move and
734 // a drag land the same way here.
735 target := if step.to > step.from { step.to + 1 } else { step.to }
736 mpv.command_async(p.mpv_ctx, u64(84), ['playlist-move', '${step.from}', '${target}'])
737 // The mirror follows the queue's new order; the playing position ripples
738 // in through the playlist-pos observer on its own.
739 p.playlist = p.queue.clone()
740 p.queue_state_changed()
741 $if debug_cadence ? {
742 eprintln('CAD queue_move from=${step.from} to=${step.to} target=${target} qlen=${p.queue.len} key=${step.state.active}')
743 }
744}
745
746// queue_state_changed schedules the queue snapshot a second out, cancelling
747// a pending one, so a burst of queue changes (a drag, a run of row removals)
748// writes once, the way settings_changed debounces the settings file.
749fn (mut p Player) queue_state_changed() {
750 if p.queue_timer != 0 {
751 ui2.cancel_timer(p.queue_timer)
752 }
753 p.queue_timer = ui2.after(1, fn [mut p] () {
754 p.save_queue_state()
755 })
756}
757
758// restore_queue replaces the app-side queue with a saved snapshot: fresh row
759// keys, the MPRIS and tracklist mirror brought along, and mpv's own playlist
760// left for the first frame — resume_pending_queue hands the entries over
761// there. The command line wins over the snapshot (see main's start), so a
762// start with files passed on it drops the restored list.
763fn (mut p Player) restore_queue(paths []string) {
764 mut kept := []string{}
765 for path in paths {
766 // A file that left the disk between sessions loses its row instead of
767 // hanging on as a dead entry; links have nothing to check.
768 if libvendetta.source_kind(path) == .link || os.exists(path) {
769 kept << path
770 }
771 }
772 if kept.len == 0 {
773 return
774 }
775 p.queue = kept.clone()
776 p.queue_reset_keys()
777 p.playlist = p.queue.clone()
778 p.queue_resume_pending = true
779}
780
781// resume_pending_queue hands the restored queue to mpv on the first frame:
782// playlist-clear, then one plain append per entry. append never starts
783// playback — append-play would begin the first file — so the queue comes
784// back silent and mpv's position stays unset until a row is clicked or a
785// later file serves the entry. The flag fires exactly once.
786fn (mut p Player) resume_pending_queue() {
787 if !p.queue_resume_pending || p.render_ctx == unsafe { nil } {
788 return
789 }
790 p.queue_resume_pending = false
791 mpv.command_async(p.mpv_ctx, u64(80), ['playlist-clear'])
792 for index, file in p.queue {
793 mpv.command_async(p.mpv_ctx, loadfile_base + u64(index), ['loadfile', file, 'append'])
794 }
795}
796
797// queue_key moves the cursor's row with Alt+the arrows or Home / End, the
798// same move a drag performs. It stays quiet when the sidebar is closed or
799// the queue is empty, so the menu-bar Alt toggle and the playback keys keep
800// theirs.
801fn (mut p Player) queue_key(ev ui2.KeyEvent) ?ui2.ReorderStep {
802 if !p.show_queue || p.queue.len == 0 {
803 return none
804 }
805 step := ui2.reorder_key(p.queue_config(), ev)?
806 p.queue_apply_step(step)
807 return step
808}
809
810// handle runs for every window event. Nothing here waits for mpv.
811fn (mut p Player) handle(event string) {
812 if event.starts_with('vd_') {
813 p.Player.handle(event)
814 return
815 }
816 $if debug_cadence ? {
817 if event.starts_with('queue_') {
818 eprintln('CAD queue ${event} len=${p.queue.len} pos=${p.playlist_index}')
819 }
820 }
821 // The queue sidebar's rows take their drags through the reorder container
822 // before anything else looks at a pointer event. A step rebuilds with the
823 // sidebar (and drifts through mpv) on the frame every event already asks
824 // for; other pointer events leave it untouched.
825 if event.starts_with('pointer:') && p.show_queue && p.queue.len > 0 {
826 if step := ui2.reorder_update(p.queue_config(), event) {
827 p.queue_apply_step(step)
828 }
829 return
830 }
831 if p.handle_media(event) {
832 return
833 }
834 match event {
835 'playback_speed_custom' {
836 p.speed_text = '${p.speed:.2f}'
837 p.custom_open = true
838 return
839 }
840 'speed_cancel' {
841 p.custom_open = false
842 return
843 }
844 'volume_max_custom' {
845 p.max_volume_text = '${p.max_volume:.0f}'
846 p.max_volume_open = true
847 return
848 }
849 'max_volume_cancel' {
850 p.max_volume_open = false
851 return
852 }
853 'max_volume_apply' {
854 v := ui2.text('max_volume_input').trim_space().f64()
855 if v > 0 && v <= 1000 {
856 p.max_volume = v
857 if p.volume > p.max_volume {
858 p.volume = p.max_volume
859 mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume)
860 }
861 p.max_volume_open = false
862 p.clear_notices()
863 p.settings_changed()
864 ui2.set_menu_bar(p.menus())
865 } else {
866 p.notify('Max volume must be between 1 and 1000.')
867 }
868 return
869 }
870 'speed_apply' {
871 speed := ui2.text('speed_input').trim_space().f64()
872 if speed >= 0.01 && speed <= 100 {
873 mpv.set_double_async(p.mpv_ctx, 19, 'speed', speed)
874 p.custom_open = false
875 p.clear_notices()
876 } else {
877 p.notify('Speed must be between 0.01 and 100.')
878 }
879 return
880 }
881 else {}
882 }
883 if event.starts_with('playback_speed:') {
884 speed := event.all_after('playback_speed:').f64()
885 mpv.set_double_async(p.mpv_ctx, 17, 'speed', speed)
886 return
887 }
888 if event.starts_with('queue_rm_') {
889 // The row keys name the events, so the index is read from the queue
890 // as it stands now: a build cannot have reordered between the row's
891 // draw and the press.
892 key := event.all_after('queue_rm_')
893 index := p.queue_index(key)
894 if index >= 0 {
895 p.queue.delete(index)
896 p.queue_keys.delete(index)
897 // No row left for the drag or the keyboard cursor to sit on.
898 if p.queue_state.active == key {
899 p.queue_state = ui2.ReorderState{}
900 }
901 mpv.command_async(p.mpv_ctx, u64(83), ['playlist-remove', '${index}'])
902 // The mirror follows the queue's new order (see queue_move).
903 p.playlist = p.queue.clone()
904 p.queue_state_changed()
905 }
906 $if debug_cadence ? {
907 eprintln('CAD queue_rm key=${key} idx=${index} qlen=${p.queue.len}')
908 }
909 return
910 }
911 if event.starts_with('theme:') {
912 p.set_theme(event.all_after('theme:'))
913 ui2.set_menu_bar(p.menus())
914 return
915 }
916 if event.starts_with('theme_edit:') {
917 p.open_theme_editor(event.all_after('theme_edit:'))
918 ui2.set_menu_bar(p.menus())
919 return
920 }
921 if event.starts_with('theme_delete:') {
922 name := event.all_after('theme_delete:')
923 os.rm(os.join_path(theme_dir(), '${name}.toml')) or {}
924 if p.theme_name == name {
925 p.set_theme(default_theme_name)
926 }
927 ui2.set_menu_bar(p.menus())
928 return
929 }
930 if p.theme_editor_open && p.handle_theme_picker_event(event) {
931 return
932 }
933 if event == 'theme_save' {
934 p.save_theme_from_editor()
935 return
936 }
937 if event == 'theme_name_input' {
938 p.theme_edit_name = ui2.text(event)
939 return
940 }
941 if event.starts_with('theme_color_input_') {
942 p.theme_edit_texts[event.all_after('theme_color_input_')] = ui2.text(event)
943 p.theme_editor_preview()
944 return
945 }
946 if event == 'view_theme_editor' {
947 p.theme_editor_open = !p.theme_editor_open
948 if p.theme_editor_open && p.theme_edit_texts.len == 0 {
949 p.open_theme_editor(p.theme_name)
950 }
951 ui2.set_menu_bar(p.menus())
952 return
953 }
954 if event.starts_with('open_mode:') {
955 p.open_mode = event.all_after('open_mode:')
956 ui2.set_menu_bar(p.menus())
957 return
958 }
959 if event.starts_with('ui_scale:') {
960 p.ui_scale = event.all_after('ui_scale:').f64()
961 p.apply_ui_scale()
962 p.settings_changed()
963 ui2.set_menu_bar(p.menus())
964 return
965 }
966 if event.starts_with('queue_load:') {
967 name := event.all_after('queue_load:')
968 if paths := load_queue_file(name) {
969 p.load_paths(paths)
970 p.clear_notices()
971 } else {
972 p.notify('Could not load the queue ${name}.')
973 }
974 return
975 }
976 if event.starts_with('queue_delete:') {
977 name := event.all_after('queue_delete:')
978 os.rm(os.join_path(queues_dir(), '${name}.json')) or {}
979 ui2.set_menu_bar(p.menus())
980 return
981 }
982 if event.starts_with('playlist_load:') {
983 name := event.all_after('playlist_load:')
984 if paths := load_playlist_file(name) {
985 if paths.len == 0 {
986 p.notify('The playlist ${name} is empty.')
987 } else {
988 p.load_paths(paths)
989 }
990 } else {
991 p.notify('Could not load the playlist ${name}.')
992 }
993 return
994 }
995 if event.starts_with('playlist_append:') {
996 name := event.all_after('playlist_append:')
997 if paths := load_playlist_file(name) {
998 if paths.len == 0 {
999 p.notify('The playlist ${name} is empty.')
1000 } else {
1001 p.add_to_queue(paths)
1002 }
1003 } else {
1004 p.notify('Could not load the playlist ${name}.')
1005 }
1006 return
1007 }
1008 if event.starts_with('playlist_delete:') {
1009 name := event.all_after('playlist_delete:')
1010 os.rm(os.join_path(playlists_dir(), '${name}.m3u')) or {}
1011 ui2.set_menu_bar(p.menus())
1012 return
1013 }
1014 if event.starts_with('mpv_option_edit:') {
1015 name := event.all_after('mpv_option_edit:')
1016 p.mpv_option_name_text = name
1017 p.mpv_option_value_text = p.mpv_opts[name] or { '' }
1018 p.mpv_option_open = true
1019 return
1020 }
1021 if event.starts_with('mpv_option_reset:') {
1022 name := event.all_after('mpv_option_reset:')
1023 p.unset_mpv_option(name)
1024 p.clear_notices()
1025 p.settings_changed()
1026 ui2.set_menu_bar(p.menus())
1027 return
1028 }
1029 if event.starts_with('preset:') {
1030 p.apply_preset(event.all_after('preset:'))
1031 ui2.set_menu_bar(p.menus())
1032 return
1033 }
1034 if event.starts_with('preset_delete:') {
1035 name := event.all_after('preset_delete:')
1036 os.rm(os.join_path(presets_dir(), '${name}.json')) or {}
1037 if p.preset_name == name {
1038 p.preset_name = ''
1039 p.settings_changed()
1040 }
1041 ui2.set_menu_bar(p.menus())
1042 return
1043 }
1044 // The sync and dropping submenus pick mpv values outright; the observer
1045 // walks the state back once the core takes the write.
1046 if event.starts_with('video_sync:') {
1047 mpv.set_string_async(p.mpv_ctx, 94, 'video-sync', event.all_after('video_sync:'))
1048 return
1049 }
1050 if event.starts_with('framedrop:') {
1051 mpv.set_string_async(p.mpv_ctx, 95, 'framedrop', event.all_after('framedrop:'))
1052 return
1053 }
1054 match event {
1055 'queue_play_now' {
1056 p.queue_open = false
1057 p.load_paths(p.queue_paths.clone())
1058 }
1059 'queue_add' {
1060 p.queue_open = false
1061 p.add_to_queue(p.queue_paths.clone())
1062 }
1063 'queue_cancel' {
1064 p.queue_open = false
1065 }
1066 'queue_save' {
1067 if p.queue.len == 0 {
1068 p.notify('The queue is empty.')
1069 } else {
1070 p.queue_name_text = ''
1071 p.queue_name_open = true
1072 }
1073 }
1074 'playlist_save' {
1075 if p.queue.len == 0 {
1076 p.notify('The queue is empty.')
1077 } else {
1078 p.playlist_name_text = ''
1079 p.playlist_name_open = true
1080 }
1081 }
1082 'playlist_name_apply' {
1083 if p.save_playlist(ui2.text('playlist_name_input')) {
1084 p.playlist_name_open = false
1085 p.clear_notices()
1086 ui2.set_menu_bar(p.menus())
1087 }
1088 }
1089 'playlist_name_cancel' {
1090 p.playlist_name_open = false
1091 }
1092 'queue_clear' {
1093 p.queue = []string{}
1094 // No row is left for the drag or the keyboard cursor to sit on.
1095 p.queue_keys = []string{}
1096 p.queue_state = ui2.ReorderState{}
1097 p.queue_scroll = 0
1098 // The mirror follows: the desktop's tracklist reads the playlist.
1099 p.playlist = p.queue.clone()
1100 p.queue_state_changed()
1101 p.notify('Queue cleared.')
1102 p.settings_changed()
1103 ui2.set_menu_bar(p.menus())
1104 }
1105 'queue_name_apply' {
1106 if p.save_queue(ui2.text('queue_name_input')) {
1107 p.queue_name_open = false
1108 p.clear_notices()
1109 ui2.set_menu_bar(p.menus())
1110 }
1111 }
1112 'queue_name_cancel' {
1113 p.queue_name_open = false
1114 }
1115 'mpv_option' {
1116 // Options > Set option...: an empty dialog that
1117 // takes any mpv option name and value.
1118 p.mpv_option_name_text = ''
1119 p.mpv_option_value_text = ''
1120 p.mpv_option_open = true
1121 }
1122 'mpv_option_cancel' {
1123 p.mpv_option_open = false
1124 }
1125 'mpv_option_apply' {
1126 name := ui2.text('mpv_opt_name_input').trim_space()
1127 value := ui2.text('mpv_opt_value_input')
1128 if name.len == 0 {
1129 p.notify('Type an mpv option name, like cache or demuxer-max-bytes.')
1130 return
1131 }
1132 p.clear_notices()
1133 // An empty value unsets the option: it leaves the configured set,
1134 // so it stops being re-applied from the saved settings too.
1135 if value.len == 0 {
1136 p.unset_mpv_option(name)
1137 p.mpv_option_open = false
1138 p.settings_changed()
1139 ui2.set_menu_bar(p.menus())
1140 return
1141 }
1142 // The dialog stays open until mpv answers: a rejection is reported
1143 // there, and the typed name and value stay put for a correction.
1144 p.send_mpv_option(OptionWrite{
1145 name: name
1146 value: value
1147 })
1148 }
1149 'preset_save' {
1150 // Options > Presets > Save current options...: the name starts
1151 // from the preset applied last, so saving again overwrites it.
1152 p.preset_name_text = p.preset_name
1153 p.preset_name_open = true
1154 }
1155 'preset_name_cancel' {
1156 p.preset_name_open = false
1157 }
1158 'preset_name_apply' {
1159 if p.save_preset(ui2.text('preset_name_input')) {
1160 p.preset_name_open = false
1161 ui2.set_menu_bar(p.menus())
1162 }
1163 }
1164 'file_open' {
1165 p.open_dialog()
1166 }
1167 'open_url' {
1168 // Every open starts from an empty field, like the saved-queue
1169 // and preset name dialogs do.
1170 p.url_text = ''
1171 p.url_open = true
1172 }
1173 'url_cancel' {
1174 p.url_open = false
1175 }
1176 'url_apply' {
1177 url := ui2.text('url_input').trim_space()
1178 if url.len == 0 {
1179 p.notify('Type a link, protocol prefix included, like https://.')
1180 return
1181 }
1182 if libvendetta.source_kind(url) != .link {
1183 p.notify('That is not a link: type a protocol prefix, like https://.')
1184 return
1185 }
1186 p.url_open = false
1187 p.clear_notices()
1188 // The typed link walks the same open path the picker's entries
1189 // do, so Default open — ask, play now, add to queue — rules
1190 // here as well.
1191 p.load_or_prompt([url])
1192 }
1193 'view_fullscreen' {
1194 p.toggle_fullscreen()
1195 }
1196 'view_statistics' {
1197 p.set_show_stats(!p.show_stats)
1198 ui2.set_menu_bar(p.menus())
1199 }
1200 'view_preview' {
1201 p.set_show_preview(!p.show_preview)
1202 ui2.set_menu_bar(p.menus())
1203 }
1204 'view_smooth_bar' {
1205 p.smooth_bar = !p.smooth_bar
1206 ui2.set_menu_bar(p.menus())
1207 }
1208 'title_status' {
1209 p.show_playback_status = !p.show_playback_status
1210 p.update_window_title()
1211 ui2.set_menu_bar(p.menus())
1212 }
1213 'title_filename' {
1214 p.show_title_filename = !p.show_title_filename
1215 p.update_window_title()
1216 ui2.set_menu_bar(p.menus())
1217 }
1218 'view_continuous' {
1219 p.set_continuous(!p.continuous)
1220 ui2.set_menu_bar(p.menus())
1221 }
1222 'view_queue' {
1223 p.show_queue = !p.show_queue
1224 ui2.set_menu_bar(p.menus())
1225 }
1226 'view_low_quality' {
1227 p.low_quality = !p.low_quality
1228 if p.low_quality {
1229 // Performance mode is the redraw budget's backstop: it takes
1230 // the continuous redraw away until it is turned off.
1231 p.set_continuous(false)
1232 p.notify('Performance mode: heavy rendering steps are skipped when frames run late.')
1233 } else {
1234 p.clear_notices()
1235 }
1236 ui2.set_menu_bar(p.menus())
1237 }
1238 'media_controls' {
1239 p.set_media_controls(!p.media_controls)
1240 }
1241 'playback_mute' {
1242 mpv.set_flag_async(p.mpv_ctx, 16, 'mute', !p.muted)
1243 }
1244 'playback_loop' {
1245 p.toggle_loop()
1246 }
1247 // The mpv flag toggles write the opposite of what mpv reports and
1248 // leave the state to the observed properties; nothing is written for
1249 // a flag the user never touches, so mpv's defaults rule untouched.
1250 'video_interpolation' {
1251 mpv.set_flag_async(p.mpv_ctx, 90, 'interpolation', !p.interpolation)
1252 }
1253 'audio_pitch_correction' {
1254 mpv.set_flag_async(p.mpv_ctx, 91, 'audio-pitch-correction', !p.pitch_correction)
1255 }
1256 'audio_exclusive' {
1257 mpv.set_flag_async(p.mpv_ctx, 92, 'audio-exclusive', !p.audio_exclusive)
1258 }
1259 // Subtitle size rides the sub-scale property: relative adds below,
1260 // and the reset writes mpv's own default for --sub-scale (1).
1261 'sub_scale_up' {
1262 mpv.command_async(p.mpv_ctx, 93, ['add', 'sub-scale', '0.1'])
1263 }
1264 'sub_scale_down' {
1265 mpv.command_async(p.mpv_ctx, 93, ['add', 'sub-scale', '-0.1'])
1266 }
1267 'sub_scale_reset' {
1268 mpv.command_async(p.mpv_ctx, 93, ['set', 'sub-scale', '1'])
1269 }
1270 // Picture quality on mpv's own terms: toggles write the opposite of
1271 // what mpv reports; the choice options flip between off and the value
1272 // mpv itself has as default (dither's algorithm, subtitle blending).
1273 'quality_deband' {
1274 mpv.set_flag_async(p.mpv_ctx, 96, 'deband', !p.deband)
1275 }
1276 'quality_dither' {
1277 mpv.set_string_async(p.mpv_ctx, 97, 'dither', if p.dither { 'no' } else { 'fruit' })
1278 }
1279 'quality_correct_down' {
1280 mpv.set_flag_async(p.mpv_ctx, 97, 'correct-downscaling', !p.correct_downscaling)
1281 }
1282 'quality_linear_down' {
1283 mpv.set_flag_async(p.mpv_ctx, 97, 'linear-downscaling', !p.linear_downscaling)
1284 }
1285 'quality_sigmoid_up' {
1286 mpv.set_flag_async(p.mpv_ctx, 97, 'sigmoid-upscaling', !p.sigmoid_upscaling)
1287 }
1288 'quality_blend_subs' {
1289 mpv.set_string_async(p.mpv_ctx, 97, 'blend-subtitles', if p.blend_subtitles {
1290 'no'
1291 } else {
1292 'yes'
1293 })
1294 }
1295 'video_fast_decode' {
1296 mpv.set_flag_async(p.mpv_ctx, 98, 'vd-lavc-fast', !p.fast_decode)
1297 }
1298 'render_wait_vsync' {
1299 // Presentation pacing is vendetta's render call, not an mpv property:
1300 // the flip changes what the next render asks mpv for.
1301 p.cfg.block_target_time = !p.cfg.block_target_time
1302 ui2.set_menu_bar(p.menus())
1303 }
1304 'file_close' {
1305 p.close_file()
1306 }
1307 else {}
1308 }
1309}
1310
1311// handle_key gives keyboard shortcuts the same meaning as in mpc-qt's defaults.
1312fn (mut p Player) handle_key(key string) {
1313 $if debug_cadence ? {
1314 eprintln('CAD key: [${key}] te=${p.theme_editor_open} co=${p.custom_open} mo=${p.mpv_option_open} po=${p.preset_name_open} fs=${p.fullscreen}')
1315 }
1316 // While the theme editor is open its fields get the keys, so none of the
1317 // shortcuts apply; Escape closes the editor.
1318 if p.theme_editor_open {
1319 if key == 'escape' {
1320 p.handle('view_theme_editor')
1321 }
1322 return
1323 }
1324 // While the speed dialog is open its text field gets the keys, so none of the
1325 // shortcuts apply; Escape closes the dialog.
1326 if p.custom_open {
1327 if key == 'escape' {
1328 p.custom_open = false
1329 }
1330 return
1331 }
1332 // The mpv option dialog is the same: typing an option name or value must
1333 // not pause the file or open panels behind the user's back. Its Apply
1334 // button and the submit of the value field drive the same mpv_option_apply
1335 // event, so keys need no more handling here.
1336 if p.mpv_option_open {
1337 if key == 'escape' {
1338 p.mpv_option_open = false
1339 }
1340 return
1341 }
1342 // The preset name dialog is the same: naming a preset must not pause the
1343 // file. Its Save button and the input's submit drive preset_name_apply.
1344 if p.preset_name_open {
1345 if key == 'escape' {
1346 p.preset_name_open = false
1347 }
1348 return
1349 }
1350 // The save-url dialog is the same: typing a link must not pause the file
1351 // or work the panels behind it. Its Open button and the input's submit
1352 // drive url_apply.
1353 if p.url_open {
1354 if key == 'escape' {
1355 p.url_open = false
1356 }
1357 return
1358 }
1359 // The save-queue and save-playlist dialogs are the same: naming a
1360 // collection must not pause the file. The playlist name dialog sits with
1361 // the queue save's shape, so both take the guard the other open dialogs
1362 // carry — without it a typed m would mute behind the dialog.
1363 if p.queue_name_open {
1364 if key == 'escape' {
1365 p.queue_name_open = false
1366 }
1367 return
1368 }
1369 if p.playlist_name_open {
1370 if key == 'escape' {
1371 p.playlist_name_open = false
1372 }
1373 return
1374 }
1375 if p.fullscreen && key == 'escape' {
1376 p.toggle_fullscreen()
1377 return
1378 }
1379 match key {
1380 'f' {
1381 p.toggle_fullscreen()
1382 }
1383 ' ' {
1384 rc := mpv.set_flag_async(p.mpv_ctx, 10, 'pause', !p.paused)
1385 $if debug_cadence ? {
1386 eprintln('CAD space rc=${rc} paused_was=${p.paused}')
1387 }
1388 }
1389 'left', 'right' {
1390 p.media_key(key)
1391 }
1392 'up' {
1393 mpv.set_double_async(p.mpv_ctx, 12, 'volume', if p.volume + 5 > p.max_volume {
1394 p.max_volume
1395 } else {
1396 p.volume + 5
1397 })
1398 p.mpris_on_volume()
1399 }
1400 'down' {
1401 mpv.set_double_async(p.mpv_ctx, 12, 'volume', if p.volume - 5 < 0 {
1402 0
1403 } else {
1404 p.volume - 5
1405 })
1406 p.mpris_on_volume()
1407 }
1408 'm' {
1409 mpv.set_flag_async(p.mpv_ctx, 16, 'mute', !p.muted)
1410 }
1411 'i' {
1412 p.set_show_stats(!p.show_stats)
1413 ui2.set_menu_bar(p.menus())
1414 }
1415 'q' {
1416 p.show_queue = !p.show_queue
1417 ui2.set_menu_bar(p.menus())
1418 }
1419 't' {
1420 p.handle('view_theme_editor')
1421 }
1422 'o' {
1423 p.toggle_overlay()
1424 ui2.set_menu_bar(p.menus())
1425 }
1426 'l' {
1427 p.toggle_loop()
1428 }
1429 'ctrl+o' {
1430 p.open_dialog()
1431 }
1432 'ctrl+u' {
1433 p.handle('open_url')
1434 }
1435 'ctrl+w' {
1436 p.close_file()
1437 }
1438 'ctrl+=' {
1439 p.zoom_by(0.25)
1440 }
1441 'ctrl+-' {
1442 p.zoom_by(-0.25)
1443 }
1444 else {
1445 p.media_key(key)
1446 }
1447 }
1448}
1449
1450// menu_hidden reports whether the menu bar is hidden in the current mode.
1451fn (p &Player) menu_hidden() bool {
1452 return if p.fullscreen { p.fullscreen_menu_hidden } else { p.windowed_menu_hidden }
1453}
1454
1455// set_menu_hidden shows or hides the menu bar for the current mode.
1456fn (mut p Player) set_menu_hidden(hidden bool) {
1457 if p.fullscreen {
1458 p.fullscreen_menu_hidden = hidden
1459 } else {
1460 p.windowed_menu_hidden = hidden
1461 }
1462 ui2.set_menu_bar_hidden(hidden)
1463}
1464
1465// pointer_moved wakes the controls and the cursor. The widget takes the pointer
1466// in its own space, below the menu bar strip.
1467fn (mut p Player) pointer_moved(x f64, y f64) {
1468 $if debug_cadence ? {
1469 eprintln('CAD pointer: ${x},${y}')
1470 }
1471 if p.fullscreen {
1472 sapp.show_mouse(true)
1473 }
1474 p.Player.pointer_moved(x, y - content_top())
1475}
1476
1477// content_top is the menu bar strip above the content. Pointer events include
1478// it; the widget's space starts below it. sapp.height() is framebuffer pixels
1479// while bounds() is in layout pixels, so the DPI scale turns one into the
1480// other's unit (the two agree at scale 1).
1481fn content_top() f64 {
1482 return f64(sapp.height()) / ui2.scale() - ui2.bounds().height
1483}
1484
1485fn (mut p Player) toggle_fullscreen() {
1486 p.fullscreen = !p.fullscreen
1487 p.sync_overlay()
1488 sapp.toggle_fullscreen()
1489 sapp.show_mouse(true)
1490 p.last_motion = time.ticks()
1491 // Fullscreen hides the menu bar too; leaving fullscreen brings it back.
1492 ui2.set_menu_bar_hidden(p.menu_hidden())
1493 ui2.set_menu_bar(p.menus())
1494}
1495
1496// set_show_stats opens and closes the statistics popup. On demand the popup
1497// must ask for its own frames: the counters would rebuild the window and the
1498// ui2 keep-alive repaint leaves numbers stale on screen for up to ten
1499// seconds, so while the popup is open a timer refreshes it once a second.
1500// The timer re-arms itself and stops when the popup closes.
1501fn (mut p Player) set_show_stats(open bool) {
1502 if p.show_stats == open {
1503 return
1504 }
1505 p.show_stats = open
1506 if p.stats_wake != 0 {
1507 ui2.cancel_timer(p.stats_wake)
1508 p.stats_wake = 0
1509 }
1510 if open {
1511 p.stats_tick()
1512 }
1513}
1514
1515// stats_tick takes the frame scheduler's snapshot into the popup's delta
1516// fields and re-arms the refresh timer. It runs on the UI thread inside the
1517// frame, where the model may change.
1518fn (mut p Player) stats_tick() {
1519 if !p.show_stats {
1520 return
1521 }
1522 s := ui2.render_stats()
1523 u := gc_heap_usage()
1524 p.stats_callbacks = s.callbacks - p.stats_last_callbacks
1525 p.stats_builds = s.builds - p.stats_last_builds
1526 p.stats_draws = s.draws - p.stats_last_draws
1527 p.stats_coalesced = s.coalesced - p.stats_last_coalesced
1528 p.stats_last_callbacks = s.callbacks
1529 p.stats_last_builds = s.builds
1530 p.stats_last_draws = s.draws
1531 p.stats_last_coalesced = s.coalesced
1532 p.stats_heap = u.heap_size
1533 p.stats_unmapped = u.unmapped_bytes
1534 // The snapshot fills the popup's model, so the numbers of this second show
1535 // at the next draw; the refresh timer asks for it a second later.
1536 ui2.request_refresh()
1537 p.stats_wake = ui2.after(1, fn [mut p] () {
1538 p.stats_tick()
1539 })
1540}
1541
1542// set_show_preview turns the seek-bar hover preview on or off. Turning it
1543// on after a --no-preview start builds the thumbnail instance here; turning
1544// it off only stops using the instance, which idles without decoding until
1545// the next start without the setting frees it, and removes the frame on show.
1546fn (mut p Player) set_show_preview(on bool) {
1547 if p.show_preview == on {
1548 return
1549 }
1550 p.show_preview = on
1551 if on {
1552 p.init_thumb()
1553 } else {
1554 p.drop_shown_thumb()
1555 }
1556}
1557
1558// set_continuous switches the window's redraw policy at runtime: continuous
1559// repaints the retained tree every vsync — the seek bar glides and hovers
1560// answer within a frame — and on_demand returns to strictly asked redraws
1561// where the window idles between asks. Performance mode takes the policy
1562// away until it is turned off, so nothing re-enables it behind its back.
1563fn (mut p Player) set_continuous(on bool) {
1564 if p.continuous == on {
1565 return
1566 }
1567 p.continuous = on
1568 ui2.set_refresh_mode(if on { ui2.RefreshMode.continuous } else { ui2.RefreshMode.on_demand })
1569}
1570
1571const max_notices = 4
1572
1573// notice_dwell is how long a notice stays on screen before it leaves,
1574// in seconds.
1575const notice_dwell = 4.0
1576
1577// notify queues a notice: it rides a toast over the video for notice_dwell
1578// seconds, then leaves. The queue keeps the last few, so a burst of messages
1579// reads as a stack instead of each one overwriting the last. An empty text
1580// clears the queue, which is what the old single-notice assignments mapped
1581// their dismissal to.
1582fn (mut p Player) notify(text string) {
1583 if text.len == 0 {
1584 p.clear_notices()
1585 return
1586 }
1587 p.notice_serial++
1588 serial := p.notice_serial
1589 wake := ui2.after(notice_dwell, fn [mut p, serial] () {
1590 p.remove_notice(serial)
1591 })
1592 p.notices << Notice{
1593 text: text
1594 serial: serial
1595 wake: wake
1596 }
1597 for p.notices.len > max_notices {
1598 oldest := p.notices[0]
1599 if oldest.wake != 0 {
1600 ui2.cancel_timer(oldest.wake)
1601 }
1602 p.notices.delete(0)
1603 }
1604 ui2.request_refresh()
1605}
1606
1607// remove_notice drops one notice, cancelling its dwell timer.
1608fn (mut p Player) remove_notice(serial u64) {
1609 for i, n in p.notices {
1610 if n.serial == serial {
1611 if n.wake != 0 {
1612 ui2.cancel_timer(n.wake)
1613 }
1614 p.notices.delete(i)
1615 break
1616 }
1617 }
1618 ui2.request_refresh()
1619}
1620
1621// clear_notices drops every queued notice at once, the dismissal the old
1622// single-notice assignments mapped to.
1623fn (mut p Player) clear_notices() {
1624 if p.notices.len == 0 {
1625 return
1626 }
1627 for n in p.notices {
1628 if n.wake != 0 {
1629 ui2.cancel_timer(n.wake)
1630 }
1631 }
1632 p.notices.clear()
1633 ui2.request_refresh()
1634}
1635
1636fn (mut p Player) close_file() {
1637 mpv.command_async(p.mpv_ctx, 14, ['stop'])
1638 p.has_file = false
1639 p.pos = 0
1640 p.clear_next = true
1641 p.drop_shown_thumb()
1642 // The stop clears mpv's mirrors asynchronously; the title has nothing to
1643 // wait on here, regardless of whether media-title's own event lands.
1644 p.media_title = ''
1645 p.update_window_title()
1646}
1647
1648fn (p &Player) has_track(kind string) bool {
1649 return p.tracks.any(it.kind == kind && it.selected)
1650}
1651
1652// track_items lists the tracks of one kind as check items. The ids are the track ids
1653// that handle_media turns into aid, sid or vid.
1654fn (p &Player) track_items(kind string, with_none bool) []ui2.MenuItem {
1655 mut items := []ui2.MenuItem{}
1656 if with_none {
1657 items << ui2.menu_check_item('track:${kind}:no', 'None', !p.has_track(kind))
1658 }
1659 for track in p.tracks {
1660 if track.kind == kind {
1661 items << ui2.menu_check_item('track:${kind}:${track.id}', track.label, track.selected)
1662 }
1663 }
1664 if items.len == 0 {
1665 items << ui2.disabled(ui2.menu_item('${kind}_none', 'None available'))
1666 }
1667 return items
1668}
1669
1670fn (mut p Player) set_sub_delay(seconds f64) {
1671 p.sub_delay = math.round(seconds * 10) / 10
1672 mpv.set_double_async(p.mpv_ctx, 62, 'sub-delay', p.sub_delay)
1673}
1674
1675fn (mut p Player) set_audio_delay(seconds f64) {
1676 p.audio_delay = math.round(seconds * 10) / 10
1677 mpv.set_double_async(p.mpv_ctx, 63, 'audio-delay', p.audio_delay)
1678}
1679
1680// toggle_overlay flips overlay controls for the current mode: fullscreen and
1681// windowed remember their own choice.
1682fn (mut p Player) toggle_overlay() {
1683 if p.fullscreen {
1684 p.fullscreen_overlay = !p.fullscreen_overlay
1685 } else {
1686 p.windowed_overlay = !p.windowed_overlay
1687 }
1688 p.sync_overlay()
1689}
1690
1691// sync_overlay hands the widget the controls mode of the current window state.
1692fn (mut p Player) sync_overlay() {
1693 p.set_overlay(if p.fullscreen { p.fullscreen_overlay } else { p.windowed_overlay })
1694}
1695
1696fn (mut p Player) toggle_subs() {
1697 p.sub_visible = !p.sub_visible
1698 mpv.set_flag_async(p.mpv_ctx, 61, 'sub-visibility', p.sub_visible)
1699}
1700
1701fn (mut p Player) toggle_ab_loop() {
1702 if p.ab_a < 0 {
1703 p.ab_a = p.pos
1704 mpv.set_string_async(p.mpv_ctx, 64, 'ab-loop-a', '${p.pos:.3f}')
1705 } else if p.ab_b < 0 {
1706 p.ab_b = p.pos
1707 mpv.set_string_async(p.mpv_ctx, 65, 'ab-loop-b', '${p.pos:.3f}')
1708 } else {
1709 p.ab_a = -1
1710 p.ab_b = -1
1711 mpv.set_string_async(p.mpv_ctx, 66, 'ab-loop-a', 'no')
1712 mpv.set_string_async(p.mpv_ctx, 67, 'ab-loop-b', 'no')
1713 }
1714}
1715
1716// handle_media runs the menu events of the track, chapter, video and playlist items.
1717// It reports whether the event was one of them.
1718fn (mut p Player) handle_media(event string) bool {
1719 if event.starts_with('track:') {
1720 parts := event.split(':')
1721 if parts.len == 3 {
1722 prop := match parts[1] {
1723 'audio' { 'aid' }
1724 'sub' { 'sid' }
1725 else { 'vid' }
1726 }
1727 mpv.set_string_async(p.mpv_ctx, 50, prop, parts[2])
1728 }
1729 return true
1730 }
1731 if event.starts_with('chapter:') {
1732 index := event.all_after('chapter:').int()
1733 if index < p.chapters.len {
1734 mpv.set_string_async(p.mpv_ctx, 51, 'chapter', '${index}')
1735 }
1736 return true
1737 }
1738 if event.starts_with('audio_device:') {
1739 name := event.all_after('audio_device:')
1740 mpv.set_string_async(p.mpv_ctx, 56, 'audio-device', name)
1741 return true
1742 }
1743 if event.starts_with('ao_server:') {
1744 name := event.all_after('ao_server:')
1745 if name in audio_server_names() {
1746 p.ao = name
1747 // mpv takes ao before it starts and reloads an open output on the
1748 // write; an empty value is its own autoprobing. The device list
1749 // belongs to the new server, so this explicit hand-off re-reads it
1750 // (the device property silently changes once the server runs).
1751 mpv.set_string_async(p.mpv_ctx, 57, 'ao', if name == 'auto' { '' } else { name })
1752 p.refresh_media_async(true)
1753 ui2.set_menu_bar(p.menus())
1754 }
1755 return true
1756 }
1757 if event.starts_with('aspect:') {
1758 p.aspect = event.all_after('aspect:')
1759 mpv.set_string_async(p.mpv_ctx, 40, 'video-aspect-override', p.aspect)
1760 ui2.set_menu_bar(p.menus())
1761 return true
1762 }
1763 if event.starts_with('rotate:') {
1764 p.rotate = event.all_after('rotate:')
1765 mpv.set_string_async(p.mpv_ctx, 41, 'video-rotate', p.rotate)
1766 ui2.set_menu_bar(p.menus())
1767 return true
1768 }
1769 match event {
1770 'playlist_next' {
1771 mpv.command_async(p.mpv_ctx, 52, ['playlist-next'])
1772 }
1773 'playlist_prev' {
1774 mpv.command_async(p.mpv_ctx, 53, ['playlist-prev'])
1775 }
1776 'playback_loop_playlist' {
1777 p.loop_playlist = !p.loop_playlist
1778 mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist {
1779 'inf'
1780 } else {
1781 'no'
1782 })
1783 }
1784 'subs_visible' {
1785 p.toggle_subs()
1786 }
1787 'ab_loop' {
1788 p.toggle_ab_loop()
1789 }
1790 'toggle_pause' {
1791 mpv.set_flag_async(p.mpv_ctx, 10, 'pause', !p.paused)
1792 }
1793 'seek_back_30' {
1794 p.media_key('shift+left')
1795 }
1796 'seek_forward_30' {
1797 p.media_key('shift+right')
1798 }
1799 'seek_back_5' {
1800 p.media_key('left')
1801 }
1802 'seek_forward_5' {
1803 p.media_key('right')
1804 }
1805 'frame_back' {
1806 p.media_key(',')
1807 }
1808 'frame_step' {
1809 p.media_key('.')
1810 }
1811 'volume_up' {
1812 p.media_key('up')
1813 }
1814 'volume_down' {
1815 p.media_key('down')
1816 }
1817 'sub_delay_less' {
1818 p.media_key('z')
1819 }
1820 'sub_delay_more' {
1821 p.media_key('x')
1822 }
1823 'audio_delay_less' {
1824 p.media_key('g')
1825 }
1826 'audio_delay_more' {
1827 p.media_key('h')
1828 }
1829 'screenshot' {
1830 mpv.command_async(p.mpv_ctx, 55, ['screenshot'])
1831 }
1832 'video_deinterlace' {
1833 p.deinterlace = !p.deinterlace
1834 mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace {
1835 'yes'
1836 } else {
1837 'no'
1838 })
1839 }
1840 'video_hwdec' {
1841 p.hwdec = !p.hwdec
1842 mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', if p.hwdec { 'auto' } else { 'no' })
1843 }
1844 'video_zoom_in' {
1845 p.zoom_by(0.25)
1846 }
1847 'video_zoom_out' {
1848 p.zoom_by(-0.25)
1849 }
1850 'video_zoom_reset' {
1851 p.zoom = 0
1852 mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom)
1853 }
1854 'overlay_mode' {
1855 p.toggle_overlay()
1856 }
1857 else {
1858 return false
1859 }
1860 }
1861 ui2.set_menu_bar(p.menus())
1862 return true
1863}
1864
1865// media_key gives the playback keys their mpv meanings.
1866fn (mut p Player) media_key(key string) {
1867 match key {
1868 'left' {
1869 if p.has_file {
1870 mpv.command_async(p.mpv_ctx, 18, ['seek', '-5'])
1871 }
1872 }
1873 'right' {
1874 if p.has_file {
1875 mpv.command_async(p.mpv_ctx, 18, ['seek', '5'])
1876 }
1877 }
1878 'shift+left' {
1879 if p.has_file {
1880 mpv.command_async(p.mpv_ctx, 70, ['seek', '-30'])
1881 }
1882 }
1883 'shift+right' {
1884 if p.has_file {
1885 mpv.command_async(p.mpv_ctx, 71, ['seek', '30'])
1886 }
1887 }
1888 'shift+l' {
1889 p.toggle_ab_loop()
1890 ui2.set_menu_bar(p.menus())
1891 }
1892 'page_up' {
1893 mpv.command_async(p.mpv_ctx, 53, ['playlist-prev'])
1894 }
1895 'page_down' {
1896 mpv.command_async(p.mpv_ctx, 52, ['playlist-next'])
1897 }
1898 ',' {
1899 mpv.command_async(p.mpv_ctx, 72, ['frame-back-step'])
1900 }
1901 '.' {
1902 mpv.command_async(p.mpv_ctx, 73, ['frame-step'])
1903 }
1904 'v' {
1905 p.toggle_subs()
1906 }
1907 'z' {
1908 p.set_sub_delay(p.sub_delay - 0.1)
1909 }
1910 'x' {
1911 p.set_sub_delay(p.sub_delay + 0.1)
1912 }
1913 'g' {
1914 p.set_audio_delay(p.audio_delay - 0.1)
1915 }
1916 'h' {
1917 p.set_audio_delay(p.audio_delay + 0.1)
1918 }
1919 's' {
1920 mpv.command_async(p.mpv_ctx, 55, ['screenshot'])
1921 }
1922 else {}
1923 }
1924}
1925
1926// toggle_loop flips the loop-this-file flag and mirrors it to mpv. The 'Loop'
1927// menu row and the Shift+L key land here so both show one state.
1928fn (mut p Player) toggle_loop() {
1929 p.loop = !p.loop
1930 mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' })
1931 ui2.set_menu_bar(p.menus())
1932}
1933
1934// zoom_by steps video-zoom in 0.25 chunks, like the zoom menu rows do.
1935fn (mut p Player) zoom_by(delta f64) {
1936 p.zoom += delta
1937 mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom)
1938}
1939
1940// queue_menu_items builds the Playback > Queues entries: save, and the load
1941// and delete submenus over the saved queue files.
1942fn (p &Player) queue_menu_items() []ui2.MenuItem {
1943 mut load_items := []ui2.MenuItem{}
1944 mut delete_items := []ui2.MenuItem{}
1945 for name in saved_queues() {
1946 load_items << ui2.menu_item('queue_load:${name}', name)
1947 delete_items << ui2.menu_item('queue_delete:${name}', name)
1948 }
1949 if load_items.len == 0 {
1950 load_items << ui2.disabled(ui2.menu_item('queues_none_load', 'No saved queues'))
1951 delete_items << ui2.disabled(ui2.menu_item('queues_none_delete', 'No saved queues'))
1952 }
1953 return [
1954 ui2.submenu('Load queue', load_items),
1955 ui2.submenu('Delete queue', delete_items),
1956 ]
1957}
1958
1959// playlist_menu_items builds the Playback > Playlists entries: the save row,
1960// then the load, append and delete submenus over the m3u files. The slots
1961// are mpv-format playlists — mpv --playlist=<file> and every other player
1962// read them as they are.
1963fn (p &Player) playlist_menu_items() []ui2.MenuItem {
1964 mut load_items := []ui2.MenuItem{}
1965 mut append_items := []ui2.MenuItem{}
1966 mut delete_items := []ui2.MenuItem{}
1967 for name in saved_playlists() {
1968 load_items << ui2.menu_item('playlist_load:${name}', name)
1969 append_items << ui2.menu_item('playlist_append:${name}', name)
1970 delete_items << ui2.menu_item('playlist_delete:${name}', name)
1971 }
1972 if load_items.len == 0 {
1973 load_items << ui2.disabled(ui2.menu_item('playlists_none_load', 'No playlists'))
1974 append_items << ui2.disabled(ui2.menu_item('playlists_none_append', 'No playlists'))
1975 delete_items << ui2.disabled(ui2.menu_item('playlists_none_delete', 'No playlists'))
1976 }
1977 return [
1978 ui2.menu_item('playlist_save', 'Save playlist...'),
1979 ui2.submenu('Load playlist', load_items),
1980 ui2.submenu('Append playlist', append_items),
1981 ui2.submenu('Delete playlist', delete_items),
1982 ]
1983}
1984
1985// mirrored_mpv_options are the options the Options and Speed menus already
1986// offer as their own check rows. Presets store them in the configured set, so
1987// the raw list would show each one twice; they are skipped there.
1988const mirrored_mpv_options = ['audio-exclusive', 'audio-pitch-correction', 'blend-subtitles',
1989 'correct-downscaling', 'deband', 'deinterlace', 'dither', 'framedrop', 'hwdec', 'interpolation',
1990 'linear-downscaling', 'sigmoid-upscaling', 'vd-lavc-fast', 'video-sync']
1991
1992// mpv_menu_items builds the Options bar entries: the dialog that
1993// sets any option, then the options configured so far through it or
1994// --mpv-opt that no check row covers. Each one can be edited (the dialog
1995// opens prefilled, an empty value unsets) or unset outright.
1996fn (p &Player) mpv_menu_items() []ui2.MenuItem {
1997 mut items := []ui2.MenuItem{}
1998 items << ui2.menu_item('mpv_option', 'Set option...')
1999 for name in p.mpv_opts.keys() {
2000 if name in mirrored_mpv_options {
2001 continue
2002 }
2003 items << ui2.menu_item('mpv_option_edit:${name}', '${name}=${p.mpv_opts[name]}')
2004 items << ui2.menu_item('mpv_option_reset:${name}', 'Unset ${name}')
2005 }
2006 return items
2007}
2008
2009// audio_server_names lists the audio servers the menus offer and the --ao
2010// flag accepts — the outputs this platform's mpv can be expected to have.
2011// 'auto' is mpv's own autoprobing, which tries its drivers in built-in order;
2012// a named server is forced, with no fallback when it fails to open.
2013fn audio_server_names() []string {
2014 $if windows {
2015 return ['auto', 'wasapi', 'null']
2016 }
2017 $if macos {
2018 // avfoundation is mpv's macOS audio driver; it opened as 'coreaudio'
2019 // in older builds, which mpv still answers to, so nothing here pins
2020 // the historical name.
2021 return ['auto', 'avfoundation', 'null']
2022 }
2023 $if freebsd || openbsd || netbsd || dragonfly {
2024 // sndio and oss are the BSDs' native servers. The ports-installed
2025 // servers (pipewire, pulse, jack) sit behind mpv's own autoprobing,
2026 // which 'auto' already is.
2027 return ['auto', 'sndio', 'oss', 'null']
2028 }
2029 $if solaris {
2030 // mpv has no SADA/Sun audio driver, so the desktop servers the
2031 // distro's mpv is built against (pulse, jack) are what the menu
2032 // offers; 'auto' probes whatever the install has.
2033 return ['auto', 'pulse', 'jack', 'null']
2034 }
2035 $if android {
2036 // audiotrack is mpv's Android driver: it writes into the Java audio
2037 // stack through JNI, which makes it the only real output there.
2038 // resolve_ao demotes a settings file carried over from a desktop to
2039 // 'auto' on its own, because pulse or pipewire are not on this list.
2040 return ['auto', 'audiotrack', 'null']
2041 }
2042 return ['auto', 'pipewire', 'pulse', 'alsa', 'jack', 'sdl', 'null']
2043}
2044
2045fn (p &Player) menus() []ui2.Menu {
2046 mut speeds := []ui2.MenuItem{}
2047 for s in [0.5, 1.0, 1.25, 1.5, 2.0] {
2048 title := if s == 1.0 { '1x' } else { '${s}x' }
2049 speeds << ui2.menu_check_item('playback_speed:${s}', title, math.abs(p.speed - s) < 0.01)
2050 }
2051 speeds << ui2.menu_item('playback_speed_custom', 'Custom...')
2052 speeds << ui2.menu_separator()
2053 speeds << ui2.menu_check_item('audio_pitch_correction', 'Correct audio pitch at speed changes', p.pitch_correction)
2054
2055 sync_mode_items := [
2056 ui2.menu_check_item('video_sync:audio', 'Audio sync (default)', p.video_sync == 'audio'),
2057 ui2.menu_check_item('video_sync:display-resample', 'Display resample', p.video_sync == 'display-resample'),
2058 ui2.menu_check_item('video_sync:display-vdrop', 'Display resample, drop late frames', p.video_sync == 'display-vdrop'),
2059 ]
2060
2061 mut devices := []ui2.MenuItem{}
2062 for device in p.devices {
2063 devices << ui2.menu_check_item('audio_device:${device.name}', device.description,
2064 device.name == p.audio_device)
2065 }
2066 if devices.len == 0 {
2067 devices << ui2.disabled(ui2.menu_item('audio_device_none', 'No output devices'))
2068 }
2069 mut audio_items := p.track_items('audio', false)
2070 audio_items << ui2.menu_separator()
2071 audio_items << ui2.MenuItem{
2072 id: 'playback_mute'
2073 title: 'Mute'
2074 checked: p.muted
2075 shortcut: 'm'
2076 }
2077 audio_items << ui2.MenuItem{
2078 id: 'audio_delay_less'
2079 title: 'Delay -0.1 s'
2080 shortcut: 'g'
2081 }
2082 audio_items << ui2.MenuItem{
2083 id: 'audio_delay_more'
2084 title: 'Delay +0.1 s'
2085 shortcut: 'h'
2086 }
2087 mut servers := []ui2.MenuItem{}
2088 for server in audio_server_names() {
2089 title := match server {
2090 'auto' { 'Auto (mpv chooses)' }
2091 'pipewire' { 'PipeWire' }
2092 'pulse' { 'PulseAudio' }
2093 'alsa' { 'ALSA' }
2094 'jack' { 'JACK' }
2095 'sdl' { 'SDL' }
2096 'wasapi' { 'WASAPI' }
2097 'avfoundation' { 'AVFoundation' }
2098 'null' { 'Null (no audio)' }
2099 else { server }
2100 }
2101 servers << ui2.menu_check_item('ao_server:${server}', title, p.ao == server)
2102 }
2103 audio_items << ui2.submenu('Audio server', servers)
2104 audio_items << ui2.submenu('Output device', devices)
2105 audio_items << ui2.menu_separator()
2106 audio_items << ui2.MenuItem{
2107 id: 'volume_up'
2108 title: 'Volume up'
2109 shortcut: 'up'
2110 }
2111 audio_items << ui2.MenuItem{
2112 id: 'volume_down'
2113 title: 'Volume down'
2114 shortcut: 'down'
2115 }
2116 audio_items << ui2.menu_separator()
2117 audio_items << ui2.menu_item('volume_max_custom', 'Set max volume...')
2118
2119 mut aspects := []ui2.MenuItem{}
2120 for option in [['no', 'Default'], ['16:9', '16:9'], ['4:3', '4:3'], ['2.35:1', '2.35:1']] {
2121 aspects << ui2.menu_check_item('aspect:${option[0]}', option[1], p.aspect == option[0])
2122 }
2123 mut rotations := []ui2.MenuItem{}
2124 for degrees in ['0', '90', '180', '270'] {
2125 rotations << ui2.menu_check_item('rotate:${degrees}', '${degrees} degrees', p.rotate == degrees)
2126 }
2127 mut video_items := p.track_items('video', false)
2128 video_items << ui2.menu_separator()
2129 video_items << ui2.submenu('Aspect', aspects)
2130 video_items << ui2.submenu('Rotate', rotations)
2131 video_items << ui2.MenuItem{
2132 id: 'video_zoom_in'
2133 title: 'Zoom in'
2134 shortcut: 'cmd+='
2135 }
2136 video_items << ui2.MenuItem{
2137 id: 'video_zoom_out'
2138 title: 'Zoom out'
2139 shortcut: 'cmd+-'
2140 }
2141 video_items << ui2.menu_item('video_zoom_reset', 'Reset zoom')
2142
2143 mut sub_items := p.track_items('sub', true)
2144 sub_items << ui2.menu_separator()
2145 sub_items << ui2.MenuItem{
2146 id: 'subs_visible'
2147 title: 'Show subtitles'
2148 checked: p.sub_visible
2149 shortcut: 'v'
2150 }
2151 sub_items << ui2.MenuItem{
2152 id: 'sub_delay_less'
2153 title: 'Delay -0.1 s'
2154 shortcut: 'z'
2155 }
2156 sub_items << ui2.MenuItem{
2157 id: 'sub_delay_more'
2158 title: 'Delay +0.1 s'
2159 shortcut: 'x'
2160 }
2161 sub_items << ui2.menu_separator()
2162 sub_items << ui2.menu_item('sub_scale_up', 'Bigger')
2163 sub_items << ui2.menu_item('sub_scale_down', 'Smaller')
2164 sub_items << ui2.menu_item('sub_scale_reset', 'Reset size')
2165
2166 mut chapter_items := []ui2.MenuItem{}
2167 for i, chapter in p.chapters {
2168 chapter_items << ui2.menu_item('chapter:${i}', chapter.title)
2169 }
2170 if chapter_items.len == 0 {
2171 chapter_items << ui2.disabled(ui2.menu_item('chapters_none', 'No chapters'))
2172 }
2173
2174 return [
2175 ui2.Menu{
2176 title: 'File'
2177 items: [
2178 ui2.menu_item_with_shortcut('file_open', 'Open...', 'cmd+o'),
2179 ui2.menu_item_with_shortcut('open_url', 'Open URL...', 'cmd+u'),
2180 ui2.menu_item_with_shortcut('file_close', 'Close', 'cmd+w'),
2181 ui2.submenu('Default open', [
2182 ui2.menu_check_item('open_mode:ask', 'Ask', p.open_mode == 'ask'),
2183 ui2.menu_check_item('open_mode:play', 'Play now', p.open_mode == 'play'),
2184 ui2.menu_check_item('open_mode:queue', 'Add to queue', p.open_mode == 'queue'),
2185 ]),
2186 ui2.menu_separator(),
2187 ui2.MenuItem{
2188 id: 'screenshot'
2189 title: 'Screenshot'
2190 shortcut: 's'
2191 },
2192 ]
2193 },
2194 ui2.Menu{
2195 title: 'View'
2196 items: [
2197 ui2.MenuItem{
2198 id: 'view_fullscreen'
2199 title: 'Fullscreen'
2200 checked: p.fullscreen
2201 shortcut: 'f'
2202 },
2203 ui2.MenuItem{
2204 id: 'overlay_mode'
2205 title: 'Overlay mode'
2206 checked: if p.fullscreen {
2207 p.fullscreen_overlay
2208 } else {
2209 p.windowed_overlay
2210 }
2211 shortcut: 'o'
2212 },
2213 ui2.MenuItem{
2214 id: 'view_statistics'
2215 title: 'Statistics'
2216 checked: p.show_stats
2217 shortcut: 'i'
2218 },
2219 ui2.MenuItem{
2220 id: 'view_preview'
2221 title: 'Hover preview'
2222 checked: p.show_preview
2223 },
2224 ui2.MenuItem{
2225 id: 'view_queue'
2226 title: 'Queue'
2227 checked: p.show_queue
2228 shortcut: 'q'
2229 },
2230 ui2.MenuItem{
2231 id: 'view_theme_editor'
2232 title: 'Theme editor'
2233 checked: p.theme_editor_open
2234 shortcut: 't'
2235 },
2236 ui2.submenu('UI scale', [
2237 ui2.menu_check_item('ui_scale:0', 'Automatic', p.ui_scale == 0),
2238 ui2.menu_check_item('ui_scale:1', '1x', p.ui_scale == 1),
2239 ui2.menu_check_item('ui_scale:1.5', '1.5x', p.ui_scale == 1.5),
2240 ui2.menu_check_item('ui_scale:2', '2x', p.ui_scale == 2),
2241 ui2.menu_check_item('ui_scale:2.5', '2.5x', p.ui_scale == 2.5),
2242 ui2.menu_check_item('ui_scale:3', '3x', p.ui_scale == 3),
2243 ]),
2244 ui2.menu_check_item('view_smooth_bar', 'Smooth seek bar', p.smooth_bar),
2245 // Performance mode is the redraw budget's backstop: it takes
2246 // the continuous redraw away until it is turned off, so the
2247 // row greys out while it runs.
2248 ui2.MenuItem{
2249 id: 'view_continuous'
2250 title: 'Continuous redraw'
2251 checked: p.continuous
2252 enabled: !p.low_quality
2253 },
2254 ui2.menu_check_item('view_low_quality', 'Performance mode', p.low_quality),
2255 ]
2256 },
2257 // One bar each for what a player works on, so a dropdown stays under
2258 // half its window height; Playback keeps the pacing and navigation and
2259 // the things that have no menu of their own.
2260 ui2.Menu{
2261 title: 'Playback'
2262 items: [
2263 ui2.MenuItem{
2264 id: 'toggle_pause'
2265 title: if p.paused { 'Play' } else { 'Pause' }
2266 shortcut: 'space'
2267 },
2268 ui2.MenuItem{
2269 id: 'playback_loop'
2270 title: 'Loop'
2271 checked: p.loop
2272 shortcut: 'l'
2273 },
2274 ui2.menu_check_item('playback_loop_playlist', 'Loop playlist', p.loop_playlist),
2275 ui2.menu_separator(),
2276 ui2.MenuItem{
2277 id: 'playlist_prev'
2278 title: 'Previous file'
2279 shortcut: 'PgUp'
2280 },
2281 ui2.MenuItem{
2282 id: 'playlist_next'
2283 title: 'Next file'
2284 shortcut: 'PgDn'
2285 },
2286 ui2.MenuItem{
2287 id: 'ab_loop'
2288 title: 'A-B loop'
2289 checked: p.ab_a >= 0 && p.ab_b >= 0
2290 shortcut: 'shift+l'
2291 },
2292 ui2.MenuItem{
2293 id: 'seek_back_30'
2294 title: 'Seek back 30 s'
2295 shortcut: 'shift+left'
2296 }
2297 ui2.MenuItem{
2298 id: 'seek_forward_30'
2299 title: 'Seek forward 30 s'
2300 shortcut: 'shift+right'
2301 },
2302 ui2.MenuItem{
2303 id: 'seek_back_5'
2304 title: 'Seek back 5 s'
2305 shortcut: 'left'
2306 },
2307 ui2.MenuItem{
2308 id: 'seek_forward_5'
2309 title: 'Seek forward 5 s'
2310 shortcut: 'right'
2311 },
2312 ui2.MenuItem{
2313 id: 'frame_back'
2314 title: 'Frame back'
2315 shortcut: ','
2316 }
2317 ui2.MenuItem{
2318 id: 'frame_step'
2319 title: 'Frame forward'
2320 shortcut: '.'
2321 },
2322 ui2.menu_separator(),
2323 ui2.submenu('Speed', speeds),
2324 ui2.menu_separator(),
2325 ui2.submenu('Chapters', chapter_items),
2326 ui2.submenu('Queues', p.queue_menu_items()),
2327 ui2.submenu('Playlists', p.playlist_menu_items()),
2328 ]
2329 },
2330 ui2.Menu{
2331 title: 'Audio'
2332 items: audio_items
2333 },
2334 ui2.Menu{
2335 title: 'Video'
2336 items: video_items
2337 },
2338 ui2.Menu{
2339 title: 'Subtitles'
2340 items: sub_items
2341 },
2342 // Options is the "how the pipeline runs" bar: any raw mpv option plus
2343 // every playback-quality flag vendetta mirrors, instead of scattering
2344 // them across the media-oriented bars.
2345 ui2.Menu{
2346 title: 'Options'
2347 items: [
2348 // Presets bundle the whole Options bar under a name, so the
2349 // submenu leads the fine-grained rows.
2350 ui2.submenu('Presets', p.preset_menu_items()),
2351 ...p.mpv_menu_items(),
2352 ui2.menu_separator(),
2353 // Vsync pacing as vendetta's render call sees it: waiting inside
2354 // the render for mpv's target display time is mpv's default
2355 // presentation behaviour, --no-block-target-time switches it
2356 // off, and the menu does the same for this session.
2357 ui2.menu_check_item('render_wait_vsync', 'Wait for vsync timing', p.cfg.block_target_time),
2358 ui2.submenu('Sync mode', sync_mode_items),
2359 ui2.menu_separator(),
2360 ui2.menu_check_item('video_interpolation', 'Interpolation', p.interpolation),
2361 ui2.submenu('Picture quality', [
2362 ui2.menu_check_item('quality_deband', 'Deband', p.deband),
2363 ui2.menu_check_item('quality_dither', 'Dither', p.dither),
2364 ui2.menu_check_item('quality_correct_down', 'Correct downscaling', p.correct_downscaling),
2365 ui2.menu_check_item('quality_linear_down', 'Linear light downscaling', p.linear_downscaling),
2366 ui2.menu_check_item('quality_sigmoid_up', 'Sigmoid upscaling', p.sigmoid_upscaling),
2367 ui2.menu_check_item('quality_blend_subs', 'Blend subtitles into video', p.blend_subtitles),
2368 ]),
2369 ui2.submenu('Frame dropping', [
2370 ui2.menu_check_item('framedrop:no', 'Off', p.framedrop == 'no'),
2371 ui2.menu_check_item('framedrop:vo', 'Display stage', p.framedrop == 'vo'),
2372 ui2.menu_check_item('framedrop:decoder', 'Decoder stage', p.framedrop == 'decoder'),
2373 ui2.menu_check_item('framedrop:decoder+vo', 'Both stages', p.framedrop == 'decoder+vo'),
2374 ]),
2375 ui2.menu_check_item('video_fast_decode', 'Fast video decoding', p.fast_decode),
2376 ui2.menu_check_item('video_deinterlace', 'Deinterlace', p.deinterlace),
2377 ui2.menu_check_item('video_hwdec', 'Hardware decoding', p.hwdec),
2378 ui2.menu_check_item('audio_exclusive', 'Exclusive audio output', p.audio_exclusive),
2379 ui2.menu_separator(),
2380 // The window title's composition, title-local state rather
2381 // than mpv options: '(paused)' and the file name.
2382 ui2.menu_check_item('title_status', 'Show playback status', p.show_playback_status),
2383 ui2.menu_check_item('title_filename', 'Show filename in window title', p.show_title_filename),
2384 ...p.media_controls_menu_items(),
2385 ui2.submenu('Theme', p.theme_menu_items()),
2386 ]
2387 },
2388 ]
2389}
2390
2391// media_controls_menu_items is the Options row for the desktop media controls.
2392// Only a -d mpris build offers it, so the default menu has no dead row.
2393fn (p &Player) media_controls_menu_items() []ui2.MenuItem {
2394 $if mpris ? {
2395 return [
2396 ui2.menu_separator(),
2397 ui2.menu_check_item('media_controls', 'Desktop media controls', p.media_controls),
2398 ui2.menu_separator(),
2399 ]
2400 } $else {
2401 return [ui2.menu_separator()]
2402 }
2403}
2404
2405// theme_menu_items lists the themes as check items, with the one the window
2406// uses checked, then the editor's load and delete submenus, shaped like the
2407// queue loader and deleter they follow.
2408fn (p &Player) theme_menu_items() []ui2.MenuItem {
2409 mut items := []ui2.MenuItem{}
2410 mut edit_items := []ui2.MenuItem{}
2411 mut delete_items := []ui2.MenuItem{}
2412 for name in available_themes() {
2413 items << ui2.menu_check_item('theme:${name}', name, p.theme_name == name)
2414 edit_items << ui2.menu_item('theme_edit:${name}', name)
2415 delete_items << ui2.menu_item('theme_delete:${name}', name)
2416 }
2417 items << ui2.menu_separator()
2418 items << ui2.submenu('Edit theme', edit_items)
2419 items << ui2.submenu('Delete theme', delete_items)
2420 return items
2421}
2422
2423// wheel_volume raises or lowers the volume on a scroll wheel notch. Only the
2424// vertical axis counts; a notch steps 5 like the volume keys. Over a panel (the
2425// statistics popup, the queue sidebar, the theme editor) the wheel belongs to
2426// the panel: the colours and the queue rows scroll instead. The wheel reports
2427// its deltas, not where it happened, so the panels are tested at the pointer's
2428// tracked position.
2429fn (mut p Player) wheel_volume(dy f64) {
2430 if dy == 0 {
2431 return
2432 }
2433 if p.over_panel(p.pointer_x, p.pointer_y) {
2434 return
2435 }
2436 step := if dy > 0 { 5.0 } else { -5.0 }
2437 p.volume = math.min(math.max(p.volume + step, 0), p.max_volume)
2438 mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume)
2439 p.mpris_on_volume()
2440 p.settings_changed()
2441 ui2.set_menu_bar(p.menus())
2442}
2443
2444// mouse_button turns a right-button press over the video into play/pause.
2445// Left and middle clicks pass through to the controls untouched.
2446fn (mut p Player) mouse_button(button int, down bool, x f64, y f64) {
2447 if !down || button != 1 {
2448 return
2449 }
2450 if !p.pointer_over_video(x, y) {
2451 return
2452 }
2453 mpv.set_flag_async(p.mpv_ctx, 10, 'pause', !p.paused)
2454}
2455
2456// pointer_over_video reports whether the window point lands on the video
2457// rather than on the menu, the controls or a floating panel.
2458fn (p &Player) pointer_over_video(x f64, y f64) bool {
2459 bar := libvendetta.control_bar(ui2.bounds(), p.duration)
2460 // Pointer events are window coordinates; the layout starts below the
2461 // menu bar strip.
2462 menu_top := content_top()
2463 if y >= menu_top + bar.bar.y {
2464 return false
2465 }
2466 return !p.over_panel(x, y - menu_top)
2467}
2468