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