import os import ui2 import libvendetta import libvendetta.mpv import math import sokol.sapp import time // The app's observed property ids, as reply userdata on the widget's mpv // context. Both this app and the widget match property events by userdata on // the one context, so the id spaces must not overlap: the widget owns the low // ids (its observers at 1-9, its commands at 10-20 and 213), and these used // to sit at 7 and up — where aid events, read by the widget as its path // observer, replaced current_path with the audio track id. The seek preview // then spent every capture trying to loadfile that id as a file. The app's // observers start at 1000, above everything else either side numbers on this // context. const obs_aid = u64(1000) const obs_sid = u64(1001) const obs_vid = u64(1002) const obs_audio_device = u64(1003) const obs_ao = u64(1004) const obs_playlist_pos = u64(1005) // The media controls' own position observer. The widget observes time-pos // for its seek bar under its own id; the app needs the same events to // announce jumps as Seeked signals, which is a second observer on the // property, not a fight over one. const obs_mpris_pos = u64(1006) const obs_duration_mpris = u64(1007) const obs_mpris_volume = u64(1008) const obs_mpris_loop = u64(1009) const obs_mpris_loop_playlist = u64(1010) const obs_media_title = u64(1011) const obs_media_artist = u64(1012) // Playback statistics properties, observed for the statistics popup. const obs_fps = u64(1013) const obs_vf_fps = u64(1014) const obs_display_fps = u64(1015) const obs_avsync = u64(1016) const obs_avsync_change = u64(1017) const obs_vsync_jitter = u64(1018) const obs_vsync_ratio = u64(1019) const obs_video_speed_corr = u64(1020) const obs_audio_speed_corr = u64(1021) const obs_decoder_dropped = u64(1022) const obs_display_dropped = u64(1023) const obs_video_bitrate = u64(1024) const obs_audio_bitrate = u64(1025) const obs_cache_time = u64(1026) const obs_cache_duration = u64(1027) const obs_cache_buffering = u64(1028) const obs_video_w = u64(1029) const obs_video_h = u64(1030) const obs_hwdec_current = u64(1031) // mpv flags the menus show as toggles: their state is mpv's, read back // through the observed properties. const obs_interpolation = u64(1032) const obs_pitch_correction = u64(1033) const obs_audio_exclusive = u64(1034) // The picture-quality, dropping and pacing half of the menu flag set. const obs_video_sync = u64(1035) const obs_framedrop = u64(1036) const obs_fast_decode = u64(1037) const obs_correct_downscaling = u64(1038) const obs_linear_downscaling = u64(1039) const obs_sigmoid_upscaling = u64(1040) const obs_deband = u64(1041) const obs_dither = u64(1042) const obs_blend_subtitles = u64(1043) // Reply userdata on the player's mpv context. Almost every write is fire and // forget, and nothing matches its reply by id, so an id only says what the // write was for and a family may share one (the picture-quality writes all use // 97). The runtime option writes are the exception: option_written matches their // replies, so they take ids from opt_write_base up, and the queue's loadfile // appends count up from loadfile_base, out of reach of any queue. Matching a // reply by id anywhere else needs a range reserved here first. const opt_write_base = u64(1) << 32 const loadfile_base = u64(1) << 20 const option_unset_userdata = u64(86) // The hidden thumbnail instance's async command ids. const thumb_load_userdata = u64(210) const thumb_seek_userdata = u64(211) const thumb_shot_userdata = u64(212) // The thumbnail pipeline is short-lived; a stuck stage is abandoned after this. const thumb_state_loading = 1 const thumb_state_seeking = 2 const thumb_state_shooting = 3 const thumb_timeout_ms = i64(4000) struct Track { kind string id string label string selected bool } struct AudioDevice { name string description string } struct Chapter { title string at f64 } // Notice is one queued toast: the text, a serial that keys its element id, // and the dwell timer that removes it. struct Notice { text string serial u64 wake u64 } // Player is vendetta's player. The embedded libvendetta widget owns the mpv // handle, the render path and the observed playback state; the rest is the // app's own state for menus, settings, the queue and statistics. struct Player { libvendetta.Player mut: tracks []Track chapters []Chapter devices []AudioDevice audio_device string = 'auto' // The audio server mpv's sound runs through: 'auto' leaves the choice to // mpv's autoprobing, a name pins one. The observed 'ao' property keeps it // in step with whatever wrote the option last. ao string = 'auto' sub_visible bool = true sub_delay f64 audio_delay f64 aspect string = 'no' rotate string = '0' zoom f64 deinterlace bool hwdec bool // The pinned UI scale (View > UI scale). 0 follows the platform, which on // Android means the phone-sized default in ui_scale_automatic. ui_scale f64 // mpv flags the menus show as toggles. They mirror the observed // properties, not vendetta's own idea of the state, and nothing writes them // at start: until the user clicks, mpv's own defaults rule. interpolation bool pitch_correction bool audio_exclusive bool // More mpv flags the menus run as toggles and submenus: picture quality, // frame dropping and sync pacing. Like the ones above, nothing writes // them at start; the observers carry mpv's current values, and only a // click or --mpv-opt changes them. video_sync string framedrop string fast_decode bool correct_downscaling bool linear_downscaling bool sigmoid_upscaling bool deband bool dither bool blend_subtitles bool loop_playlist bool ab_a f64 = -1 ab_b f64 = -1 loop bool max_volume_open bool max_volume_text string custom_open bool // The File > Open URL... dialog: what is typed here is a link by // construction, so it rides the same open path as the picker's files // without any existence check. url_open bool url_text string fullscreen bool windowed_menu_hidden bool fullscreen_menu_hidden bool = true preview_visible bool preview_time f64 = -1 preview_state int preview_t0 i64 preview_index int preview_pending_path string preview_pending_time f64 preview_show_path string preview_show_time f64 preview_show_w f64 preview_show_h f64 preview_over bool thumb_path string thumb_ctx voidptr speed_text string playlist []string show_stats bool show_queue bool // The seek-bar hover preview. The thumbnail mpv instance behind it is // only created while this is on: --no-preview or the saved setting // keeps the second mpv core out of low-end machines entirely. show_preview bool = true // The notice queue: toasts over the video, each shown for notice_dwell // seconds before it leaves. notices []Notice notice_serial u64 queue_open bool queue_paths []string queue []string // The queue sidebar's reorder container: its controlled state, the // generated keys behind the rows (paths can repeat, so they cannot name // a row), the scroll feedback, and the frame the sidebar was last built // with — the handlers rebuild rows from that same shape. See queue_config // in view.v. queue_state ui2.ReorderState queue_keys []string queue_scroll f64 queue_serial u64 queue_frame ui2.Rect theme Theme theme_name string = default_theme_name // The theme editor panel: the theme the edits start from, the fields' // texts, and each colour row's chooser. theme_editor_open bool theme_edit_base Theme theme_edit_name string theme_edit_texts map[string]string theme_pickers map[string]ThemePicker low_quality bool // The window title's two halves, each the Options bar's own check row: // the playback status is the '(paused)' suffix while the file is paused, // and the playing file's name follows the app name after ' - '. show_playback_status bool = true show_title_filename bool = true // The WM_CLASS write ran: sokol's X11 display exists only after its loop // opens the window, and the write is once-per-session work. window_class_set bool // The window's redraw policy: with it on, ui2 repaints the retained tree // every vsync and rebuilds on ask, so the seek bar glides and hovers // answer within a frame. It is the View menu's Continuous redraw row, and // performance mode takes it away until turned off. continuous bool last_frame_t0 i64 // The render thread (this one) must never wait on the mpv core while // advanced control is on, so the track, chapter and device lists are read // on a worker thread and arrive over this channel. media_chan chan MediaData media_read_busy bool media_dirty bool // A device-list read rented while a media read was in flight (see // refresh_media_async): the next read carries the devices with it. media_devices_wanted bool // The thumbnail capture poll's ui2 timer: re-armed while a generation is // in flight, so the on-demand loop asks for frames until it finishes. thumb_wake u64 save_timer u64 // The settings file's text as last written, so an unchanged state is not // written again (save_settings). settings_text string // The queue snapshot's debounced write timer (settings_changed's shape). queue_timer u64 // Whether the restored queue still waits for the first frame to hand its // entries to mpv's playlist without starting them (resume_pending_queue). queue_resume_pending bool // The statistics popup re-renders its numbers once a second through this // timer. Between runs it keeps the previous frame scheduler snapshot, so // the renderer line reports what the last period did, plus the heap sizes. stats_wake u64 stats_last_callbacks u64 stats_last_builds u64 stats_last_draws u64 stats_last_coalesced u64 stats_callbacks u64 stats_builds u64 stats_draws u64 stats_coalesced u64 stats_heap u64 stats_unmapped u64 queue_name_open bool queue_name_text string // The save-playlist dialog's state: the queue save's shape writing an // mpv-format m3u slot instead of a JSON queue file. playlist_name_open bool playlist_name_text string open_mode string = 'ask' want_fullscreen bool // mpv options the user configured through --mpv-opt or the Options // menu. They persist through the settings file and are mirrored into mpv // on start, after everything mpv itself needs. mpv_opts map[string]string // Runtime option writes mpv has not answered yet, by their reply userdata // (send_mpv_option, option_written). opt_writes map[u64]OptionWrite opt_write_serial u64 mpv_option_open bool mpv_option_name_text string mpv_option_value_text string // Options presets: named bundles of the Options bar saved under // ~/.config/vendetta/presets. The name records the preset applied last, // so the menu can check it; the other two are the save dialog's state. preset_name string preset_name_open bool preset_name_text string // The desktop media controls (MPRIS): the service and its worker live // here; nil means never started, media_controls is the on/off choice // the setting and the menu row drive. mpris &Mpris = unsafe { nil } media_controls bool // The media title and artist the metadata observers report, for the // MPRIS Metadata dictionary. media_title string media_artist string // Playback statistics observed from mpv, shown in the statistics popup. hwdec_current string = '?' video_w f64 video_h f64 container_fps f64 vf_fps f64 display_fps f64 avsync f64 avsync_change f64 vsync_jitter f64 vsync_ratio f64 video_speed_corr f64 audio_speed_corr f64 decoder_dropped f64 display_dropped f64 video_bitrate f64 audio_bitrate f64 cache_time f64 cache_duration f64 cache_buffering f64 windowed_overlay bool fullscreen_overlay bool = true playlist_index int } // update_window_title mirrors what mpv plays into the window title, in the // form 'Vendetta (paused) - filename': the pause suffix appears under the // Options bar's Show playback status row while playback is paused, and the // name is the file's own name for a local file or mpv's media-title for a // stream, shown under the Show filename row. With both rows off the title // stays plain 'Vendetta'. The media-title and pause property events run it, // so a file change and a pause flip repaint the title out of the mirrors the // observers already hold; neither call needs its own mpv read. fn (mut p Player) update_window_title() { name := if !p.has_file { '' } else if p.current_kind == .file && p.current_path.len > 0 { os.file_name(p.current_path) } else { p.media_title } mut title := 'Vendetta' if p.show_playback_status && p.paused { title += ' (paused)' } if p.show_title_filename && name.len > 0 { title += ' - ' + name } apply_window_title(title) } // on_mpv_event follows the events the menus and lists show. The widget has // already taken the playback state from each one. fn (mut p Player) on_mpv_event(ev voidptr) { match mpv.event_id(ev) { mpv.event_file_loaded { // The tracks and chapters follow the file; the device list does // not (and its read would initialize the audio output here). p.refresh_media_async(false) // The playlist came together: the step flags and metadata // follow, announced with the rest. p.mpris_announce() ui2.set_menu_bar(p.menus()) } mpv.event_end_file { p.tracks = []Track{} p.chapters = []Chapter{} p.ab_a = -1 p.ab_b = -1 // The file left: Stopped or the next file's state. The path // property change announces what follows; an end without one // (the last file stopped) still has to retract the metadata. p.mpris_push() ui2.set_menu_bar(p.menus()) } mpv.event_property_change { p.apply_app_property(ev) } mpv.event_set_property_reply { p.option_written(ev) } mpv.event_seek { p.mpris_seek_started() } mpv.event_playback_restart { p.mpris_seek_landed() } else {} } } // apply_app_property takes the properties the app shows in its menus and // statistics. The few it shares with the widget are read again here so the menus // refresh when they change. fn (mut p Player) apply_app_property(ev voidptr) { name := mpv.property_name(ev) $if debug_cadence ? { eprintln('CAD prop ${name}') } match name { 'aid', 'sid', 'vid' { // Track selections change the track list, not the devices. p.refresh_media_async(false) ui2.set_menu_bar(p.menus()) } 'audio-device' { if v := mpv.property_string(ev) { p.audio_device = v ui2.set_menu_bar(p.menus()) } } 'ao' { if v := mpv.property_string(ev) { // An empty list is mpv's autoprobing; the menu names that 'auto'. p.ao = if v.len == 0 { 'auto' } else { v } ui2.set_menu_bar(p.menus()) } } 'pause' { if v := mpv.property_flag(ev) { $if debug_cadence ? { eprintln('CAD pause=${v}') } p.paused = v p.mpris_push() p.update_window_title() ui2.set_menu_bar(p.menus()) } } 'mute' { if v := mpv.property_flag(ev) { p.muted = v p.mpris_push() ui2.set_menu_bar(p.menus()) } } 'interpolation' { if v := mpv.property_flag(ev) { p.interpolation = v ui2.set_menu_bar(p.menus()) } } 'audio-pitch-correction' { if v := mpv.property_flag(ev) { p.pitch_correction = v ui2.set_menu_bar(p.menus()) } } 'audio-exclusive' { if v := mpv.property_flag(ev) { p.audio_exclusive = v ui2.set_menu_bar(p.menus()) } } 'video-sync' { if v := mpv.property_string(ev) { p.video_sync = v ui2.set_menu_bar(p.menus()) } } 'framedrop' { if v := mpv.property_string(ev) { p.framedrop = v ui2.set_menu_bar(p.menus()) } } 'vd-lavc-fast' { if v := mpv.property_flag(ev) { p.fast_decode = v ui2.set_menu_bar(p.menus()) } } 'correct-downscaling' { if v := mpv.property_flag(ev) { p.correct_downscaling = v ui2.set_menu_bar(p.menus()) } } 'linear-downscaling' { if v := mpv.property_flag(ev) { p.linear_downscaling = v ui2.set_menu_bar(p.menus()) } } 'sigmoid-upscaling' { if v := mpv.property_flag(ev) { p.sigmoid_upscaling = v ui2.set_menu_bar(p.menus()) } } 'deband' { if v := mpv.property_flag(ev) { p.deband = v ui2.set_menu_bar(p.menus()) } } // The choice options arrive as strings; the menu needs the check // semantics, which is "anything mpv holds that works". 'dither' { if v := mpv.property_string(ev) { p.dither = v != 'no' ui2.set_menu_bar(p.menus()) } } 'blend-subtitles' { if v := mpv.property_string(ev) { p.blend_subtitles = v != 'no' ui2.set_menu_bar(p.menus()) } } 'speed' { if v := mpv.property_double(ev) { p.speed = v p.mpris_push() ui2.set_menu_bar(p.menus()) } } 'fps' { if v := mpv.property_double(ev) { p.container_fps = v } } 'video-params/w' { if v := mpv.property_double(ev) { p.video_w = v } } 'video-params/h' { if v := mpv.property_double(ev) { p.video_h = v } } 'hwdec-current' { if v := mpv.property_string(ev) { p.hwdec_current = v } } 'playlist-pos' { if v := mpv.property_string(ev) { p.playlist_index = v.int() p.mpris_push() } } // The media controls' position observer: jumps become Seeked // signals, steady playback updates nothing (the desktop reads // Position when it wants it). 'time-pos' { if v := mpv.property_double(ev) { p.mpris_on_position(v) } } 'duration' { if v := mpv.property_double(ev) { p.mpris_push() } } 'volume' { if v := mpv.property_double(ev) { // The write the property reports is mpv's truth, so the // player's mirror follows it too (the strip slider writes // through mpv, not through the app). p.volume = v p.mpris_push() } } 'loop-file' { p.mpris_push() } 'loop-playlist' { p.mpris_push() } 'media-title' { if v := mpv.property_string(ev) { p.media_title = v p.mpris_push() p.update_window_title() } } 'metadata/by-key/artist' { p.media_artist = mpv.property_string(ev) or { '' } p.mpris_push() } 'estimated-vf-fps' { if v := mpv.property_double(ev) { p.vf_fps = v } } 'estimated-display-fps' { if v := mpv.property_double(ev) { p.display_fps = v } } 'avsync' { if v := mpv.property_double(ev) { p.avsync = v } } 'total-avsync-change' { if v := mpv.property_double(ev) { p.avsync_change = v } } 'vsync-jitter' { if v := mpv.property_double(ev) { p.vsync_jitter = v } } 'vsync-ratio' { if v := mpv.property_double(ev) { p.vsync_ratio = v } } 'video-speed-correction' { if v := mpv.property_double(ev) { p.video_speed_corr = v } } 'audio-speed-correction' { if v := mpv.property_double(ev) { p.audio_speed_corr = v } } 'decoder-frame-drop-count' { if v := mpv.property_double(ev) { p.decoder_dropped = v } } 'drop-frame-count' { if v := mpv.property_double(ev) { p.display_dropped = v } } 'video-bitrate' { if v := mpv.property_double(ev) { p.video_bitrate = v / 1000 } } 'audio-bitrate' { if v := mpv.property_double(ev) { p.audio_bitrate = v / 1000 } } 'demuxer-cache-time' { if v := mpv.property_double(ev) { p.cache_time = v } } 'demuxer-cache-duration' { if v := mpv.property_double(ev) { p.cache_duration = v } } 'cache-buffering-state' { if v := mpv.property_double(ev) { p.cache_buffering = v } } 'path' { if v := mpv.property_string(ev) { p.current_path = v if v.len > 0 { p.load_thumb_file() } // A new file means new metadata; the service announces it // all, capability flags included. p.mpris_announce() } } else {} } } // queue_new_key returns the next key a queue row is named with. The queue can // hold the same path twice, so the paths themselves cannot be the keys; a // monotonic serial is unique for the run and stable as rows swap places. fn (mut p Player) queue_new_key() string { p.queue_serial++ return '${p.queue_serial}' } // queue_reset_keys re-keys the queue wholesale: load_paths replaced every // entry, so old keys — and with them the drag and keyboard cursor state — // mean nothing anymore. fn (mut p Player) queue_reset_keys() { p.queue_keys = []string{cap: p.queue.len} p.queue_state = ui2.ReorderState{} p.queue_scroll = 0 for _ in 0 .. p.queue.len { p.queue_keys << p.queue_new_key() } } // queue_index finds a queue row by its key; -1 when the row is gone. fn (p &Player) queue_index(key string) int { return p.queue_keys.index(key) } // queue_apply_step stores what a drag or an Alt-key move did and applies the // move: the queue array and its row keys shift the same way, mpv's playlist — // whose order the sidebar mirrors — moves the same one entry, and the playlist // mirror follows so the desktop tracklist reads the new order. fn (mut p Player) queue_apply_step(step ui2.ReorderStep) { p.queue_state = step.state if !step.moved { return } p.queue = ui2.reorder_move(p.queue, step.from, step.to) p.queue_keys = ui2.reorder_move(p.queue_keys, step.from, step.to) // mpv counts the move target before the entry is taken out, so a move // down needs one more: queue_up_ kept its plain target for a step up, // queue_down_ moved to index + 2 for a from -> from + 1. A key move and // a drag land the same way here. target := if step.to > step.from { step.to + 1 } else { step.to } mpv.command_async(p.mpv_ctx, u64(84), ['playlist-move', '${step.from}', '${target}']) // The mirror follows the queue's new order; the playing position ripples // in through the playlist-pos observer on its own. p.playlist = p.queue.clone() p.queue_state_changed() $if debug_cadence ? { eprintln('CAD queue_move from=${step.from} to=${step.to} target=${target} qlen=${p.queue.len} key=${step.state.active}') } } // queue_state_changed schedules the queue snapshot a second out, cancelling // a pending one, so a burst of queue changes (a drag, a run of row removals) // writes once, the way settings_changed debounces the settings file. fn (mut p Player) queue_state_changed() { if p.queue_timer != 0 { ui2.cancel_timer(p.queue_timer) } p.queue_timer = ui2.after(1, fn [mut p] () { p.save_queue_state() }) } // restore_queue replaces the app-side queue with a saved snapshot: fresh row // keys, the MPRIS and tracklist mirror brought along, and mpv's own playlist // left for the first frame — resume_pending_queue hands the entries over // there. The command line wins over the snapshot (see main's start), so a // start with files passed on it drops the restored list. fn (mut p Player) restore_queue(paths []string) { mut kept := []string{} for path in paths { // A file that left the disk between sessions loses its row instead of // hanging on as a dead entry; links have nothing to check. if libvendetta.source_kind(path) == .link || os.exists(path) { kept << path } } if kept.len == 0 { return } p.queue = kept.clone() p.queue_reset_keys() p.playlist = p.queue.clone() p.queue_resume_pending = true } // resume_pending_queue hands the restored queue to mpv on the first frame: // playlist-clear, then one plain append per entry. append never starts // playback — append-play would begin the first file — so the queue comes // back silent and mpv's position stays unset until a row is clicked or a // later file serves the entry. The flag fires exactly once. fn (mut p Player) resume_pending_queue() { if !p.queue_resume_pending || p.render_ctx == unsafe { nil } { return } p.queue_resume_pending = false mpv.command_async(p.mpv_ctx, u64(80), ['playlist-clear']) for index, file in p.queue { mpv.command_async(p.mpv_ctx, loadfile_base + u64(index), ['loadfile', file, 'append']) } } // queue_key moves the cursor's row with Alt+the arrows or Home / End, the // same move a drag performs. It stays quiet when the sidebar is closed or // the queue is empty, so the menu-bar Alt toggle and the playback keys keep // theirs. fn (mut p Player) queue_key(ev ui2.KeyEvent) ?ui2.ReorderStep { if !p.show_queue || p.queue.len == 0 { return none } step := ui2.reorder_key(p.queue_config(), ev)? p.queue_apply_step(step) return step } // handle runs for every window event. Nothing here waits for mpv. fn (mut p Player) handle(event string) { if event.starts_with('vd_') { p.Player.handle(event) return } $if debug_cadence ? { if event.starts_with('queue_') { eprintln('CAD queue ${event} len=${p.queue.len} pos=${p.playlist_index}') } } // The queue sidebar's rows take their drags through the reorder container // before anything else looks at a pointer event. A step rebuilds with the // sidebar (and drifts through mpv) on the frame every event already asks // for; other pointer events leave it untouched. if event.starts_with('pointer:') && p.show_queue && p.queue.len > 0 { if step := ui2.reorder_update(p.queue_config(), event) { p.queue_apply_step(step) } return } if p.handle_media(event) { return } match event { 'playback_speed_custom' { p.speed_text = '${p.speed:.2f}' p.custom_open = true return } 'speed_cancel' { p.custom_open = false return } 'volume_max_custom' { p.max_volume_text = '${p.max_volume:.0f}' p.max_volume_open = true return } 'max_volume_cancel' { p.max_volume_open = false return } 'max_volume_apply' { v := ui2.text('max_volume_input').trim_space().f64() if v > 0 && v <= 1000 { p.max_volume = v if p.volume > p.max_volume { p.volume = p.max_volume mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume) } p.max_volume_open = false p.clear_notices() p.settings_changed() ui2.set_menu_bar(p.menus()) } else { p.notify('Max volume must be between 1 and 1000.') } return } 'speed_apply' { speed := ui2.text('speed_input').trim_space().f64() if speed >= 0.01 && speed <= 100 { mpv.set_double_async(p.mpv_ctx, 19, 'speed', speed) p.custom_open = false p.clear_notices() } else { p.notify('Speed must be between 0.01 and 100.') } return } else {} } if event.starts_with('playback_speed:') { speed := event.all_after('playback_speed:').f64() mpv.set_double_async(p.mpv_ctx, 17, 'speed', speed) return } if event.starts_with('queue_rm_') { // The row keys name the events, so the index is read from the queue // as it stands now: a build cannot have reordered between the row's // draw and the press. key := event.all_after('queue_rm_') index := p.queue_index(key) if index >= 0 { p.queue.delete(index) p.queue_keys.delete(index) // No row left for the drag or the keyboard cursor to sit on. if p.queue_state.active == key { p.queue_state = ui2.ReorderState{} } mpv.command_async(p.mpv_ctx, u64(83), ['playlist-remove', '${index}']) // The mirror follows the queue's new order (see queue_move). p.playlist = p.queue.clone() p.queue_state_changed() } $if debug_cadence ? { eprintln('CAD queue_rm key=${key} idx=${index} qlen=${p.queue.len}') } return } if event.starts_with('theme:') { p.set_theme(event.all_after('theme:')) ui2.set_menu_bar(p.menus()) return } if event.starts_with('theme_edit:') { p.open_theme_editor(event.all_after('theme_edit:')) ui2.set_menu_bar(p.menus()) return } if event.starts_with('theme_delete:') { name := event.all_after('theme_delete:') os.rm(os.join_path(theme_dir(), '${name}.toml')) or {} if p.theme_name == name { p.set_theme(default_theme_name) } ui2.set_menu_bar(p.menus()) return } if p.theme_editor_open && p.handle_theme_picker_event(event) { return } if event == 'theme_save' { p.save_theme_from_editor() return } if event == 'theme_name_input' { p.theme_edit_name = ui2.text(event) return } if event.starts_with('theme_color_input_') { p.theme_edit_texts[event.all_after('theme_color_input_')] = ui2.text(event) p.theme_editor_preview() return } if event == 'view_theme_editor' { p.theme_editor_open = !p.theme_editor_open if p.theme_editor_open && p.theme_edit_texts.len == 0 { p.open_theme_editor(p.theme_name) } ui2.set_menu_bar(p.menus()) return } if event.starts_with('open_mode:') { p.open_mode = event.all_after('open_mode:') ui2.set_menu_bar(p.menus()) return } if event.starts_with('ui_scale:') { p.ui_scale = event.all_after('ui_scale:').f64() p.apply_ui_scale() p.settings_changed() ui2.set_menu_bar(p.menus()) return } if event.starts_with('queue_load:') { name := event.all_after('queue_load:') if paths := load_queue_file(name) { p.load_paths(paths) p.clear_notices() } else { p.notify('Could not load the queue ${name}.') } return } if event.starts_with('queue_delete:') { name := event.all_after('queue_delete:') os.rm(os.join_path(queues_dir(), '${name}.json')) or {} ui2.set_menu_bar(p.menus()) return } if event.starts_with('playlist_load:') { name := event.all_after('playlist_load:') if paths := load_playlist_file(name) { if paths.len == 0 { p.notify('The playlist ${name} is empty.') } else { p.load_paths(paths) } } else { p.notify('Could not load the playlist ${name}.') } return } if event.starts_with('playlist_append:') { name := event.all_after('playlist_append:') if paths := load_playlist_file(name) { if paths.len == 0 { p.notify('The playlist ${name} is empty.') } else { p.add_to_queue(paths) } } else { p.notify('Could not load the playlist ${name}.') } return } if event.starts_with('playlist_delete:') { name := event.all_after('playlist_delete:') os.rm(os.join_path(playlists_dir(), '${name}.m3u')) or {} ui2.set_menu_bar(p.menus()) return } if event.starts_with('mpv_option_edit:') { name := event.all_after('mpv_option_edit:') p.mpv_option_name_text = name p.mpv_option_value_text = p.mpv_opts[name] or { '' } p.mpv_option_open = true return } if event.starts_with('mpv_option_reset:') { name := event.all_after('mpv_option_reset:') p.unset_mpv_option(name) p.clear_notices() p.settings_changed() ui2.set_menu_bar(p.menus()) return } if event.starts_with('preset:') { p.apply_preset(event.all_after('preset:')) ui2.set_menu_bar(p.menus()) return } if event.starts_with('preset_delete:') { name := event.all_after('preset_delete:') os.rm(os.join_path(presets_dir(), '${name}.json')) or {} if p.preset_name == name { p.preset_name = '' p.settings_changed() } ui2.set_menu_bar(p.menus()) return } // The sync and dropping submenus pick mpv values outright; the observer // walks the state back once the core takes the write. if event.starts_with('video_sync:') { mpv.set_string_async(p.mpv_ctx, 94, 'video-sync', event.all_after('video_sync:')) return } if event.starts_with('framedrop:') { mpv.set_string_async(p.mpv_ctx, 95, 'framedrop', event.all_after('framedrop:')) return } match event { 'queue_play_now' { p.queue_open = false p.load_paths(p.queue_paths.clone()) } 'queue_add' { p.queue_open = false p.add_to_queue(p.queue_paths.clone()) } 'queue_cancel' { p.queue_open = false } 'queue_save' { if p.queue.len == 0 { p.notify('The queue is empty.') } else { p.queue_name_text = '' p.queue_name_open = true } } 'playlist_save' { if p.queue.len == 0 { p.notify('The queue is empty.') } else { p.playlist_name_text = '' p.playlist_name_open = true } } 'playlist_name_apply' { if p.save_playlist(ui2.text('playlist_name_input')) { p.playlist_name_open = false p.clear_notices() ui2.set_menu_bar(p.menus()) } } 'playlist_name_cancel' { p.playlist_name_open = false } 'queue_clear' { p.queue = []string{} // No row is left for the drag or the keyboard cursor to sit on. p.queue_keys = []string{} p.queue_state = ui2.ReorderState{} p.queue_scroll = 0 // The mirror follows: the desktop's tracklist reads the playlist. p.playlist = p.queue.clone() p.queue_state_changed() p.notify('Queue cleared.') p.settings_changed() ui2.set_menu_bar(p.menus()) } 'queue_name_apply' { if p.save_queue(ui2.text('queue_name_input')) { p.queue_name_open = false p.clear_notices() ui2.set_menu_bar(p.menus()) } } 'queue_name_cancel' { p.queue_name_open = false } 'mpv_option' { // Options > Set option...: an empty dialog that // takes any mpv option name and value. p.mpv_option_name_text = '' p.mpv_option_value_text = '' p.mpv_option_open = true } 'mpv_option_cancel' { p.mpv_option_open = false } 'mpv_option_apply' { name := ui2.text('mpv_opt_name_input').trim_space() value := ui2.text('mpv_opt_value_input') if name.len == 0 { p.notify('Type an mpv option name, like cache or demuxer-max-bytes.') return } p.clear_notices() // An empty value unsets the option: it leaves the configured set, // so it stops being re-applied from the saved settings too. if value.len == 0 { p.unset_mpv_option(name) p.mpv_option_open = false p.settings_changed() ui2.set_menu_bar(p.menus()) return } // The dialog stays open until mpv answers: a rejection is reported // there, and the typed name and value stay put for a correction. p.send_mpv_option(OptionWrite{ name: name value: value }) } 'preset_save' { // Options > Presets > Save current options...: the name starts // from the preset applied last, so saving again overwrites it. p.preset_name_text = p.preset_name p.preset_name_open = true } 'preset_name_cancel' { p.preset_name_open = false } 'preset_name_apply' { if p.save_preset(ui2.text('preset_name_input')) { p.preset_name_open = false ui2.set_menu_bar(p.menus()) } } 'file_open' { p.open_dialog() } 'open_url' { // Every open starts from an empty field, like the saved-queue // and preset name dialogs do. p.url_text = '' p.url_open = true } 'url_cancel' { p.url_open = false } 'url_apply' { url := ui2.text('url_input').trim_space() if url.len == 0 { p.notify('Type a link, protocol prefix included, like https://.') return } if libvendetta.source_kind(url) != .link { p.notify('That is not a link: type a protocol prefix, like https://.') return } p.url_open = false p.clear_notices() // The typed link walks the same open path the picker's entries // do, so Default open — ask, play now, add to queue — rules // here as well. p.load_or_prompt([url]) } 'view_fullscreen' { p.toggle_fullscreen() } 'view_statistics' { p.set_show_stats(!p.show_stats) ui2.set_menu_bar(p.menus()) } 'view_preview' { p.set_show_preview(!p.show_preview) ui2.set_menu_bar(p.menus()) } 'view_smooth_bar' { p.smooth_bar = !p.smooth_bar ui2.set_menu_bar(p.menus()) } 'title_status' { p.show_playback_status = !p.show_playback_status p.update_window_title() ui2.set_menu_bar(p.menus()) } 'title_filename' { p.show_title_filename = !p.show_title_filename p.update_window_title() ui2.set_menu_bar(p.menus()) } 'view_continuous' { p.set_continuous(!p.continuous) ui2.set_menu_bar(p.menus()) } 'view_queue' { p.show_queue = !p.show_queue ui2.set_menu_bar(p.menus()) } 'view_low_quality' { p.low_quality = !p.low_quality if p.low_quality { // Performance mode is the redraw budget's backstop: it takes // the continuous redraw away until it is turned off. p.set_continuous(false) p.notify('Performance mode: heavy rendering steps are skipped when frames run late.') } else { p.clear_notices() } ui2.set_menu_bar(p.menus()) } 'media_controls' { p.set_media_controls(!p.media_controls) } 'playback_mute' { mpv.set_flag_async(p.mpv_ctx, 16, 'mute', !p.muted) } 'playback_loop' { p.toggle_loop() } // The mpv flag toggles write the opposite of what mpv reports and // leave the state to the observed properties; nothing is written for // a flag the user never touches, so mpv's defaults rule untouched. 'video_interpolation' { mpv.set_flag_async(p.mpv_ctx, 90, 'interpolation', !p.interpolation) } 'audio_pitch_correction' { mpv.set_flag_async(p.mpv_ctx, 91, 'audio-pitch-correction', !p.pitch_correction) } 'audio_exclusive' { mpv.set_flag_async(p.mpv_ctx, 92, 'audio-exclusive', !p.audio_exclusive) } // Subtitle size rides the sub-scale property: relative adds below, // and the reset writes mpv's own default for --sub-scale (1). 'sub_scale_up' { mpv.command_async(p.mpv_ctx, 93, ['add', 'sub-scale', '0.1']) } 'sub_scale_down' { mpv.command_async(p.mpv_ctx, 93, ['add', 'sub-scale', '-0.1']) } 'sub_scale_reset' { mpv.command_async(p.mpv_ctx, 93, ['set', 'sub-scale', '1']) } // Picture quality on mpv's own terms: toggles write the opposite of // what mpv reports; the choice options flip between off and the value // mpv itself has as default (dither's algorithm, subtitle blending). 'quality_deband' { mpv.set_flag_async(p.mpv_ctx, 96, 'deband', !p.deband) } 'quality_dither' { mpv.set_string_async(p.mpv_ctx, 97, 'dither', if p.dither { 'no' } else { 'fruit' }) } 'quality_correct_down' { mpv.set_flag_async(p.mpv_ctx, 97, 'correct-downscaling', !p.correct_downscaling) } 'quality_linear_down' { mpv.set_flag_async(p.mpv_ctx, 97, 'linear-downscaling', !p.linear_downscaling) } 'quality_sigmoid_up' { mpv.set_flag_async(p.mpv_ctx, 97, 'sigmoid-upscaling', !p.sigmoid_upscaling) } 'quality_blend_subs' { mpv.set_string_async(p.mpv_ctx, 97, 'blend-subtitles', if p.blend_subtitles { 'no' } else { 'yes' }) } 'video_fast_decode' { mpv.set_flag_async(p.mpv_ctx, 98, 'vd-lavc-fast', !p.fast_decode) } 'render_wait_vsync' { // Presentation pacing is vendetta's render call, not an mpv property: // the flip changes what the next render asks mpv for. p.cfg.block_target_time = !p.cfg.block_target_time ui2.set_menu_bar(p.menus()) } 'file_close' { p.close_file() } else {} } } // handle_key gives keyboard shortcuts the same meaning as in mpc-qt's defaults. fn (mut p Player) handle_key(key string) { $if debug_cadence ? { 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}') } // While the theme editor is open its fields get the keys, so none of the // shortcuts apply; Escape closes the editor. if p.theme_editor_open { if key == 'escape' { p.handle('view_theme_editor') } return } // While the speed dialog is open its text field gets the keys, so none of the // shortcuts apply; Escape closes the dialog. if p.custom_open { if key == 'escape' { p.custom_open = false } return } // The mpv option dialog is the same: typing an option name or value must // not pause the file or open panels behind the user's back. Its Apply // button and the submit of the value field drive the same mpv_option_apply // event, so keys need no more handling here. if p.mpv_option_open { if key == 'escape' { p.mpv_option_open = false } return } // The preset name dialog is the same: naming a preset must not pause the // file. Its Save button and the input's submit drive preset_name_apply. if p.preset_name_open { if key == 'escape' { p.preset_name_open = false } return } // The save-url dialog is the same: typing a link must not pause the file // or work the panels behind it. Its Open button and the input's submit // drive url_apply. if p.url_open { if key == 'escape' { p.url_open = false } return } // The save-queue and save-playlist dialogs are the same: naming a // collection must not pause the file. The playlist name dialog sits with // the queue save's shape, so both take the guard the other open dialogs // carry — without it a typed m would mute behind the dialog. if p.queue_name_open { if key == 'escape' { p.queue_name_open = false } return } if p.playlist_name_open { if key == 'escape' { p.playlist_name_open = false } return } if p.fullscreen && key == 'escape' { p.toggle_fullscreen() return } match key { 'f' { p.toggle_fullscreen() } ' ' { rc := mpv.set_flag_async(p.mpv_ctx, 10, 'pause', !p.paused) $if debug_cadence ? { eprintln('CAD space rc=${rc} paused_was=${p.paused}') } } 'left', 'right' { p.media_key(key) } 'up' { mpv.set_double_async(p.mpv_ctx, 12, 'volume', if p.volume + 5 > p.max_volume { p.max_volume } else { p.volume + 5 }) p.mpris_on_volume() } 'down' { mpv.set_double_async(p.mpv_ctx, 12, 'volume', if p.volume - 5 < 0 { 0 } else { p.volume - 5 }) p.mpris_on_volume() } 'm' { mpv.set_flag_async(p.mpv_ctx, 16, 'mute', !p.muted) } 'i' { p.set_show_stats(!p.show_stats) ui2.set_menu_bar(p.menus()) } 'q' { p.show_queue = !p.show_queue ui2.set_menu_bar(p.menus()) } 't' { p.handle('view_theme_editor') } 'o' { p.toggle_overlay() ui2.set_menu_bar(p.menus()) } 'l' { p.toggle_loop() } 'ctrl+o' { p.open_dialog() } 'ctrl+u' { p.handle('open_url') } 'ctrl+w' { p.close_file() } 'ctrl+=' { p.zoom_by(0.25) } 'ctrl+-' { p.zoom_by(-0.25) } else { p.media_key(key) } } } // menu_hidden reports whether the menu bar is hidden in the current mode. fn (p &Player) menu_hidden() bool { return if p.fullscreen { p.fullscreen_menu_hidden } else { p.windowed_menu_hidden } } // set_menu_hidden shows or hides the menu bar for the current mode. fn (mut p Player) set_menu_hidden(hidden bool) { if p.fullscreen { p.fullscreen_menu_hidden = hidden } else { p.windowed_menu_hidden = hidden } ui2.set_menu_bar_hidden(hidden) } // pointer_moved wakes the controls and the cursor. The widget takes the pointer // in its own space, below the menu bar strip. fn (mut p Player) pointer_moved(x f64, y f64) { $if debug_cadence ? { eprintln('CAD pointer: ${x},${y}') } if p.fullscreen { sapp.show_mouse(true) } p.Player.pointer_moved(x, y - content_top()) } // content_top is the menu bar strip above the content. Pointer events include // it; the widget's space starts below it. sapp.height() is framebuffer pixels // while bounds() is in layout pixels, so the DPI scale turns one into the // other's unit (the two agree at scale 1). fn content_top() f64 { return f64(sapp.height()) / ui2.scale() - ui2.bounds().height } fn (mut p Player) toggle_fullscreen() { p.fullscreen = !p.fullscreen p.sync_overlay() sapp.toggle_fullscreen() sapp.show_mouse(true) p.last_motion = time.ticks() // Fullscreen hides the menu bar too; leaving fullscreen brings it back. ui2.set_menu_bar_hidden(p.menu_hidden()) ui2.set_menu_bar(p.menus()) } // set_show_stats opens and closes the statistics popup. On demand the popup // must ask for its own frames: the counters would rebuild the window and the // ui2 keep-alive repaint leaves numbers stale on screen for up to ten // seconds, so while the popup is open a timer refreshes it once a second. // The timer re-arms itself and stops when the popup closes. fn (mut p Player) set_show_stats(open bool) { if p.show_stats == open { return } p.show_stats = open if p.stats_wake != 0 { ui2.cancel_timer(p.stats_wake) p.stats_wake = 0 } if open { p.stats_tick() } } // stats_tick takes the frame scheduler's snapshot into the popup's delta // fields and re-arms the refresh timer. It runs on the UI thread inside the // frame, where the model may change. fn (mut p Player) stats_tick() { if !p.show_stats { return } s := ui2.render_stats() u := gc_heap_usage() p.stats_callbacks = s.callbacks - p.stats_last_callbacks p.stats_builds = s.builds - p.stats_last_builds p.stats_draws = s.draws - p.stats_last_draws p.stats_coalesced = s.coalesced - p.stats_last_coalesced p.stats_last_callbacks = s.callbacks p.stats_last_builds = s.builds p.stats_last_draws = s.draws p.stats_last_coalesced = s.coalesced p.stats_heap = u.heap_size p.stats_unmapped = u.unmapped_bytes // The snapshot fills the popup's model, so the numbers of this second show // at the next draw; the refresh timer asks for it a second later. ui2.request_refresh() p.stats_wake = ui2.after(1, fn [mut p] () { p.stats_tick() }) } // set_show_preview turns the seek-bar hover preview on or off. Turning it // on after a --no-preview start builds the thumbnail instance here; turning // it off only stops using the instance, which idles without decoding until // the next start without the setting frees it, and removes the frame on show. fn (mut p Player) set_show_preview(on bool) { if p.show_preview == on { return } p.show_preview = on if on { p.init_thumb() } else { p.drop_shown_thumb() } } // set_continuous switches the window's redraw policy at runtime: continuous // repaints the retained tree every vsync — the seek bar glides and hovers // answer within a frame — and on_demand returns to strictly asked redraws // where the window idles between asks. Performance mode takes the policy // away until it is turned off, so nothing re-enables it behind its back. fn (mut p Player) set_continuous(on bool) { if p.continuous == on { return } p.continuous = on ui2.set_refresh_mode(if on { ui2.RefreshMode.continuous } else { ui2.RefreshMode.on_demand }) } const max_notices = 4 // notice_dwell is how long a notice stays on screen before it leaves, // in seconds. const notice_dwell = 4.0 // notify queues a notice: it rides a toast over the video for notice_dwell // seconds, then leaves. The queue keeps the last few, so a burst of messages // reads as a stack instead of each one overwriting the last. An empty text // clears the queue, which is what the old single-notice assignments mapped // their dismissal to. fn (mut p Player) notify(text string) { if text.len == 0 { p.clear_notices() return } p.notice_serial++ serial := p.notice_serial wake := ui2.after(notice_dwell, fn [mut p, serial] () { p.remove_notice(serial) }) p.notices << Notice{ text: text serial: serial wake: wake } for p.notices.len > max_notices { oldest := p.notices[0] if oldest.wake != 0 { ui2.cancel_timer(oldest.wake) } p.notices.delete(0) } ui2.request_refresh() } // remove_notice drops one notice, cancelling its dwell timer. fn (mut p Player) remove_notice(serial u64) { for i, n in p.notices { if n.serial == serial { if n.wake != 0 { ui2.cancel_timer(n.wake) } p.notices.delete(i) break } } ui2.request_refresh() } // clear_notices drops every queued notice at once, the dismissal the old // single-notice assignments mapped to. fn (mut p Player) clear_notices() { if p.notices.len == 0 { return } for n in p.notices { if n.wake != 0 { ui2.cancel_timer(n.wake) } } p.notices.clear() ui2.request_refresh() } fn (mut p Player) close_file() { mpv.command_async(p.mpv_ctx, 14, ['stop']) p.has_file = false p.pos = 0 p.clear_next = true p.drop_shown_thumb() // The stop clears mpv's mirrors asynchronously; the title has nothing to // wait on here, regardless of whether media-title's own event lands. p.media_title = '' p.update_window_title() } fn (p &Player) has_track(kind string) bool { return p.tracks.any(it.kind == kind && it.selected) } // track_items lists the tracks of one kind as check items. The ids are the track ids // that handle_media turns into aid, sid or vid. fn (p &Player) track_items(kind string, with_none bool) []ui2.MenuItem { mut items := []ui2.MenuItem{} if with_none { items << ui2.menu_check_item('track:${kind}:no', 'None', !p.has_track(kind)) } for track in p.tracks { if track.kind == kind { items << ui2.menu_check_item('track:${kind}:${track.id}', track.label, track.selected) } } if items.len == 0 { items << ui2.disabled(ui2.menu_item('${kind}_none', 'None available')) } return items } fn (mut p Player) set_sub_delay(seconds f64) { p.sub_delay = math.round(seconds * 10) / 10 mpv.set_double_async(p.mpv_ctx, 62, 'sub-delay', p.sub_delay) } fn (mut p Player) set_audio_delay(seconds f64) { p.audio_delay = math.round(seconds * 10) / 10 mpv.set_double_async(p.mpv_ctx, 63, 'audio-delay', p.audio_delay) } // toggle_overlay flips overlay controls for the current mode: fullscreen and // windowed remember their own choice. fn (mut p Player) toggle_overlay() { if p.fullscreen { p.fullscreen_overlay = !p.fullscreen_overlay } else { p.windowed_overlay = !p.windowed_overlay } p.sync_overlay() } // sync_overlay hands the widget the controls mode of the current window state. fn (mut p Player) sync_overlay() { p.set_overlay(if p.fullscreen { p.fullscreen_overlay } else { p.windowed_overlay }) } fn (mut p Player) toggle_subs() { p.sub_visible = !p.sub_visible mpv.set_flag_async(p.mpv_ctx, 61, 'sub-visibility', p.sub_visible) } fn (mut p Player) toggle_ab_loop() { if p.ab_a < 0 { p.ab_a = p.pos mpv.set_string_async(p.mpv_ctx, 64, 'ab-loop-a', '${p.pos:.3f}') } else if p.ab_b < 0 { p.ab_b = p.pos mpv.set_string_async(p.mpv_ctx, 65, 'ab-loop-b', '${p.pos:.3f}') } else { p.ab_a = -1 p.ab_b = -1 mpv.set_string_async(p.mpv_ctx, 66, 'ab-loop-a', 'no') mpv.set_string_async(p.mpv_ctx, 67, 'ab-loop-b', 'no') } } // handle_media runs the menu events of the track, chapter, video and playlist items. // It reports whether the event was one of them. fn (mut p Player) handle_media(event string) bool { if event.starts_with('track:') { parts := event.split(':') if parts.len == 3 { prop := match parts[1] { 'audio' { 'aid' } 'sub' { 'sid' } else { 'vid' } } mpv.set_string_async(p.mpv_ctx, 50, prop, parts[2]) } return true } if event.starts_with('chapter:') { index := event.all_after('chapter:').int() if index < p.chapters.len { mpv.set_string_async(p.mpv_ctx, 51, 'chapter', '${index}') } return true } if event.starts_with('audio_device:') { name := event.all_after('audio_device:') mpv.set_string_async(p.mpv_ctx, 56, 'audio-device', name) return true } if event.starts_with('ao_server:') { name := event.all_after('ao_server:') if name in audio_server_names() { p.ao = name // mpv takes ao before it starts and reloads an open output on the // write; an empty value is its own autoprobing. The device list // belongs to the new server, so this explicit hand-off re-reads it // (the device property silently changes once the server runs). mpv.set_string_async(p.mpv_ctx, 57, 'ao', if name == 'auto' { '' } else { name }) p.refresh_media_async(true) ui2.set_menu_bar(p.menus()) } return true } if event.starts_with('aspect:') { p.aspect = event.all_after('aspect:') mpv.set_string_async(p.mpv_ctx, 40, 'video-aspect-override', p.aspect) ui2.set_menu_bar(p.menus()) return true } if event.starts_with('rotate:') { p.rotate = event.all_after('rotate:') mpv.set_string_async(p.mpv_ctx, 41, 'video-rotate', p.rotate) ui2.set_menu_bar(p.menus()) return true } match event { 'playlist_next' { mpv.command_async(p.mpv_ctx, 52, ['playlist-next']) } 'playlist_prev' { mpv.command_async(p.mpv_ctx, 53, ['playlist-prev']) } 'playback_loop_playlist' { p.loop_playlist = !p.loop_playlist mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' }) } 'subs_visible' { p.toggle_subs() } 'ab_loop' { p.toggle_ab_loop() } 'toggle_pause' { mpv.set_flag_async(p.mpv_ctx, 10, 'pause', !p.paused) } 'seek_back_30' { p.media_key('shift+left') } 'seek_forward_30' { p.media_key('shift+right') } 'seek_back_5' { p.media_key('left') } 'seek_forward_5' { p.media_key('right') } 'frame_back' { p.media_key(',') } 'frame_step' { p.media_key('.') } 'volume_up' { p.media_key('up') } 'volume_down' { p.media_key('down') } 'sub_delay_less' { p.media_key('z') } 'sub_delay_more' { p.media_key('x') } 'audio_delay_less' { p.media_key('g') } 'audio_delay_more' { p.media_key('h') } 'screenshot' { mpv.command_async(p.mpv_ctx, 55, ['screenshot']) } 'video_deinterlace' { p.deinterlace = !p.deinterlace mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' }) } 'video_hwdec' { p.hwdec = !p.hwdec mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', if p.hwdec { 'auto' } else { 'no' }) } 'video_zoom_in' { p.zoom_by(0.25) } 'video_zoom_out' { p.zoom_by(-0.25) } 'video_zoom_reset' { p.zoom = 0 mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom) } 'overlay_mode' { p.toggle_overlay() } else { return false } } ui2.set_menu_bar(p.menus()) return true } // media_key gives the playback keys their mpv meanings. fn (mut p Player) media_key(key string) { match key { 'left' { if p.has_file { mpv.command_async(p.mpv_ctx, 18, ['seek', '-5']) } } 'right' { if p.has_file { mpv.command_async(p.mpv_ctx, 18, ['seek', '5']) } } 'shift+left' { if p.has_file { mpv.command_async(p.mpv_ctx, 70, ['seek', '-30']) } } 'shift+right' { if p.has_file { mpv.command_async(p.mpv_ctx, 71, ['seek', '30']) } } 'shift+l' { p.toggle_ab_loop() ui2.set_menu_bar(p.menus()) } 'page_up' { mpv.command_async(p.mpv_ctx, 53, ['playlist-prev']) } 'page_down' { mpv.command_async(p.mpv_ctx, 52, ['playlist-next']) } ',' { mpv.command_async(p.mpv_ctx, 72, ['frame-back-step']) } '.' { mpv.command_async(p.mpv_ctx, 73, ['frame-step']) } 'v' { p.toggle_subs() } 'z' { p.set_sub_delay(p.sub_delay - 0.1) } 'x' { p.set_sub_delay(p.sub_delay + 0.1) } 'g' { p.set_audio_delay(p.audio_delay - 0.1) } 'h' { p.set_audio_delay(p.audio_delay + 0.1) } 's' { mpv.command_async(p.mpv_ctx, 55, ['screenshot']) } else {} } } // toggle_loop flips the loop-this-file flag and mirrors it to mpv. The 'Loop' // menu row and the Shift+L key land here so both show one state. fn (mut p Player) toggle_loop() { p.loop = !p.loop mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' }) ui2.set_menu_bar(p.menus()) } // zoom_by steps video-zoom in 0.25 chunks, like the zoom menu rows do. fn (mut p Player) zoom_by(delta f64) { p.zoom += delta mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom) } // queue_menu_items builds the Playback > Queues entries: save, and the load // and delete submenus over the saved queue files. fn (p &Player) queue_menu_items() []ui2.MenuItem { mut load_items := []ui2.MenuItem{} mut delete_items := []ui2.MenuItem{} for name in saved_queues() { load_items << ui2.menu_item('queue_load:${name}', name) delete_items << ui2.menu_item('queue_delete:${name}', name) } if load_items.len == 0 { load_items << ui2.disabled(ui2.menu_item('queues_none_load', 'No saved queues')) delete_items << ui2.disabled(ui2.menu_item('queues_none_delete', 'No saved queues')) } return [ ui2.submenu('Load queue', load_items), ui2.submenu('Delete queue', delete_items), ] } // playlist_menu_items builds the Playback > Playlists entries: the save row, // then the load, append and delete submenus over the m3u files. The slots // are mpv-format playlists — mpv --playlist= and every other player // read them as they are. fn (p &Player) playlist_menu_items() []ui2.MenuItem { mut load_items := []ui2.MenuItem{} mut append_items := []ui2.MenuItem{} mut delete_items := []ui2.MenuItem{} for name in saved_playlists() { load_items << ui2.menu_item('playlist_load:${name}', name) append_items << ui2.menu_item('playlist_append:${name}', name) delete_items << ui2.menu_item('playlist_delete:${name}', name) } if load_items.len == 0 { load_items << ui2.disabled(ui2.menu_item('playlists_none_load', 'No playlists')) append_items << ui2.disabled(ui2.menu_item('playlists_none_append', 'No playlists')) delete_items << ui2.disabled(ui2.menu_item('playlists_none_delete', 'No playlists')) } return [ ui2.menu_item('playlist_save', 'Save playlist...'), ui2.submenu('Load playlist', load_items), ui2.submenu('Append playlist', append_items), ui2.submenu('Delete playlist', delete_items), ] } // mirrored_mpv_options are the options the Options and Speed menus already // offer as their own check rows. Presets store them in the configured set, so // the raw list would show each one twice; they are skipped there. const mirrored_mpv_options = ['audio-exclusive', 'audio-pitch-correction', 'blend-subtitles', 'correct-downscaling', 'deband', 'deinterlace', 'dither', 'framedrop', 'hwdec', 'interpolation', 'linear-downscaling', 'sigmoid-upscaling', 'vd-lavc-fast', 'video-sync'] // mpv_menu_items builds the Options bar entries: the dialog that // sets any option, then the options configured so far through it or // --mpv-opt that no check row covers. Each one can be edited (the dialog // opens prefilled, an empty value unsets) or unset outright. fn (p &Player) mpv_menu_items() []ui2.MenuItem { mut items := []ui2.MenuItem{} items << ui2.menu_item('mpv_option', 'Set option...') for name in p.mpv_opts.keys() { if name in mirrored_mpv_options { continue } items << ui2.menu_item('mpv_option_edit:${name}', '${name}=${p.mpv_opts[name]}') items << ui2.menu_item('mpv_option_reset:${name}', 'Unset ${name}') } return items } // audio_server_names lists the audio servers the menus offer and the --ao // flag accepts — the outputs this platform's mpv can be expected to have. // 'auto' is mpv's own autoprobing, which tries its drivers in built-in order; // a named server is forced, with no fallback when it fails to open. fn audio_server_names() []string { $if windows { return ['auto', 'wasapi', 'null'] } $if macos { // avfoundation is mpv's macOS audio driver; it opened as 'coreaudio' // in older builds, which mpv still answers to, so nothing here pins // the historical name. return ['auto', 'avfoundation', 'null'] } $if freebsd || openbsd || netbsd || dragonfly { // sndio and oss are the BSDs' native servers. The ports-installed // servers (pipewire, pulse, jack) sit behind mpv's own autoprobing, // which 'auto' already is. return ['auto', 'sndio', 'oss', 'null'] } $if solaris { // mpv has no SADA/Sun audio driver, so the desktop servers the // distro's mpv is built against (pulse, jack) are what the menu // offers; 'auto' probes whatever the install has. return ['auto', 'pulse', 'jack', 'null'] } $if android { // audiotrack is mpv's Android driver: it writes into the Java audio // stack through JNI, which makes it the only real output there. // resolve_ao demotes a settings file carried over from a desktop to // 'auto' on its own, because pulse or pipewire are not on this list. return ['auto', 'audiotrack', 'null'] } return ['auto', 'pipewire', 'pulse', 'alsa', 'jack', 'sdl', 'null'] } fn (p &Player) menus() []ui2.Menu { mut speeds := []ui2.MenuItem{} for s in [0.5, 1.0, 1.25, 1.5, 2.0] { title := if s == 1.0 { '1x' } else { '${s}x' } speeds << ui2.menu_check_item('playback_speed:${s}', title, math.abs(p.speed - s) < 0.01) } speeds << ui2.menu_item('playback_speed_custom', 'Custom...') speeds << ui2.menu_separator() speeds << ui2.menu_check_item('audio_pitch_correction', 'Correct audio pitch at speed changes', p.pitch_correction) sync_mode_items := [ ui2.menu_check_item('video_sync:audio', 'Audio sync (default)', p.video_sync == 'audio'), ui2.menu_check_item('video_sync:display-resample', 'Display resample', p.video_sync == 'display-resample'), ui2.menu_check_item('video_sync:display-vdrop', 'Display resample, drop late frames', p.video_sync == 'display-vdrop'), ] mut devices := []ui2.MenuItem{} for device in p.devices { devices << ui2.menu_check_item('audio_device:${device.name}', device.description, device.name == p.audio_device) } if devices.len == 0 { devices << ui2.disabled(ui2.menu_item('audio_device_none', 'No output devices')) } mut audio_items := p.track_items('audio', false) audio_items << ui2.menu_separator() audio_items << ui2.MenuItem{ id: 'playback_mute' title: 'Mute' checked: p.muted shortcut: 'm' } audio_items << ui2.MenuItem{ id: 'audio_delay_less' title: 'Delay -0.1 s' shortcut: 'g' } audio_items << ui2.MenuItem{ id: 'audio_delay_more' title: 'Delay +0.1 s' shortcut: 'h' } mut servers := []ui2.MenuItem{} for server in audio_server_names() { title := match server { 'auto' { 'Auto (mpv chooses)' } 'pipewire' { 'PipeWire' } 'pulse' { 'PulseAudio' } 'alsa' { 'ALSA' } 'jack' { 'JACK' } 'sdl' { 'SDL' } 'wasapi' { 'WASAPI' } 'avfoundation' { 'AVFoundation' } 'null' { 'Null (no audio)' } else { server } } servers << ui2.menu_check_item('ao_server:${server}', title, p.ao == server) } audio_items << ui2.submenu('Audio server', servers) audio_items << ui2.submenu('Output device', devices) audio_items << ui2.menu_separator() audio_items << ui2.MenuItem{ id: 'volume_up' title: 'Volume up' shortcut: 'up' } audio_items << ui2.MenuItem{ id: 'volume_down' title: 'Volume down' shortcut: 'down' } audio_items << ui2.menu_separator() audio_items << ui2.menu_item('volume_max_custom', 'Set max volume...') mut aspects := []ui2.MenuItem{} for option in [['no', 'Default'], ['16:9', '16:9'], ['4:3', '4:3'], ['2.35:1', '2.35:1']] { aspects << ui2.menu_check_item('aspect:${option[0]}', option[1], p.aspect == option[0]) } mut rotations := []ui2.MenuItem{} for degrees in ['0', '90', '180', '270'] { rotations << ui2.menu_check_item('rotate:${degrees}', '${degrees} degrees', p.rotate == degrees) } mut video_items := p.track_items('video', false) video_items << ui2.menu_separator() video_items << ui2.submenu('Aspect', aspects) video_items << ui2.submenu('Rotate', rotations) video_items << ui2.MenuItem{ id: 'video_zoom_in' title: 'Zoom in' shortcut: 'cmd+=' } video_items << ui2.MenuItem{ id: 'video_zoom_out' title: 'Zoom out' shortcut: 'cmd+-' } video_items << ui2.menu_item('video_zoom_reset', 'Reset zoom') mut sub_items := p.track_items('sub', true) sub_items << ui2.menu_separator() sub_items << ui2.MenuItem{ id: 'subs_visible' title: 'Show subtitles' checked: p.sub_visible shortcut: 'v' } sub_items << ui2.MenuItem{ id: 'sub_delay_less' title: 'Delay -0.1 s' shortcut: 'z' } sub_items << ui2.MenuItem{ id: 'sub_delay_more' title: 'Delay +0.1 s' shortcut: 'x' } sub_items << ui2.menu_separator() sub_items << ui2.menu_item('sub_scale_up', 'Bigger') sub_items << ui2.menu_item('sub_scale_down', 'Smaller') sub_items << ui2.menu_item('sub_scale_reset', 'Reset size') mut chapter_items := []ui2.MenuItem{} for i, chapter in p.chapters { chapter_items << ui2.menu_item('chapter:${i}', chapter.title) } if chapter_items.len == 0 { chapter_items << ui2.disabled(ui2.menu_item('chapters_none', 'No chapters')) } return [ ui2.Menu{ title: 'File' items: [ ui2.menu_item_with_shortcut('file_open', 'Open...', 'cmd+o'), ui2.menu_item_with_shortcut('open_url', 'Open URL...', 'cmd+u'), ui2.menu_item_with_shortcut('file_close', 'Close', 'cmd+w'), ui2.submenu('Default open', [ ui2.menu_check_item('open_mode:ask', 'Ask', p.open_mode == 'ask'), ui2.menu_check_item('open_mode:play', 'Play now', p.open_mode == 'play'), ui2.menu_check_item('open_mode:queue', 'Add to queue', p.open_mode == 'queue'), ]), ui2.menu_separator(), ui2.MenuItem{ id: 'screenshot' title: 'Screenshot' shortcut: 's' }, ] }, ui2.Menu{ title: 'View' items: [ ui2.MenuItem{ id: 'view_fullscreen' title: 'Fullscreen' checked: p.fullscreen shortcut: 'f' }, ui2.MenuItem{ id: 'overlay_mode' title: 'Overlay mode' checked: if p.fullscreen { p.fullscreen_overlay } else { p.windowed_overlay } shortcut: 'o' }, ui2.MenuItem{ id: 'view_statistics' title: 'Statistics' checked: p.show_stats shortcut: 'i' }, ui2.MenuItem{ id: 'view_preview' title: 'Hover preview' checked: p.show_preview }, ui2.MenuItem{ id: 'view_queue' title: 'Queue' checked: p.show_queue shortcut: 'q' }, ui2.MenuItem{ id: 'view_theme_editor' title: 'Theme editor' checked: p.theme_editor_open shortcut: 't' }, ui2.submenu('UI scale', [ ui2.menu_check_item('ui_scale:0', 'Automatic', p.ui_scale == 0), ui2.menu_check_item('ui_scale:1', '1x', p.ui_scale == 1), ui2.menu_check_item('ui_scale:1.5', '1.5x', p.ui_scale == 1.5), ui2.menu_check_item('ui_scale:2', '2x', p.ui_scale == 2), ui2.menu_check_item('ui_scale:2.5', '2.5x', p.ui_scale == 2.5), ui2.menu_check_item('ui_scale:3', '3x', p.ui_scale == 3), ]), ui2.menu_check_item('view_smooth_bar', 'Smooth seek bar', p.smooth_bar), // Performance mode is the redraw budget's backstop: it takes // the continuous redraw away until it is turned off, so the // row greys out while it runs. ui2.MenuItem{ id: 'view_continuous' title: 'Continuous redraw' checked: p.continuous enabled: !p.low_quality }, ui2.menu_check_item('view_low_quality', 'Performance mode', p.low_quality), ] }, // One bar each for what a player works on, so a dropdown stays under // half its window height; Playback keeps the pacing and navigation and // the things that have no menu of their own. ui2.Menu{ title: 'Playback' items: [ ui2.MenuItem{ id: 'toggle_pause' title: if p.paused { 'Play' } else { 'Pause' } shortcut: 'space' }, ui2.MenuItem{ id: 'playback_loop' title: 'Loop' checked: p.loop shortcut: 'l' }, ui2.menu_check_item('playback_loop_playlist', 'Loop playlist', p.loop_playlist), ui2.menu_separator(), ui2.MenuItem{ id: 'playlist_prev' title: 'Previous file' shortcut: 'PgUp' }, ui2.MenuItem{ id: 'playlist_next' title: 'Next file' shortcut: 'PgDn' }, ui2.MenuItem{ id: 'ab_loop' title: 'A-B loop' checked: p.ab_a >= 0 && p.ab_b >= 0 shortcut: 'shift+l' }, ui2.MenuItem{ id: 'seek_back_30' title: 'Seek back 30 s' shortcut: 'shift+left' } ui2.MenuItem{ id: 'seek_forward_30' title: 'Seek forward 30 s' shortcut: 'shift+right' }, ui2.MenuItem{ id: 'seek_back_5' title: 'Seek back 5 s' shortcut: 'left' }, ui2.MenuItem{ id: 'seek_forward_5' title: 'Seek forward 5 s' shortcut: 'right' }, ui2.MenuItem{ id: 'frame_back' title: 'Frame back' shortcut: ',' } ui2.MenuItem{ id: 'frame_step' title: 'Frame forward' shortcut: '.' }, ui2.menu_separator(), ui2.submenu('Speed', speeds), ui2.menu_separator(), ui2.submenu('Chapters', chapter_items), ui2.submenu('Queues', p.queue_menu_items()), ui2.submenu('Playlists', p.playlist_menu_items()), ] }, ui2.Menu{ title: 'Audio' items: audio_items }, ui2.Menu{ title: 'Video' items: video_items }, ui2.Menu{ title: 'Subtitles' items: sub_items }, // Options is the "how the pipeline runs" bar: any raw mpv option plus // every playback-quality flag vendetta mirrors, instead of scattering // them across the media-oriented bars. ui2.Menu{ title: 'Options' items: [ // Presets bundle the whole Options bar under a name, so the // submenu leads the fine-grained rows. ui2.submenu('Presets', p.preset_menu_items()), ...p.mpv_menu_items(), ui2.menu_separator(), // Vsync pacing as vendetta's render call sees it: waiting inside // the render for mpv's target display time is mpv's default // presentation behaviour, --no-block-target-time switches it // off, and the menu does the same for this session. ui2.menu_check_item('render_wait_vsync', 'Wait for vsync timing', p.cfg.block_target_time), ui2.submenu('Sync mode', sync_mode_items), ui2.menu_separator(), ui2.menu_check_item('video_interpolation', 'Interpolation', p.interpolation), ui2.submenu('Picture quality', [ ui2.menu_check_item('quality_deband', 'Deband', p.deband), ui2.menu_check_item('quality_dither', 'Dither', p.dither), ui2.menu_check_item('quality_correct_down', 'Correct downscaling', p.correct_downscaling), ui2.menu_check_item('quality_linear_down', 'Linear light downscaling', p.linear_downscaling), ui2.menu_check_item('quality_sigmoid_up', 'Sigmoid upscaling', p.sigmoid_upscaling), ui2.menu_check_item('quality_blend_subs', 'Blend subtitles into video', p.blend_subtitles), ]), ui2.submenu('Frame dropping', [ ui2.menu_check_item('framedrop:no', 'Off', p.framedrop == 'no'), ui2.menu_check_item('framedrop:vo', 'Display stage', p.framedrop == 'vo'), ui2.menu_check_item('framedrop:decoder', 'Decoder stage', p.framedrop == 'decoder'), ui2.menu_check_item('framedrop:decoder+vo', 'Both stages', p.framedrop == 'decoder+vo'), ]), ui2.menu_check_item('video_fast_decode', 'Fast video decoding', p.fast_decode), ui2.menu_check_item('video_deinterlace', 'Deinterlace', p.deinterlace), ui2.menu_check_item('video_hwdec', 'Hardware decoding', p.hwdec), ui2.menu_check_item('audio_exclusive', 'Exclusive audio output', p.audio_exclusive), ui2.menu_separator(), // The window title's composition, title-local state rather // than mpv options: '(paused)' and the file name. ui2.menu_check_item('title_status', 'Show playback status', p.show_playback_status), ui2.menu_check_item('title_filename', 'Show filename in window title', p.show_title_filename), ...p.media_controls_menu_items(), ui2.submenu('Theme', p.theme_menu_items()), ] }, ] } // media_controls_menu_items is the Options row for the desktop media controls. // Only a -d mpris build offers it, so the default menu has no dead row. fn (p &Player) media_controls_menu_items() []ui2.MenuItem { $if mpris ? { return [ ui2.menu_separator(), ui2.menu_check_item('media_controls', 'Desktop media controls', p.media_controls), ui2.menu_separator(), ] } $else { return [ui2.menu_separator()] } } // theme_menu_items lists the themes as check items, with the one the window // uses checked, then the editor's load and delete submenus, shaped like the // queue loader and deleter they follow. fn (p &Player) theme_menu_items() []ui2.MenuItem { mut items := []ui2.MenuItem{} mut edit_items := []ui2.MenuItem{} mut delete_items := []ui2.MenuItem{} for name in available_themes() { items << ui2.menu_check_item('theme:${name}', name, p.theme_name == name) edit_items << ui2.menu_item('theme_edit:${name}', name) delete_items << ui2.menu_item('theme_delete:${name}', name) } items << ui2.menu_separator() items << ui2.submenu('Edit theme', edit_items) items << ui2.submenu('Delete theme', delete_items) return items } // wheel_volume raises or lowers the volume on a scroll wheel notch. Only the // vertical axis counts; a notch steps 5 like the volume keys. Over a panel (the // statistics popup, the queue sidebar, the theme editor) the wheel belongs to // the panel: the colours and the queue rows scroll instead. The wheel reports // its deltas, not where it happened, so the panels are tested at the pointer's // tracked position. fn (mut p Player) wheel_volume(dy f64) { if dy == 0 { return } if p.over_panel(p.pointer_x, p.pointer_y) { return } step := if dy > 0 { 5.0 } else { -5.0 } p.volume = math.min(math.max(p.volume + step, 0), p.max_volume) mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume) p.mpris_on_volume() p.settings_changed() ui2.set_menu_bar(p.menus()) } // mouse_button turns a right-button press over the video into play/pause. // Left and middle clicks pass through to the controls untouched. fn (mut p Player) mouse_button(button int, down bool, x f64, y f64) { if !down || button != 1 { return } if !p.pointer_over_video(x, y) { return } mpv.set_flag_async(p.mpv_ctx, 10, 'pause', !p.paused) } // pointer_over_video reports whether the window point lands on the video // rather than on the menu, the controls or a floating panel. fn (p &Player) pointer_over_video(x f64, y f64) bool { bar := libvendetta.control_bar(ui2.bounds(), p.duration) // Pointer events are window coordinates; the layout starts below the // menu bar strip. menu_top := content_top() if y >= menu_top + bar.bar.y { return false } return !p.over_panel(x, y - menu_top) }