vendetta / src / settings.v
492 lines · 470 sloc · 17.74 KB · e566477c350a80f9666b93ab0d991ad14f06df91
Raw
1import os
2import ui2
3import libvendetta
4import libvendetta.mpv
5import json2
6
7// Settings is the player state worth keeping between runs. It lives in
8// ~/.config/vendetta/settings.json and is written a second after the last change
9// and again when the window closes.
10struct Settings {
11pub mut:
12 volume f64 = 100
13 max_volume f64 = 100
14 muted bool
15 speed f64 = 1
16 // The audio server: 'auto' is mpv's autoprobing, a name forces one. The
17 // platform's server list validates it on load, so a file carried over
18 // from another OS demotes instead of forcing an absent output.
19 ao string = 'pulse'
20 loop_file bool
21 loop_playlist bool
22 hwdec bool
23 deinterlace bool
24 // The pinned UI scale; 0 is automatic — the platform's own choice, with
25 // a phone-sized default on Android.
26 ui_scale f64
27 sub_visible bool = true
28 aspect string = 'no'
29 rotate string = '0'
30 zoom f64
31 windowed_overlay bool
32 fullscreen_overlay bool = true
33 show_stats bool
34 show_queue bool
35 // Off also keeps the hidden thumbnail mpv instance from ever being
36 // created: an idle second core is pure memory cost.
37 show_preview bool = true
38 open_mode string = 'ask'
39 low_quality bool
40 // The window's redraw policy: ui2 repaints the retained tree every vsync
41 // and rebuilds on ask while it is on. Performance mode forces it off for
42 // the session.
43 continuous bool
44 // The smooth seek bar: the player carries the bar forward at playback speed
45 // between mpv's position reports and redraws the window at the display rate
46 // while it plays.
47 smooth_bar bool
48 theme string = default_theme_name
49 preset string
50 media_controls bool
51 mpv_opts map[string]string
52}
53
54// config_base is the directory vendetta's state lives under — the tree whose
55// vendetta/ subdirectory holds settings.json, themes, queues and presets. It
56// is the platform config directory everywhere else; on Android it is the
57// app's internal files directory, the one location a NativeActivity app may
58// write without storage permissions. The activity's own data path cannot be
59// asked yet (sapp registers it only once its loop runs, and this is read
60// before the window opens), so the package id is taken from the process name
61// — Android names the process after it — and the system's per-user data root
62// spells the rest.
63fn config_base() string {
64 $if android {
65 if text := os.read_file('/proc/self/cmdline') {
66 pkg := text.all_before('\0')
67 if pkg.len > 0 {
68 return os.join_path('/data/user/0', pkg, 'files')
69 }
70 }
71 return os.temp_dir()
72 }
73 return os.user_config_dir() or { os.join_path(os.home_dir(), '.config') }
74}
75
76// migrate_legacy_config imports the previous player's config on the first run
77// after the rename from vore: saved settings, themes, and queues. It only
78// runs while the new directory does not exist, so it happens exactly once;
79// the old directory stays put for hand-checking.
80fn migrate_legacy_config() {
81 home := config_base()
82 old_base := os.join_path(home, 'vore')
83 new_base := os.join_path(home, 'vendetta')
84 if os.exists(new_base) || !os.is_dir(old_base) {
85 return
86 }
87 // The new tree must exist before the first settings save lands.
88 os.mkdir_all(new_base) or { return }
89 os.cp(os.join_path(old_base, 'settings.json'), os.join_path(new_base, 'settings.json')) or {}
90 for sub, ext in {
91 'themes': '.toml'
92 'queues': '.json'
93 'presets': '.json'
94 } {
95 old_sub := os.join_path(old_base, sub)
96 files := os.ls(old_sub) or { continue }
97 new_sub := os.join_path(new_base, sub)
98 os.mkdir_all(new_sub) or { continue }
99 for file in files {
100 if file.ends_with(ext) {
101 os.cp(os.join_path(old_sub, file), os.join_path(new_sub, file)) or {}
102 }
103 }
104 }
105}
106
107// settings_path is <config base>/vendetta/settings.json — ~/.config on the
108// desktops, the app's internal files directory on Android (config_base).
109fn settings_path() string {
110 return os.join_path(config_base(), 'vendetta', 'settings.json')
111}
112
113// load_settings reads the settings file; a missing or malformed file falls
114// back to the compiled-in defaults.
115fn load_settings() Settings {
116 text := os.read_file(settings_path()) or { return Settings{} }
117 return json2.decode[Settings](text, json2.DecoderOptions{}) or { Settings{} }
118}
119
120// QueueState is the queue's cross-session snapshot. The named slots in
121// Playback > Queues already cover the save-and-recall story; this file only
122// carries the live queue over a restart, which it never did — the queue
123// died with the player, so a list built across an evening vanished with it.
124struct QueueState {
125pub mut:
126 paths []string
127}
128
129// queue_state_path is <config base>/vendetta/queue.json, next to
130// settings.json.
131fn queue_state_path() string {
132 return os.join_path(config_base(), 'vendetta', 'queue.json')
133}
134
135// load_queue_state reads the queue snapshot; a missing or malformed file
136// starts with an empty queue.
137fn load_queue_state() QueueState {
138 text := os.read_file(queue_state_path()) or { return QueueState{} }
139 return json2.decode[QueueState](text, json2.DecoderOptions{}) or { QueueState{} }
140}
141
142// save_queue_state writes the queue snapshot out now.
143fn (p &Player) save_queue_state() {
144 paths := p.queue.clone()
145 dir := os.dir(queue_state_path())
146 os.mkdir_all(dir, os.MkdirParams{}) or {}
147 os.write_file(queue_state_path(), json2.encode(QueueState{ paths: paths }, json2.EncoderOptions{})) or {
148 eprintln('vendetta: could not save the queue: ${err}')
149 }
150}
151
152// collect_settings snapshots the persisted state out of the player.
153fn (p &Player) collect_settings() Settings {
154 return Settings{
155 volume: p.volume
156 max_volume: p.max_volume
157 muted: p.muted
158 speed: p.speed
159 ao: p.ao
160 loop_file: p.loop
161 loop_playlist: p.loop_playlist
162 hwdec: p.hwdec
163 deinterlace: p.deinterlace
164 ui_scale: p.ui_scale
165 sub_visible: p.sub_visible
166 aspect: p.aspect
167 rotate: p.rotate
168 zoom: p.zoom
169 windowed_overlay: p.windowed_overlay
170 fullscreen_overlay: p.fullscreen_overlay
171 show_stats: p.show_stats
172 show_queue: p.show_queue
173 show_preview: p.show_preview
174 open_mode: p.open_mode
175 low_quality: p.low_quality
176 continuous: p.continuous
177 smooth_bar: p.smooth_bar
178 theme: p.theme_name
179 preset: p.preset_name
180 media_controls: p.media_controls
181 mpv_opts: p.mpv_opts
182 }
183}
184
185// save_settings writes the current player state out, unless the file already
186// holds it. Most keys change nothing that is saved, and the debounced save they
187// schedule then costs an encode instead of a rewrite.
188fn (mut p Player) save_settings() {
189 text := json2.encode(p.collect_settings(), json2.EncoderOptions{})
190 if text == p.settings_text {
191 return
192 }
193 dir := os.dir(settings_path())
194 os.mkdir_all(dir, os.MkdirParams{}) or {}
195 os.write_file(settings_path(), text) or {
196 eprintln('vendetta: could not save settings: ${err}')
197 return
198 }
199 p.settings_text = text
200}
201
202// settings_changed schedules a save a second out, cancelling a pending one,
203// so dragging the volume slider writes once instead of per tick.
204fn (mut p Player) settings_changed() {
205 if p.save_timer != 0 {
206 ui2.cancel_timer(p.save_timer)
207 }
208 p.save_timer = ui2.after(1, fn [mut p] () {
209 p.save_settings()
210 })
211}
212
213// ui_scale_automatic is what the UI scale's automatic choice means: on
214// Android ui2's own scale is the fit of its design size to the framebuffer,
215// which follows the created window size and shifts under rotation, so
216// automatic pins a phone-sized 2.5x; the desktops follow the platform DPI.
217fn ui_scale_automatic() f64 {
218 mut s := 0.0
219 $if android {
220 s = 2.5
221 }
222 return s
223}
224
225// apply_ui_scale pins the window's layout scale; 0 keeps the platform's own.
226// The video surface scales with the chrome and stays at the framebuffer's
227// own resolution.
228fn (p &Player) apply_ui_scale() {
229 ui2.set_scale_override(if p.ui_scale > 0 { p.ui_scale } else { ui_scale_automatic() })
230}
231
232// apply_settings mirrors the stored state into the player and mpv.
233fn (mut p Player) apply_settings(s Settings) {
234 p.volume = s.volume
235 if p.volume > s.max_volume {
236 p.volume = s.max_volume
237 }
238 p.max_volume = s.max_volume
239 p.muted = s.muted
240 p.speed = s.speed
241 p.loop = s.loop_file
242 p.loop_playlist = s.loop_playlist
243 p.hwdec = s.hwdec
244 p.deinterlace = s.deinterlace
245 p.ui_scale = s.ui_scale
246 // The scale pins before the window opens; View > UI scale flips it live.
247 p.apply_ui_scale()
248 p.sub_visible = s.sub_visible
249 p.aspect = s.aspect
250 p.rotate = s.rotate
251 p.zoom = s.zoom
252 p.windowed_overlay = s.windowed_overlay
253 p.fullscreen_overlay = s.fullscreen_overlay
254 // If the saved state opens the statistics popup, its once-a-second refresh
255 // timer starts right here, where the plain assignment would leave it stale.
256 p.set_show_stats(s.show_stats)
257 p.show_queue = s.show_queue
258 // The thumbnail instance is built later in main from this same flag, so
259 // a plain assignment is all the saved choice needs here.
260 p.show_preview = s.show_preview
261 p.open_mode = s.open_mode
262 p.low_quality = s.low_quality
263 // The continuous redraw needs no start-up work either: the window opens
264 // with the saved policy and View > Continuous redraw flips it live.
265 p.continuous = s.continuous
266 // The smooth bar needs no start-up work: its glide arms itself from the
267 // first time-pos report, and the chain dies on a pause by itself.
268 p.smooth_bar = s.smooth_bar
269 // The desktop media controls start here, before the menu bar is built,
270 // so the Options check row reflects them from the first build.
271 p.media_controls = s.media_controls
272 if s.media_controls {
273 p.start_media_controls()
274 }
275 p.ao = s.ao
276 p.set_theme(s.theme)
277 // The name is only a marker for the Options > Presets checkmark: the
278 // options the preset holds are already in mpv_opts above, so applying
279 // the preset again on start would only replay what the settings carry.
280 p.preset_name = s.preset
281 // The mpv options saved from earlier sessions go in through the property
282 // interface, which answers from initialization on; options mpv can only
283 // take before start report being rejected here, like on the command line.
284 p.mpv_opts = s.mpv_opts.clone()
285 for name, value in p.mpv_opts {
286 if complaint := p.set_mpv_option(name, value) {
287 eprintln('vendetta: saved mpv option ${name}=${value}: ${complaint}')
288 }
289 }
290 mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume)
291 mpv.set_flag_async(p.mpv_ctx, 16, 'mute', p.muted)
292 mpv.set_double_async(p.mpv_ctx, 19, 'speed', p.speed)
293 mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' })
294 mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' })
295 mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', libvendetta.hwdec_mode(p.hwdec))
296 mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' })
297 mpv.set_flag_async(p.mpv_ctx, 61, 'sub-visibility', p.sub_visible)
298 mpv.set_string_async(p.mpv_ctx, 40, 'video-aspect-override', p.aspect)
299 mpv.set_string_async(p.mpv_ctx, 41, 'video-rotate', p.rotate)
300 mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom)
301 // The audio server is vendetta's own setting: a saved mpv_opts entry for
302 // ao must not resurrect over it. Harmless after initialize — mpv takes
303 // ao whenever no output is open and reloads the open one otherwise.
304 mpv.set_string_async(p.mpv_ctx, 57, 'ao', if p.ao == 'auto' { '' } else { p.ao })
305}
306
307// apply_cli overlays the command line flags on top of the saved settings:
308// a flag wins when present, otherwise the saved value stays.
309fn (mut p Player) apply_cli(cfg Config) {
310 if cfg.theme.len > 0 {
311 p.set_theme(cfg.theme)
312 }
313 // The media-controls flags outrank the saved setting: off wins over on
314 // when both are given, and with neither the saved choice stands. The
315 // service started in apply_settings follows the same transitions.
316 if cfg.no_media_controls {
317 p.set_media_controls(false)
318 } else if cfg.media_controls {
319 p.set_media_controls(true)
320 }
321 // The preview flags outrank the saved setting the same way, off winning
322 // when both are given; staying on builds the thumbnail instance here,
323 // which main's own start-up call then finds already made.
324 if cfg.no_preview {
325 p.set_show_preview(false)
326 } else if cfg.preview {
327 p.set_show_preview(true)
328 }
329 // The smooth-bar flags outrank the saved setting the same way, off winning
330 // when both are given.
331 if cfg.no_smooth_bar {
332 p.smooth_bar = false
333 } else if cfg.smooth_bar {
334 p.smooth_bar = true
335 }
336 if cfg.volume >= 0 {
337 p.volume = cfg.volume
338 if p.volume > p.max_volume {
339 p.volume = p.max_volume
340 }
341 }
342 if cfg.mute {
343 p.muted = true
344 }
345 if cfg.speed > 0 {
346 p.speed = cfg.speed
347 }
348 if cfg.no_hwdec {
349 p.hwdec = false
350 } else if cfg.hwdec {
351 p.hwdec = true
352 }
353 if cfg.deinterlace {
354 p.deinterlace = true
355 }
356 if cfg.low_quality {
357 p.low_quality = true
358 }
359 if cfg.loop_file {
360 p.loop = true
361 }
362 if cfg.loop_playlist {
363 p.loop_playlist = true
364 }
365 if cfg.no_overlay {
366 p.windowed_overlay = false
367 } else if cfg.overlay {
368 p.windowed_overlay = true
369 }
370 if cfg.fullscreen {
371 p.want_fullscreen = true
372 }
373 start_at := cfg.start_at.trim_space()
374 if start_at.len > 0 {
375 mpv.set_property_string(p.mpv_ctx, 'start', start_at)
376 }
377 sub_file := cfg.sub_file.trim_space()
378 if sub_file.len > 0 {
379 mpv.set_property_string(p.mpv_ctx, 'sub-file', sub_file)
380 }
381 // Mirror everything the renderer reads straight from the player state.
382 mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume)
383 mpv.set_flag_async(p.mpv_ctx, 16, 'mute', p.muted)
384 mpv.set_double_async(p.mpv_ctx, 19, 'speed', p.speed)
385 mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', libvendetta.hwdec_mode(p.hwdec))
386 mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' })
387 mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' })
388 mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' })
389 // The command line's mpv options go out again through the property
390 // interface: apply_settings has just re-applied whatever the saved
391 // settings hold under the same names, and the command line outranks it.
392 // The write is a synchronous one, but this can still lose to the async
393 // property mirrors above for the options vendetta owns itself (volume,
394 // speed, hwdec...): those land at the next core update and are what the
395 // dedicated flags are for, so --mpv-opt only promises the options vendetta
396 // does not mirror. Accepted entries join player.mpv_opts, so they keep
397 // applying across sessions beside the flags; an empty value unsets one
398 // that was configured earlier.
399 for raw in cfg.mpv_opts {
400 name, value := parse_mpv_option(raw) or {
401 eprintln('vendetta: mpv-opt must be name=value: ${raw}')
402 continue
403 }
404 // Same empty-value rule as the menu: the empty write goes out and
405 // the option leaves the configured set whatever mpv makes of it.
406 if value.len == 0 {
407 p.unset_mpv_option(name)
408 continue
409 }
410 if complaint := p.set_mpv_option(name, value) {
411 eprintln('vendetta: mpv option ${name}=${value}: ${complaint}')
412 continue
413 }
414 p.mpv_opts[name] = value
415 }
416}
417
418// set_mpv_option sets one mpv option and returns mpv's complaint, or none when
419// the option was accepted. The call waits for mpv's core, so it is for start-up
420// only, before the first frame; a runtime write goes through send_mpv_option.
421// Properties and options share one namespace, so option names given like mpv
422// takes them on the command line work both before and after initialize.
423fn (mut p Player) set_mpv_option(name string, value string) ?string {
424 rc := mpv.set_property_string(p.mpv_ctx, name, value)
425 if rc < 0 {
426 return mpv.error_string(rc)
427 }
428 return none
429}
430
431// unset_mpv_option drops an mpv option from the configured set and asks mpv
432// to clear it with an empty value. String options take that; numeric ones
433// reject the empty write, so their value holds until the restart, where
434// nothing re-applies it. Either way the option stops coming back, which is
435// what undoing a mis-set option through the menu needs, so the write's
436// outcome is not worth an error.
437fn (mut p Player) unset_mpv_option(name string) {
438 mpv.set_string_async(p.mpv_ctx, option_unset_userdata, name, '')
439 p.mpv_opts.delete(name)
440}
441
442// OptionWrite is a runtime option write that mpv has not answered yet.
443struct OptionWrite {
444 name string
445 value string
446 // preset is the preset the write came from; empty for the Set option dialog.
447 preset string
448}
449
450// send_mpv_option queues a runtime option write without waiting for mpv's core,
451// which the render thread must not do. mpv answers with a SET_PROPERTY_REPLY
452// carrying the id the write was sent with, and option_written reads that answer,
453// so a rejection still reaches the user.
454fn (mut p Player) send_mpv_option(w OptionWrite) {
455 p.opt_write_serial++
456 ud := opt_write_base + p.opt_write_serial
457 rc := mpv.set_string_async(p.mpv_ctx, ud, w.name, w.value)
458 if rc < 0 {
459 p.option_rejected(w, mpv.error_string(rc))
460 return
461 }
462 p.opt_writes[ud] = w
463}
464
465// option_written applies mpv's answer to a runtime option write. A rejection is
466// reported where the write came from. An accepted option joins the configured
467// set, and an accepted dialog write closes the dialog.
468fn (mut p Player) option_written(ev voidptr) {
469 ud := mpv.event_reply_userdata(ev)
470 w := p.opt_writes[ud] or { return }
471 p.opt_writes.delete(ud)
472 code := mpv.event_error(ev)
473 if code < 0 {
474 p.option_rejected(w, mpv.error_string(code))
475 return
476 }
477 p.mpv_opts[w.name] = w.value
478 if w.preset.len == 0 {
479 p.mpv_option_open = false
480 }
481 p.settings_changed()
482 ui2.set_menu_bar(p.menus())
483}
484
485// option_rejected tells the user mpv refused a runtime option write.
486fn (mut p Player) option_rejected(w OptionWrite, complaint string) {
487 if w.preset.len > 0 {
488 p.notify('Preset ${w.preset}: mpv rejected ${w.name}=${w.value}: ${complaint}')
489 } else {
490 p.notify('mpv rejected ${w.name}=${w.value}: ${complaint}')
491 }
492}
493