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