import os import ui2 import libvendetta import libvendetta.mpv import json2 // Settings is the player state worth keeping between runs. It lives in // ~/.config/vendetta/settings.json and is written a second after the last change // and again when the window closes. struct Settings { pub mut: volume f64 = 100 max_volume f64 = 100 muted bool speed f64 = 1 // The audio server: 'auto' is mpv's autoprobing, a name forces one. The // platform's server list validates it on load, so a file carried over // from another OS demotes instead of forcing an absent output. ao string = 'auto' loop_file bool loop_playlist bool hwdec bool deinterlace bool // The pinned UI scale; 0 is automatic — the platform's own choice, with // a phone-sized default on Android. ui_scale f64 sub_visible bool = true aspect string = 'no' rotate string = '0' zoom f64 windowed_overlay bool fullscreen_overlay bool = true show_stats bool show_queue bool // Off also keeps the hidden thumbnail mpv instance from ever being // created: an idle second core is pure memory cost. show_preview bool = true open_mode string = 'ask' low_quality bool // The window's redraw policy: ui2 repaints the retained tree every vsync // and rebuilds on ask while it is on. Performance mode forces it off for // the session. continuous bool // The smooth seek bar: the player carries the bar forward at playback speed // between mpv's position reports and redraws the window at the display rate // while it plays. smooth_bar bool // The height of the seek and volume bars; 0, as in a file saved before the // setting existed, keeps the widget's default. slider_height f64 // The window title's two halves, shown while set (both default on): // '(paused)' while playback is paused, then the playing file's name. show_playback_status bool = true show_title_filename bool = true theme string = default_theme_name preset string media_controls bool mpv_opts map[string]string } // config_base is the directory vendetta's state lives under — the tree whose // vendetta/ subdirectory holds settings.json, themes, queues and presets. It // is the platform config directory everywhere else; on Android it is the // app's internal files directory, the one location a NativeActivity app may // write without storage permissions. The activity's own data path cannot be // asked yet (sapp registers it only once its loop runs, and this is read // before the window opens), so the package id is taken from the process name // — Android names the process after it — and the system's per-user data root // spells the rest. fn config_base() string { $if android { if text := os.read_file('/proc/self/cmdline') { pkg := text.all_before('\0') if pkg.len > 0 { return os.join_path('/data/user/0', pkg, 'files') } } return os.temp_dir() } return os.user_config_dir() or { os.join_path(os.home_dir(), '.config') } } // migrate_legacy_config imports the previous player's config on the first run // after the rename from vore: saved settings, themes, and queues. It only // runs while the new directory does not exist, so it happens exactly once; // the old directory stays put for hand-checking. fn migrate_legacy_config() { home := config_base() old_base := os.join_path(home, 'vore') new_base := os.join_path(home, 'vendetta') if os.exists(new_base) || !os.is_dir(old_base) { return } // The new tree must exist before the first settings save lands. os.mkdir_all(new_base) or { return } os.cp(os.join_path(old_base, 'settings.json'), os.join_path(new_base, 'settings.json')) or {} for sub, ext in { 'themes': '.toml' 'queues': '.json' 'presets': '.json' } { old_sub := os.join_path(old_base, sub) files := os.ls(old_sub) or { continue } new_sub := os.join_path(new_base, sub) os.mkdir_all(new_sub) or { continue } for file in files { if file.ends_with(ext) { os.cp(os.join_path(old_sub, file), os.join_path(new_sub, file)) or {} } } } } // settings_path is /vendetta/settings.json — ~/.config on the // desktops, the app's internal files directory on Android (config_base). fn settings_path() string { return os.join_path(config_base(), 'vendetta', 'settings.json') } // load_settings reads the settings file; a missing or malformed file falls // back to the compiled-in defaults. fn load_settings() Settings { text := os.read_file(settings_path()) or { return Settings{} } return json2.decode[Settings](text, json2.DecoderOptions{}) or { Settings{} } } // QueueState is the queue's cross-session snapshot. The named slots in // Playback > Queues already cover the save-and-recall story; this file only // carries the live queue over a restart, which it never did — the queue // died with the player, so a list built across an evening vanished with it. struct QueueState { pub mut: paths []string } // queue_state_path is /vendetta/queue.json, next to // settings.json. fn queue_state_path() string { return os.join_path(config_base(), 'vendetta', 'queue.json') } // load_queue_state reads the queue snapshot; a missing or malformed file // starts with an empty queue. fn load_queue_state() QueueState { text := os.read_file(queue_state_path()) or { return QueueState{} } return json2.decode[QueueState](text, json2.DecoderOptions{}) or { QueueState{} } } // save_queue_state writes the queue snapshot out now. fn (p &Player) save_queue_state() { paths := p.queue.clone() dir := os.dir(queue_state_path()) os.mkdir_all(dir, os.MkdirParams{}) or {} os.write_file(queue_state_path(), json2.encode(QueueState{ paths: paths }, json2.EncoderOptions{})) or { eprintln('vendetta: could not save the queue: ${err}') } } // collect_settings snapshots the persisted state out of the player. fn (p &Player) collect_settings() Settings { return Settings{ volume: p.volume max_volume: p.max_volume muted: p.muted speed: p.speed ao: p.ao loop_file: p.loop loop_playlist: p.loop_playlist hwdec: p.hwdec deinterlace: p.deinterlace ui_scale: p.ui_scale sub_visible: p.sub_visible aspect: p.aspect rotate: p.rotate zoom: p.zoom windowed_overlay: p.windowed_overlay fullscreen_overlay: p.fullscreen_overlay show_stats: p.show_stats show_queue: p.show_queue show_preview: p.show_preview open_mode: p.open_mode low_quality: p.low_quality continuous: p.continuous smooth_bar: p.smooth_bar slider_height: p.cfg.slider_h show_playback_status: p.show_playback_status show_title_filename: p.show_title_filename theme: p.theme_name preset: p.preset_name media_controls: p.media_controls mpv_opts: p.mpv_opts } } // save_settings writes the current player state out, unless the file already // holds it. Most keys change nothing that is saved, and the debounced save they // schedule then costs an encode instead of a rewrite. fn (mut p Player) save_settings() { text := json2.encode(p.collect_settings(), json2.EncoderOptions{}) if text == p.settings_text { return } dir := os.dir(settings_path()) os.mkdir_all(dir, os.MkdirParams{}) or {} os.write_file(settings_path(), text) or { eprintln('vendetta: could not save settings: ${err}') return } p.settings_text = text } // settings_changed schedules a save a second out, cancelling a pending one, // so dragging the volume slider writes once instead of per tick. fn (mut p Player) settings_changed() { if p.save_timer != 0 { ui2.cancel_timer(p.save_timer) } p.save_timer = ui2.after(1, fn [mut p] () { p.save_settings() }) } // ui_scale_automatic is what the UI scale's automatic choice means: on // Android ui2's own scale is the fit of its design size to the framebuffer, // which follows the created window size and shifts under rotation, so // automatic pins a phone-sized 2.5x; the desktops follow the platform DPI. fn ui_scale_automatic() f64 { mut s := 0.0 $if android { s = 2.5 } return s } // apply_ui_scale pins the window's layout scale; 0 keeps the platform's own. // The video surface scales with the chrome and stays at the framebuffer's // own resolution. fn (p &Player) apply_ui_scale() { ui2.set_scale_override(if p.ui_scale > 0 { p.ui_scale } else { ui_scale_automatic() }) } // apply_settings mirrors the stored state into the player and mpv. fn (mut p Player) apply_settings(s Settings) { p.volume = s.volume if p.volume > s.max_volume { p.volume = s.max_volume } p.max_volume = s.max_volume p.muted = s.muted p.speed = s.speed p.loop = s.loop_file p.loop_playlist = s.loop_playlist p.hwdec = s.hwdec p.deinterlace = s.deinterlace p.ui_scale = s.ui_scale // The scale pins before the window opens; the settings dialog flips it live. p.apply_ui_scale() p.sub_visible = s.sub_visible p.aspect = s.aspect p.rotate = s.rotate p.zoom = s.zoom p.windowed_overlay = s.windowed_overlay p.fullscreen_overlay = s.fullscreen_overlay // If the saved state opens the statistics popup, its once-a-second refresh // timer starts right here, where the plain assignment would leave it stale. p.set_show_stats(s.show_stats) p.show_queue = s.show_queue // The thumbnail instance is built later in main from this same flag, so // a plain assignment is all the saved choice needs here. p.show_preview = s.show_preview p.open_mode = s.open_mode p.low_quality = s.low_quality // The continuous redraw needs no start-up work either: the window opens // with the saved policy and the settings dialog flips it live. p.continuous = s.continuous // The smooth bar needs no start-up work: its glide arms itself from the // first time-pos report, and the chain dies on a pause by itself. p.smooth_bar = s.smooth_bar if s.slider_height > 0 { p.cfg.slider_h = s.slider_height } // The title needs none either: the two rows only reshape what the // property events write, and the window opens before anything plays. p.show_playback_status = s.show_playback_status p.show_title_filename = s.show_title_filename // The desktop media controls start here, before the menu bar is built, // so the Options check row reflects them from the first build. p.media_controls = s.media_controls if s.media_controls { p.start_media_controls() } p.ao = s.ao p.set_theme(s.theme) // The name is only a marker for the Options > Presets checkmark: the // options the preset holds are already in mpv_opts above, so applying // the preset again on start would only replay what the settings carry. p.preset_name = s.preset // The mpv options saved from earlier sessions go in through the property // interface, which answers from initialization on; options mpv can only // take before start report being rejected here, like on the command line. p.mpv_opts = s.mpv_opts.clone() for name, value in p.mpv_opts { if complaint := p.set_mpv_option(name, value) { eprintln('vendetta: saved mpv option ${name}=${value}: ${complaint}') } } mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume) mpv.set_flag_async(p.mpv_ctx, 16, 'mute', p.muted) mpv.set_double_async(p.mpv_ctx, 19, 'speed', p.speed) mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' }) mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' }) mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', libvendetta.hwdec_mode(p.hwdec)) mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' }) mpv.set_flag_async(p.mpv_ctx, 61, 'sub-visibility', p.sub_visible) mpv.set_string_async(p.mpv_ctx, 40, 'video-aspect-override', p.aspect) mpv.set_string_async(p.mpv_ctx, 41, 'video-rotate', p.rotate) mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom) // The audio server is vendetta's own setting: a saved mpv_opts entry for // ao must not resurrect over it. Harmless after initialize — mpv takes // ao whenever no output is open and reloads the open one otherwise. mpv.set_string_async(p.mpv_ctx, 57, 'ao', if p.ao == 'auto' { '' } else { p.ao }) } // apply_cli overlays the command line flags on top of the saved settings: // a flag wins when present, otherwise the saved value stays. fn (mut p Player) apply_cli(cfg Config) { if cfg.theme.len > 0 { p.set_theme(cfg.theme) } // The media-controls flags outrank the saved setting: off wins over on // when both are given, and with neither the saved choice stands. The // service started in apply_settings follows the same transitions. if cfg.no_media_controls { p.set_media_controls(false) } else if cfg.media_controls { p.set_media_controls(true) } // The preview flags outrank the saved setting the same way, off winning // when both are given; staying on builds the thumbnail instance here, // which main's own start-up call then finds already made. if cfg.no_preview { p.set_show_preview(false) } else if cfg.preview { p.set_show_preview(true) } // The smooth-bar flags outrank the saved setting the same way, off winning // when both are given. if cfg.no_smooth_bar { p.smooth_bar = false } else if cfg.smooth_bar { p.smooth_bar = true } if cfg.slider_height > 0 { p.cfg.slider_h = cfg.slider_height } if cfg.volume >= 0 { p.volume = cfg.volume if p.volume > p.max_volume { p.volume = p.max_volume } } if cfg.mute { p.muted = true } if cfg.speed > 0 { p.speed = cfg.speed } if cfg.no_hwdec { p.hwdec = false } else if cfg.hwdec { p.hwdec = true } if cfg.deinterlace { p.deinterlace = true } if cfg.low_quality { p.low_quality = true } if cfg.loop_file { p.loop = true } if cfg.loop_playlist { p.loop_playlist = true } if cfg.no_overlay { p.windowed_overlay = false } else if cfg.overlay { p.windowed_overlay = true } if cfg.fullscreen { p.want_fullscreen = true } start_at := cfg.start_at.trim_space() if start_at.len > 0 { mpv.set_property_string(p.mpv_ctx, 'start', start_at) } sub_file := cfg.sub_file.trim_space() if sub_file.len > 0 { mpv.set_property_string(p.mpv_ctx, 'sub-file', sub_file) } // Mirror everything the renderer reads straight from the player state. mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume) mpv.set_flag_async(p.mpv_ctx, 16, 'mute', p.muted) mpv.set_double_async(p.mpv_ctx, 19, 'speed', p.speed) mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', libvendetta.hwdec_mode(p.hwdec)) mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' }) mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' }) mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' }) // The command line's mpv options go out again through the property // interface: apply_settings has just re-applied whatever the saved // settings hold under the same names, and the command line outranks it. // The write is a synchronous one, but this can still lose to the async // property mirrors above for the options vendetta owns itself (volume, // speed, hwdec...): those land at the next core update and are what the // dedicated flags are for, so --mpv-opt only promises the options vendetta // does not mirror. Accepted entries join player.mpv_opts, so they keep // applying across sessions beside the flags; an empty value unsets one // that was configured earlier. for raw in cfg.mpv_opts { name, value := parse_mpv_option(raw) or { eprintln('vendetta: mpv-opt must be name=value: ${raw}') continue } // Same empty-value rule as the menu: the empty write goes out and // the option leaves the configured set whatever mpv makes of it. if value.len == 0 { p.unset_mpv_option(name) continue } if complaint := p.set_mpv_option(name, value) { eprintln('vendetta: mpv option ${name}=${value}: ${complaint}') continue } p.mpv_opts[name] = value } } // set_mpv_option sets one mpv option and returns mpv's complaint, or none when // the option was accepted. The call waits for mpv's core, so it is for start-up // only, before the first frame; a runtime write goes through send_mpv_option. // Properties and options share one namespace, so option names given like mpv // takes them on the command line work both before and after initialize. fn (mut p Player) set_mpv_option(name string, value string) ?string { rc := mpv.set_property_string(p.mpv_ctx, name, value) if rc < 0 { return mpv.error_string(rc) } return none } // unset_mpv_option drops an mpv option from the configured set and asks mpv // to clear it with an empty value. String options take that; numeric ones // reject the empty write, so their value holds until the restart, where // nothing re-applies it. Either way the option stops coming back, which is // what undoing a mis-set option through the menu needs, so the write's // outcome is not worth an error. fn (mut p Player) unset_mpv_option(name string) { mpv.set_string_async(p.mpv_ctx, option_unset_userdata, name, '') p.mpv_opts.delete(name) } // OptionWrite is a runtime option write that mpv has not answered yet. struct OptionWrite { name string value string // preset is the preset the write came from; empty for the Set option dialog. preset string } // send_mpv_option queues a runtime option write without waiting for mpv's core, // which the render thread must not do. mpv answers with a SET_PROPERTY_REPLY // carrying the id the write was sent with, and option_written reads that answer, // so a rejection still reaches the user. fn (mut p Player) send_mpv_option(w OptionWrite) { p.opt_write_serial++ ud := opt_write_base + p.opt_write_serial rc := mpv.set_string_async(p.mpv_ctx, ud, w.name, w.value) if rc < 0 { p.option_rejected(w, mpv.error_string(rc)) return } p.opt_writes[ud] = w } // option_written applies mpv's answer to a runtime option write. A rejection is // reported where the write came from. An accepted option joins the configured // set, and an accepted dialog write closes the dialog. fn (mut p Player) option_written(ev voidptr) { ud := mpv.event_reply_userdata(ev) w := p.opt_writes[ud] or { return } p.opt_writes.delete(ud) code := mpv.event_error(ev) if code < 0 { p.option_rejected(w, mpv.error_string(code)) return } p.mpv_opts[w.name] = w.value if w.preset.len == 0 { p.mpv_option_open = false } p.settings_changed() ui2.set_menu_bar(p.menus()) } // option_rejected tells the user mpv refused a runtime option write. fn (mut p Player) option_rejected(w OptionWrite, complaint string) { if w.preset.len > 0 { p.notify('Preset ${w.preset}: mpv rejected ${w.name}=${w.value}: ${complaint}') } else { p.notify('mpv rejected ${w.name}=${w.value}: ${complaint}') } }