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