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