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