vendetta / src / settings.v
431 lines · 413 sloc · 15.71 KB · 77754ad9e6dc749afefba326ff89abc5ddd8c9c9
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.
186fn (p &Player) save_settings() {
187 dir := os.dir(settings_path())
188 os.mkdir_all(dir, os.MkdirParams{}) or {}
189 os.write_file(settings_path(), json2.encode(p.collect_settings(), json2.EncoderOptions{})) or {
190 eprintln('vendetta: could not save settings: ${err}')
191 }
192}
193
194// settings_changed schedules a save a second out, cancelling a pending one,
195// so dragging the volume slider writes once instead of per tick.
196fn (mut p Player) settings_changed() {
197 if p.save_timer != 0 {
198 ui2.cancel_timer(p.save_timer)
199 }
200 p.save_timer = ui2.after(1, fn [mut p] () {
201 p.save_settings()
202 })
203}
204
205// ui_scale_automatic is what the UI scale's automatic choice means: on
206// Android ui2's own scale is the fit of its design size to the framebuffer,
207// which follows the created window size and shifts under rotation, so
208// automatic pins a phone-sized 2.5x; the desktops follow the platform DPI.
209fn ui_scale_automatic() f64 {
210 mut s := 0.0
211 $if android {
212 s = 2.5
213 }
214 return s
215}
216
217// apply_ui_scale pins the window's layout scale; 0 keeps the platform's own.
218// The video surface scales with the chrome and stays at the framebuffer's
219// own resolution.
220fn (p &Player) apply_ui_scale() {
221 ui2.set_scale_override(if p.ui_scale > 0 { p.ui_scale } else { ui_scale_automatic() })
222}
223
224// apply_settings mirrors the stored state into the player and mpv.
225fn (mut p Player) apply_settings(s Settings) {
226 p.volume = s.volume
227 if p.volume > s.max_volume {
228 p.volume = s.max_volume
229 }
230 p.max_volume = s.max_volume
231 p.muted = s.muted
232 p.speed = s.speed
233 p.loop = s.loop_file
234 p.loop_playlist = s.loop_playlist
235 p.hwdec = s.hwdec
236 p.deinterlace = s.deinterlace
237 p.ui_scale = s.ui_scale
238 // The scale pins before the window opens; View > UI scale flips it live.
239 p.apply_ui_scale()
240 p.sub_visible = s.sub_visible
241 p.aspect = s.aspect
242 p.rotate = s.rotate
243 p.zoom = s.zoom
244 p.windowed_overlay = s.windowed_overlay
245 p.fullscreen_overlay = s.fullscreen_overlay
246 // If the saved state opens the statistics popup, its once-a-second refresh
247 // timer starts right here, where the plain assignment would leave it stale.
248 p.set_show_stats(s.show_stats)
249 p.show_queue = s.show_queue
250 // The thumbnail instance is built later in main from this same flag, so
251 // a plain assignment is all the saved choice needs here.
252 p.show_preview = s.show_preview
253 p.open_mode = s.open_mode
254 p.low_quality = s.low_quality
255 // The continuous redraw needs no start-up work either: the window opens
256 // with the saved policy and View > Continuous redraw flips it live.
257 p.continuous = s.continuous
258 // The smooth bar needs no start-up work: its glide arms itself from the
259 // first time-pos report, and the chain dies on a pause by itself.
260 p.smooth_bar = s.smooth_bar
261 // The desktop media controls start here, before the menu bar is built,
262 // so the Options check row reflects them from the first build.
263 p.media_controls = s.media_controls
264 if s.media_controls {
265 p.start_media_controls()
266 }
267 p.ao = s.ao
268 p.set_theme(s.theme)
269 // The name is only a marker for the Options > Presets checkmark: the
270 // options the preset holds are already in mpv_opts above, so applying
271 // the preset again on start would only replay what the settings carry.
272 p.preset_name = s.preset
273 // The mpv options saved from earlier sessions go in through the property
274 // interface, which answers from initialization on; options mpv can only
275 // take before start report being rejected here, like on the command line.
276 p.mpv_opts = s.mpv_opts.clone()
277 for name, value in p.mpv_opts {
278 if complaint := p.set_mpv_option(name, value) {
279 eprintln('vendetta: saved mpv option ${name}=${value}: ${complaint}')
280 }
281 }
282 mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume)
283 mpv.set_flag_async(p.mpv_ctx, 16, 'mute', p.muted)
284 mpv.set_double_async(p.mpv_ctx, 19, 'speed', p.speed)
285 mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' })
286 mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' })
287 mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', libvendetta.hwdec_mode(p.hwdec))
288 mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' })
289 mpv.set_flag_async(p.mpv_ctx, 61, 'sub-visibility', p.sub_visible)
290 mpv.set_string_async(p.mpv_ctx, 40, 'video-aspect-override', p.aspect)
291 mpv.set_string_async(p.mpv_ctx, 41, 'video-rotate', p.rotate)
292 mpv.set_double_async(p.mpv_ctx, 44, 'video-zoom', p.zoom)
293 // The audio server is vendetta's own setting: a saved mpv_opts entry for
294 // ao must not resurrect over it. Harmless after initialize — mpv takes
295 // ao whenever no output is open and reloads the open one otherwise.
296 mpv.set_string_async(p.mpv_ctx, 57, 'ao', if p.ao == 'auto' { '' } else { p.ao })
297}
298
299// apply_cli overlays the command line flags on top of the saved settings:
300// a flag wins when present, otherwise the saved value stays.
301fn (mut p Player) apply_cli(cfg Config) {
302 if cfg.theme.len > 0 {
303 p.set_theme(cfg.theme)
304 }
305 // The media-controls flags outrank the saved setting: off wins over on
306 // when both are given, and with neither the saved choice stands. The
307 // service started in apply_settings follows the same transitions.
308 if cfg.no_media_controls {
309 p.set_media_controls(false)
310 } else if cfg.media_controls {
311 p.set_media_controls(true)
312 }
313 // The preview flags outrank the saved setting the same way, off winning
314 // when both are given; staying on builds the thumbnail instance here,
315 // which main's own start-up call then finds already made.
316 if cfg.no_preview {
317 p.set_show_preview(false)
318 } else if cfg.preview {
319 p.set_show_preview(true)
320 }
321 // The smooth-bar flags outrank the saved setting the same way, off winning
322 // when both are given.
323 if cfg.no_smooth_bar {
324 p.smooth_bar = false
325 } else if cfg.smooth_bar {
326 p.smooth_bar = true
327 }
328 if cfg.volume >= 0 {
329 p.volume = cfg.volume
330 if p.volume > p.max_volume {
331 p.volume = p.max_volume
332 }
333 }
334 if cfg.mute {
335 p.muted = true
336 }
337 if cfg.speed > 0 {
338 p.speed = cfg.speed
339 }
340 if cfg.no_hwdec {
341 p.hwdec = false
342 } else if cfg.hwdec {
343 p.hwdec = true
344 }
345 if cfg.deinterlace {
346 p.deinterlace = true
347 }
348 if cfg.low_quality {
349 p.low_quality = true
350 }
351 if cfg.loop_file {
352 p.loop = true
353 }
354 if cfg.loop_playlist {
355 p.loop_playlist = true
356 }
357 if cfg.no_overlay {
358 p.windowed_overlay = false
359 } else if cfg.overlay {
360 p.windowed_overlay = true
361 }
362 if cfg.fullscreen {
363 p.want_fullscreen = true
364 }
365 start_at := cfg.start_at.trim_space()
366 if start_at.len > 0 {
367 mpv.set_property_string(p.mpv_ctx, 'start', start_at)
368 }
369 sub_file := cfg.sub_file.trim_space()
370 if sub_file.len > 0 {
371 mpv.set_property_string(p.mpv_ctx, 'sub-file', sub_file)
372 }
373 // Mirror everything the renderer reads straight from the player state.
374 mpv.set_double_async(p.mpv_ctx, 12, 'volume', p.volume)
375 mpv.set_flag_async(p.mpv_ctx, 16, 'mute', p.muted)
376 mpv.set_double_async(p.mpv_ctx, 19, 'speed', p.speed)
377 mpv.set_string_async(p.mpv_ctx, 43, 'hwdec', libvendetta.hwdec_mode(p.hwdec))
378 mpv.set_string_async(p.mpv_ctx, 42, 'deinterlace', if p.deinterlace { 'yes' } else { 'no' })
379 mpv.set_string_async(p.mpv_ctx, 15, 'loop-file', if p.loop { 'inf' } else { 'no' })
380 mpv.set_string_async(p.mpv_ctx, 54, 'loop-playlist', if p.loop_playlist { 'inf' } else { 'no' })
381 // The command line's mpv options go out again through the property
382 // interface: apply_settings has just re-applied whatever the saved
383 // settings hold under the same names, and the command line outranks it.
384 // The write is a synchronous one, but this can still lose to the async
385 // property mirrors above for the options vendetta owns itself (volume,
386 // speed, hwdec...): those land at the next core update and are what the
387 // dedicated flags are for, so --mpv-opt only promises the options vendetta
388 // does not mirror. Accepted entries join player.mpv_opts, so they keep
389 // applying across sessions beside the flags; an empty value unsets one
390 // that was configured earlier.
391 for raw in cfg.mpv_opts {
392 name, value := parse_mpv_option(raw) or {
393 eprintln('vendetta: mpv-opt must be name=value: ${raw}')
394 continue
395 }
396 // Same empty-value rule as the menu: the empty write goes out and
397 // the option leaves the configured set whatever mpv makes of it.
398 if value.len == 0 {
399 p.unset_mpv_option(name)
400 continue
401 }
402 if complaint := p.set_mpv_option(name, value) {
403 eprintln('vendetta: mpv option ${name}=${value}: ${complaint}')
404 continue
405 }
406 p.mpv_opts[name] = value
407 }
408}
409
410// set_mpv_option sets one mpv option on the playing instance and returns
411// mpv's complaint, or none when the option was accepted. Properties and
412// options share one namespace, so option names given like mpv takes them on
413// the command line work both before and after initialize.
414fn (mut p Player) set_mpv_option(name string, value string) ?string {
415 rc := mpv.set_property_string(p.mpv_ctx, name, value)
416 if rc < 0 {
417 return mpv.error_string(rc)
418 }
419 return none
420}
421
422// unset_mpv_option drops an mpv option from the configured set and asks mpv
423// to clear it with an empty value. String options take that; numeric ones
424// reject the empty write, so their value holds until the restart, where
425// nothing re-applies it. Either way the option stops coming back, which is
426// what undoing a mis-set option through the menu needs, so the write's
427// outcome is not worth an error.
428fn (mut p Player) unset_mpv_option(name string) {
429 mpv.set_property_string(p.mpv_ctx, name, '')
430 p.mpv_opts.delete(name)
431}
432