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