-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
1044 lines (1001 loc) Β· 48.3 KB
/
Copy pathlib.rs
File metadata and controls
1044 lines (1001 loc) Β· 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! WaveFlow Tauri backend entry point.
//!
//! Sets up tracing, resolves filesystem paths, opens the global `app.db`
//! (running any pending migrations) and exposes the initial set of Tauri
//! commands to the frontend.
mod analysis;
mod audio;
mod backup;
mod commands;
mod db;
mod discord_presence;
mod dlna;
mod error;
mod logging;
mod media_controls;
mod metadata_artwork;
mod notifications;
mod offline;
mod paths;
mod queue;
mod scrobbler;
#[cfg(feature = "sync_v1")]
mod server_client;
mod smart_playlists;
// `mod spotify` was extracted to the `waveflow-spotify` workspace crate.
// `crate::commands::spotify` now imports from `waveflow_spotify::*` and
// passes raw `&SqlitePool` handles in lieu of `&AppState`. Same pattern
// as `waveflow-syncedlyrics`.
mod state;
// Multi-device sync (Phase 1.f, RFC-003). When the `sync_v1` feature
// is OFF (1.5.0 default), `mod sync` resolves to `sync_stub.rs` β
// a no-op surface that matches the real public API so the ~70 emit
// call sites in `commands/{library,playlist,track,scan,duplicates}`
// compile unchanged. See `sync_stub.rs` for the short-circuit
// semantics and `Cargo.toml` for the rationale.
#[cfg(feature = "sync_v1")]
mod sync;
#[cfg(not(feature = "sync_v1"))]
#[path = "sync_stub.rs"]
mod sync;
mod thumbnails;
mod watcher;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tauri::{
menu::{Menu, MenuItem, PredefinedMenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
AppHandle, Listener, Manager, WindowEvent,
};
use audio::{AudioCmd, AudioEngine};
use queue::Direction;
use state::AppState;
use watcher::WatcherManager;
/// Set to `true` by the tray "Quit" menu before calling `app.exit()`.
/// `WindowEvent::CloseRequested` checks the flag: if armed, the close
/// proceeds to actual shutdown; otherwise the close is intercepted and
/// the window is hidden instead (close-to-tray default).
struct QuitGate(AtomicBool);
const TRAY_ID: &str = "waveflow";
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// Initialize structured logging. `RUST_LOG` overrides the default
// filter. The returned guard owns the non-blocking file writer's
// background thread and must be held until the process exits β a
// dropped guard flushes and closes the file early, losing the tail
// of the log right when a crash report is most useful.
let _log_guard = logging::init_tracing();
// `mut` is only consumed when the updater plugin is wired in (release
// builds); the lint would fire in debug otherwise.
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
// Single-instance MUST be the first plugin so a second launch
// exits cleanly before any heavy init (pool open, audio engine,
// tray, watchers) runs in the duplicate process.
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}))
// Autostart wiring. Pass `--minimized` so the OS-launched
// instance shows up in the tray without grabbing focus β the
// user expressed intent to "start with the system", not "open
// a window every boot". The frontend reads `?autostart=1` from
// `argv` if it ever wants to surface a "launched on boot"
// banner; not used today.
.plugin(tauri_plugin_autostart::init(
tauri_plugin_autostart::MacosLauncher::LaunchAgent,
Some(vec!["--minimized"]),
))
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_notification::init());
// Auto-updater is wired in release builds only. In dev (`tauri dev`)
// the binary points at the local source tree, the version is the
// working copy, and there's no signed manifest to fetch β the
// plugin would just spam errors. Ship-only by design.
//
// Also gated on the `updater` Cargo feature (default-on) so the
// Flatpak / app-store builds can compile it out β those channels
// manage updates themselves and the in-app updater would clash
// with their read-only install root.
#[cfg(all(not(debug_assertions), feature = "updater"))]
{
builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
}
builder
.manage(QuitGate(AtomicBool::new(false)))
.setup(|app| {
let init_handle = app.handle().clone();
let engine_handle = app.handle().clone();
// Block on the async init β this runs once at startup before any
// command can be dispatched, so blocking here is acceptable.
let state =
tauri::async_runtime::block_on(async move { AppState::init(&init_handle).await })?;
// Hydrate the close-to-tray flag once at boot. The atomic
// is the source of truth for `WindowEvent::CloseRequested`
// so it has to be in place before the first user input.
let minimize_to_tray = tauri::async_runtime::block_on(
commands::preferences::load_minimize_to_tray(&state.app_db),
);
app.manage(commands::preferences::PreferencesState::new(
minimize_to_tray,
));
app.manage(state);
// Plugin SDK epoch ticker. Wasmtime's epoch-interruption
// deadline only fires when something is bumping the
// engine's epoch counter β the runtime's `set_epoch_deadline`
// is expressed in ticks, not wall-clock, so without a
// ticker a runaway guest call would never trap. 10 ms
// cadence matches `RuntimeConfig::epoch_ticks_per_call`'s
// 3 000-tick default = ~30 s wall-clock per call. Cheap
// β one atomic increment per tick, the tokio interval
// handle keeps no allocator pressure.
let plugin_ticker_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let runtime = plugin_ticker_handle
.state::<AppState>()
.plugins
.clone();
let mut interval =
tokio::time::interval(std::time::Duration::from_millis(10));
interval.set_missed_tick_behavior(
tokio::time::MissedTickBehavior::Skip,
);
loop {
interval.tick().await;
runtime.tick_epoch();
}
});
// Sync drain task β pushes pending `sync_pending_op`
// rows to the waveflow-server in the background. Spawned
// here so it picks up `AppState` from `app.manage(state)`
// above. Wake handle already lives in `AppState::drain`,
// so CRUD commands can `state.drain.notify()` after a
// successful tx.commit() without needing a separate
// import path.
// Sync background tasks (drain push, auto-backfill on boot,
// heartbeat tick, WS subscriber) + the rustls CryptoProvider
// they need β all gated behind the `sync_v1` feature. With
// 1.5.0's sync_v1 OFF the stub `mod sync` doesn't expose
// `spawn`/`heartbeat::spawn`/etc., so the spawn sites would
// fail to resolve unless cfg-gated here.
#[cfg(feature = "sync_v1")]
{
sync::drain::spawn(app.handle().clone());
// RFC-003 Phase B.2 β fire a one-shot auto-backfill
// pass on boot when the user opted in via
// `sync.v2.backfill_enabled`. All gates (offline /
// SyncMode::Local / no JWT / no profile canonical)
// short-circuit silently inside `maybe_auto_backfill`,
// so this is safe to fire unconditionally β the helper
// owns the gate logic.
let boot_handle = app.handle().clone();
// `setup` runs OUTSIDE a tokio reactor, so a bare
// `tokio::spawn` panics with "no reactor running".
// `tauri::async_runtime::spawn` resolves to the Tauri-
// managed tokio runtime β same pattern `sync::drain::spawn`
// documents at its own spawn site.
tauri::async_runtime::spawn(async move {
use tauri::Manager;
let state = boot_handle.state::<state::AppState>();
if let Err(err) = sync::backfill::maybe_auto_backfill(state.inner()).await {
tracing::warn!(error = %err, "auto-backfill on boot failed");
}
});
// RFC-003 Phase B polish β periodic heartbeat that fires
// `maybe_auto_backfill` every
// `sync.backfill.heartbeat_interval_min` minutes (default
// 60 min). Same gates as the boot pass short-circuit
// inside the helper, so a Local / offline / no-JWT
// session spins idle without cost. Cadence is re-read at
// every tick from the active profile's
// `profile_setting`, so changing it from Settings applies
// on the next iteration without restart.
sync::backfill::heartbeat::spawn(app.handle().clone());
// Install the rustls process-wide CryptoProvider before
// the WS subscriber spawns. rustls 0.23 panics on the
// first TLS handshake when no provider is installed, and
// tokio-tungstenite's `connect_async` is the first
// wss:// consumer in the codebase (reqwest uses its own
// per-connector setup). Ignore the Result β a second
// call (e.g. after a future reqwest version starts
// installing one) returns Err which is harmless here.
let _ = rustls::crypto::ring::default_provider().install_default();
// Sync WebSocket subscriber + catch-up pull (Phase
// 1.f.desktop.4b). Closes the loop: drain pushes local
// edits upstream, ws subscribes to other devices'. Both
// gate on `mode = Hybrid` + a configured JWT, so a
// local-only profile spawns the task but its gates
// short-circuit every pass without HTTP.
sync::ws::spawn(app.handle().clone());
}
// Audio engine lives alongside AppState. `new` spawns the cpal
// output thread (silence callback) and the decoder thread, both
// receiving a clone of the AppHandle so they can emit Tauri
// events (player:position, player:state, player:track-ended,
// player:error) directly.
//
// Pull the persisted output-device name (if any) from the
// active profile so the user lands on whatever output they
// last picked instead of the OS default. Empty string in
// the row means "follow the OS default" β see
// `player_set_output_device`.
let (persisted_device, persisted_wasapi_exclusive) =
tauri::async_runtime::block_on(async {
let state = app.state::<AppState>();
let Ok(pool) = state.require_profile_pool().await else {
return (None, false);
};
let device: Option<String> = sqlx::query_scalar(
"SELECT value FROM profile_setting WHERE key = 'audio.output_device'",
)
.fetch_optional(&pool)
.await
.ok()
.flatten()
.filter(|s: &String| !s.is_empty());
let exclusive: bool = sqlx::query_scalar::<_, String>(
"SELECT value FROM profile_setting WHERE key = 'audio.wasapi_exclusive'",
)
.fetch_optional(&pool)
.await
.ok()
.flatten()
.map(|s| s == "1" || s == "true")
.unwrap_or(false);
(device, exclusive)
});
let engine: Arc<AudioEngine> = AudioEngine::new_with_device(
engine_handle,
persisted_device,
persisted_wasapi_exclusive,
);
app.manage(engine);
// Filesystem watcher manager. Holds one notify watcher per
// `library_folder.is_watched=1` row in the active profile;
// the boot-time hydration walks the DB and arms each one
// so users don't need to re-toggle after a restart.
let watcher_handle = app.handle().clone();
let watcher = Arc::new(WatcherManager::new(watcher_handle));
let watcher_for_init = watcher.clone();
let restore_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let state = restore_handle.state::<AppState>();
if let Ok(pool) = state.require_profile_pool().await {
if let Err(err) = watcher_for_init.restore_from_db(&pool).await {
tracing::warn!(%err, "watcher boot restore failed");
}
}
});
app.manage(watcher);
// Scan-on-start. Honours `profile_setting['library.scan_on_start']`
// (default OFF β opt in so power users with terabyte libraries
// don't pay the I/O at every launch). The rescan walks every
// `library_folder` row of the active profile and runs the
// same `scan_folder_inner` path the manual "Rescan" button
// uses, so the `scan:progress` toast surfaces automatically.
// Fire-and-forget β failures log but never block startup.
let scan_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let state = scan_handle.state::<AppState>();
let Ok(pool) = state.require_profile_pool().await else {
return;
};
let enabled: bool = sqlx::query_scalar::<_, String>(
"SELECT value FROM profile_setting WHERE key = 'library.scan_on_start'",
)
.fetch_optional(&pool)
.await
.ok()
.flatten()
.map(|v| v == "true" || v == "1")
.unwrap_or(false);
if !enabled {
return;
}
let Ok(profile_id) = state.require_profile_id().await else {
return;
};
let artwork_dir = state.paths.profile_artwork_dir(profile_id);
let folder_ids: Vec<i64> =
match sqlx::query_scalar("SELECT id FROM library_folder ORDER BY id")
.fetch_all(&pool)
.await
{
Ok(rows) => rows,
Err(err) => {
tracing::warn!(%err, "scan-on-start: list folders failed");
return;
}
};
for folder_id in folder_ids {
if let Err(err) = commands::scan::scan_folder_inner(
&pool,
&artwork_dir,
folder_id,
Some(&scan_handle),
)
.await
{
tracing::warn!(folder_id, %err, "scan-on-start: folder scan failed");
}
}
});
// OS media controls (SMTC / MPRIS / MediaRemote) via
// souvlaki. Needs the main window to exist for HWND on
// Windows; on Linux/macOS the platform integration owns
// its own connection. Failure is non-fatal β playback
// keeps working without the OS overlay.
if let Some(controls) = media_controls::init(app.handle().clone()) {
app.manage(controls);
}
// Discord Rich Presence. Always spawn the worker thread β
// it stays idle until the user flips the opt-in toggle.
// Reading the persisted flag here means the activity is
// restored on the very next track-changed event without
// waiting for the Settings view to mount.
let initial_rpc_enabled = tauri::async_runtime::block_on(async {
let state = app.state::<AppState>();
discord_presence::read_enabled(&state.app_db).await
});
if let Some(presence) = discord_presence::init(initial_rpc_enabled) {
app.manage(presence);
}
// Last.fm scrobble worker. Polls scrobble_queue every 30 s
// and posts eligible items to track.scrobble; survives
// profile switches because it always reads the active
// profile's pool fresh per tick.
scrobbler::spawn(app.handle().clone());
// Auto-backup loop. Idle while `backup.enabled` is off
// (parks on a Notify channel), wakes immediately when the
// user toggles via Settings. See [`backup`] module docs.
let backup_handle = backup::BackupHandle::new();
app.manage(backup_handle.clone());
backup::spawn_backup_loop(app.handle().clone(), backup_handle);
// DLNA / UPnP MediaServer auto-start. Reads the persisted
// `dlna.enabled` flag at boot and forwards the config to
// the worker so users don't have to flip the toggle every
// launch. Failure is non-fatal β the Settings page will
// surface `last_error` next time the user opens it.
tauri::async_runtime::spawn({
let handle = app.handle().clone();
async move {
let state = handle.state::<AppState>();
let cfg = match dlna::config::load(&state.app_db).await {
Ok(c) => c,
Err(err) => {
tracing::warn!(?err, "DLNA config load failed");
return;
}
};
if cfg.enabled {
match commands::dlna::build_resources(&state).await {
Ok(resources) => state.dlna.start(cfg, resources),
Err(err) => tracing::warn!(?err, "DLNA boot resources unavailable"),
}
}
}
});
// System tray (status icon).
//
// Labels are seeded in English because Rust runs before the
// frontend has had a chance to load i18next; the React layer
// pushes a localised set via `set_tray_labels` once
// `i18nReady` resolves, and again on every `languageChanged`
// event. The `MenuItem` handles are stashed in
// `TrayMenuItems` so retitling doesn't rebuild the menu.
// Left-click on the icon mirrors "Open WaveFlow" for the
// common case where the window was hidden via the
// close-to-tray path. Tooltip is updated to "Title β Artist"
// by `commands::player::emit_track_changed` whenever a new
// track starts.
let play_pause_item =
MenuItem::with_id(app, "play_pause", "Play / Pause", true, None::<&str>)?;
let previous_item = MenuItem::with_id(app, "previous", "Previous", true, None::<&str>)?;
let next_item = MenuItem::with_id(app, "next", "Next", true, None::<&str>)?;
let show_item = MenuItem::with_id(app, "show", "Open WaveFlow", true, None::<&str>)?;
let quit_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
let menu = Menu::with_items(
app,
&[
&play_pause_item,
&previous_item,
&next_item,
&PredefinedMenuItem::separator(app)?,
&show_item,
&PredefinedMenuItem::separator(app)?,
&quit_item,
],
)?;
app.manage(commands::tray::TrayMenuItems {
play_pause: play_pause_item,
previous: previous_item,
next: next_item,
show: show_item,
quit: quit_item,
});
let icon = app
.default_window_icon()
.cloned()
.ok_or("default window icon missing")?;
TrayIconBuilder::with_id(TRAY_ID)
.icon(icon)
.menu(&menu)
.show_menu_on_left_click(false)
.tooltip("WaveFlow")
.on_menu_event(|app, event| match event.id.as_ref() {
"play_pause" => toggle_play_pause(app),
"previous" => spawn_previous(app),
"next" => spawn_next(app),
"show" => show_main_window(app),
"quit" => request_quit(app),
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
show_main_window(tray.app_handle());
}
})
.build(app)?;
// Splash β main handoff.
//
// The frontend emits `app://ready` once the React root has
// committed its first useful paint (see src/main.tsx). When
// we get that event we close the splash and reveal the
// main window from native code β more reliable than the
// previous IPC dance, which on Linux WebKitGTK 2.52 raced
// against the heavy first-launch init (migrations + DB
// pool + library scan) and left the splash hanging
// forever (issue #42).
//
// A 15 s safety-net timer force-reveals the main window if
// `app://ready` never fires β guards against a frontend
// crash leaving the user stuck on an eternal splash.
let handoff_done = Arc::new(AtomicBool::new(false));
let handoff_handle = app.handle().clone();
let handoff_done_for_event = handoff_done.clone();
app.listen("app://ready", move |_event| {
if handoff_done_for_event.swap(true, Ordering::SeqCst) {
return;
}
// Reset the flag if the reveal fails so the fallback
// timer (or a subsequent `app://ready` re-emission) can
// retry β otherwise a transient main.show() / splash.close()
// failure would leave the user stuck on an eternal splash
// with no recovery path.
if !reveal_main_close_splash(&handoff_handle) {
handoff_done_for_event.store(false, Ordering::SeqCst);
}
});
let fallback_handle = app.handle().clone();
let fallback_done = handoff_done.clone();
tauri::async_runtime::spawn(async move {
// First attempt after 15 s; subsequent retries every
// 250 ms up to 10 total attempts. Bounded so a
// permanently missing main window doesn't spin forever
// (the warn! log surfaces it instead). The retry exists
// because `ReadySignal` only emits `app://ready` once
// at mount β if we lost the race with that single
// event AND the first reveal failed, without a retry
// the user would be stuck on the splash.
tokio::time::sleep(Duration::from_secs(15)).await;
for attempt in 0..10 {
if fallback_done.swap(true, Ordering::SeqCst) {
return;
}
tracing::warn!(
attempt,
"splash handoff fallback: `app://ready` never fired in time, force-revealing main window"
);
if reveal_main_close_splash(&fallback_handle) {
return;
}
fallback_done.store(false, Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(250)).await;
}
tracing::error!(
"splash handoff fallback: exhausted 10 reveal attempts, user is likely stuck on splash"
);
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::app_info::get_app_info,
commands::app_info::open_data_folder,
commands::changelog::get_changelog,
commands::diagnostics::get_log_dir,
commands::diagnostics::open_log_folder,
commands::diagnostics::read_recent_logs,
commands::profile::list_profiles,
commands::profile::get_active_profile,
commands::profile::create_profile,
commands::profile::rename_profile,
commands::profile::switch_profile,
commands::profile::deactivate_profile,
commands::profile::delete_profile,
commands::profile::get_profile_setting,
commands::profile::set_profile_setting,
commands::profile_io::export_profile,
commands::profile_io::import_profile,
commands::library::list_libraries,
commands::library::create_library,
commands::library::update_library,
commands::library::delete_library,
commands::library::rescan_library,
commands::library::add_folder_to_library,
commands::library::list_library_folders,
commands::library::set_folder_watched,
commands::library::remove_folder_from_library,
commands::library::import_paths,
commands::duplicates::find_duplicates,
commands::duplicates::delete_tracks,
commands::analysis::analyze_track,
commands::analysis::analyze_library,
commands::analysis::cancel_library_analysis,
commands::analysis::get_track_analysis,
commands::analysis::get_auto_analyze,
commands::analysis::set_auto_analyze,
commands::playlist::list_playlists,
commands::playlist::get_playlist,
commands::playlist::create_playlist,
commands::playlist::update_playlist,
commands::playlist::delete_playlist,
commands::playlist::list_playlist_tracks,
commands::playlist::list_playlists_containing_track,
commands::playlist::add_track_to_playlist,
commands::playlist::add_tracks_to_playlist,
commands::playlist::remove_track_from_playlist,
commands::playlist::reorder_playlist_track,
commands::playlist::add_source_to_playlist,
commands::playlist::export_playlist_m3u,
commands::playlist::import_playlist_m3u,
commands::playlist_cover::set_playlist_cover_from_file,
commands::playlist_cover::regenerate_playlist_auto_cover,
commands::playlist_cover::clear_playlist_cover,
commands::smart_playlists::regenerate_daily_mixes,
commands::smart_playlists::regenerate_on_repeat,
commands::smart_playlists::regenerate_all_smart_playlists,
commands::smart_playlists::create_custom_smart_playlist,
commands::smart_playlists::update_custom_smart_playlist,
commands::smart_playlists::regenerate_custom_smart_playlist,
commands::smart_playlists::get_custom_smart_playlist_rules,
commands::smart_playlists::preview_custom_smart_playlist,
commands::scan::scan_folder,
commands::scan::rescan_local_artist_images,
commands::deezer::search_artists_deezer,
commands::deezer::set_artist_artwork_from_deezer,
commands::deezer::set_artist_artwork_from_file,
commands::deezer::clear_artist_artwork,
commands::track::list_tracks,
commands::track::get_track,
commands::track::search_tracks,
commands::track::search_tracks_advanced,
commands::edit::update_track_tags,
commands::edit::update_tracks_batch,
commands::edit::update_track_cover,
commands::track::toggle_like_track,
commands::track::list_liked_track_ids,
commands::track::list_liked_tracks,
commands::track::set_track_rating,
commands::browse::list_albums,
commands::browse::list_artists,
commands::browse::list_genres,
commands::browse::list_folders,
commands::browse::list_recent_plays,
commands::browse::list_play_history,
commands::browse::play_history_months,
commands::browse::get_profile_stats,
commands::browse::get_album_detail,
commands::browse::get_artist_detail,
commands::browse::get_genre_detail,
commands::deezer::enrich_album_deezer,
commands::deezer::enrich_artist_deezer,
commands::deezer::search_albums_deezer,
commands::deezer::set_album_artwork_from_deezer,
commands::deezer::set_album_artwork_from_file,
commands::deezer::batch_fetch_missing_album_covers,
commands::deezer::batch_fetch_missing_artist_pictures,
commands::similar::get_similar_artists,
commands::radio::start_radio,
commands::mood_radio::start_mood_radio,
commands::mood_radio::mood_radio_counts,
commands::dlna::dlna_get_config,
commands::dlna::dlna_set_config,
commands::dlna::dlna_get_status,
commands::plugins::list_installed_plugins,
commands::plugins::get_plugin_info,
commands::plugins::set_plugin_enabled,
commands::plugins::uninstall_plugin,
commands::plugins::plugin_list_entries,
commands::plugins::plugin_resolve,
commands::plugins::plugin_stream_url,
commands::integration::get_lastfm_api_key,
commands::integration::set_lastfm_api_key,
commands::integration::get_lastfm_api_secret,
commands::integration::set_lastfm_api_secret,
commands::integration::lastfm_get_status,
commands::integration::lastfm_login,
commands::integration::lastfm_logout,
commands::integration::get_discord_rpc_enabled,
commands::integration::set_discord_rpc_enabled,
commands::integration::get_notifications_track_change,
commands::integration::set_notifications_track_change,
commands::spotify::get_spotify_client_id,
commands::spotify::set_spotify_client_id,
commands::spotify::spotify_get_status,
commands::spotify::spotify_login,
commands::spotify::spotify_logout,
commands::spotify::spotify_get_access_token,
commands::spotify::spotify_list_playlists,
commands::spotify::spotify_get_playlist_tracks,
commands::spotify::spotify_get_queue,
commands::spotify::spotify_search,
commands::spotify::spotify_pause_local,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_get_status,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_set_url,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_set_web_url,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_set_token,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_sign_out,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_open_login_browser,
#[cfg(feature = "sync_v1")]
commands::server_auth::server_begin_loopback_login,
#[cfg(feature = "sync_v1")]
commands::sync::sync_get_queue_state,
#[cfg(feature = "sync_v1")]
commands::sync::sync_clear_pending,
#[cfg(feature = "sync_v1")]
commands::sync::sync_get_mode,
#[cfg(feature = "sync_v1")]
commands::sync::sync_set_mode,
#[cfg(feature = "sync_v1")]
commands::sync::sync_drain_now,
#[cfg(feature = "sync_v1")]
commands::sync::sync_digest_check,
#[cfg(feature = "sync_v1")]
commands::sync::sync_backfill_now,
#[cfg(feature = "sync_v1")]
commands::sync::sync_backfill_get_enabled,
#[cfg(feature = "sync_v1")]
commands::sync::sync_backfill_set_enabled,
#[cfg(feature = "sync_v1")]
commands::sync::sync_backfill_get_status,
#[cfg(feature = "sync_v1")]
commands::sync::sync_backfill_get_heartbeat_interval,
#[cfg(feature = "sync_v1")]
commands::sync::sync_backfill_set_heartbeat_interval,
#[cfg(feature = "sync_v1")]
commands::sync::sync_digest_check_detailed,
commands::offline::get_offline_mode,
commands::offline::set_offline_mode,
commands::preferences::get_minimize_to_tray,
commands::preferences::set_minimize_to_tray,
commands::preferences::get_auto_start,
commands::preferences::set_auto_start,
commands::preferences::get_ui_zoom,
commands::preferences::set_ui_zoom,
commands::preferences::get_mini_player_bounds,
commands::preferences::set_mini_player_bounds,
commands::tray::set_tray_labels,
commands::lyrics::get_lyrics,
commands::lyrics::fetch_lyrics,
commands::lyrics::refetch_lyrics,
commands::lyrics::import_lrc_file,
commands::lyrics::save_lyrics,
commands::lyrics::export_lyrics_to_path,
commands::lyrics::clear_lyrics,
commands::lyrics::get_lyrics_translation_lang,
commands::lyrics::set_lyrics_translation_lang,
commands::lyrics::get_lyrics_default_destination,
commands::lyrics::set_lyrics_default_destination,
commands::lyrics::prefetch_library_lyrics,
commands::lyrics::cancel_lyrics_prefetch,
commands::player::player_get_state,
commands::player::player_pause,
commands::player::player_set_pause_after_track,
commands::player::player_set_ab_loop,
commands::player::player_clear_ab_loop,
commands::player::player_get_ab_loop,
commands::player::player_resume,
commands::player::player_stop,
commands::player::player_seek,
commands::player::player_set_volume,
commands::player::player_play_tracks,
commands::player::player_play_url,
commands::player::player_add_to_queue,
commands::player::player_play_next,
commands::player::player_reorder_queue,
commands::player::player_next,
commands::player::player_previous,
commands::player::player_toggle_shuffle,
commands::player::player_cycle_repeat,
commands::player::player_resume_last,
commands::player::player_get_queue,
commands::player::player_jump_to_index,
commands::player::player_set_normalize,
commands::player::player_set_mono,
commands::player::player_set_crossfade,
commands::player::player_set_gapless,
commands::player::player_set_speed,
commands::player::player_get_speed,
commands::player::player_set_visualizer,
commands::player::player_get_visualizer,
commands::player::player_set_smart_crossfade,
commands::player::player_get_smart_crossfade,
commands::player::player_set_dynamic_crossfade,
commands::player::player_get_dynamic_crossfade,
commands::player::player_set_replaygain,
commands::player::player_get_eq,
commands::player::player_set_eq_enabled,
commands::player::player_set_eq_band,
commands::player::player_set_eq_preset,
commands::player::player_get_audio_settings,
commands::player::player_list_output_devices,
commands::player::player_set_output_device,
commands::player::player_set_wasapi_exclusive,
commands::player::player_get_wasapi_exclusive,
commands::stats::stats_overview,
commands::stats::stats_top_tracks,
commands::stats::stats_top_artists,
commands::stats::stats_top_albums,
commands::stats::stats_listening_by_day,
commands::stats::stats_listening_by_hour,
commands::maintenance::regenerate_thumbnails,
commands::maintenance::reset_app,
commands::backup::get_backup_config,
commands::backup::set_backup_config,
commands::backup::run_backup_now,
commands::stats::export_stats_json,
commands::wrapped::get_wrapped,
commands::wrapped::available_wrapped_years,
commands::wrapped::wrapped_current_year,
#[cfg(feature = "sync_v1")]
commands::share::save_share_image,
#[cfg(feature = "sync_v1")]
commands::share::share_link_mint,
#[cfg(feature = "sync_v1")]
commands::share::share_link_revoke,
#[cfg(feature = "sync_v1")]
commands::share::share_link_status,
])
.on_window_event(|window, event| match event {
// Close-to-tray: when the user clicks the window's "X" we
// intercept the close, hide the window, and leave the
// backend running so the tray menu can keep controlling
// playback. The `QuitGate` is flipped to `true` by the
// tray's "Quitter" menu before calling `app.exit()`, at
// which point we let the close proceed normally.
WindowEvent::CloseRequested { api, .. } => {
let app = window.app_handle();
let quitting = app.state::<QuitGate>().0.load(Ordering::Acquire);
if quitting {
return;
}
// The mini-player window is its own dispensable surface
// β closing it should just close it, never tear down
// the whole app. Only the main window participates in
// the close-to-tray decision.
if window.label() != "main" {
return;
}
let minimize_to_tray = app
.state::<commands::preferences::PreferencesState>()
.minimize_to_tray
.load(Ordering::Acquire);
if minimize_to_tray {
api.prevent_close();
let _ = window.hide();
} else {
// Arm the quit gate so the impending Destroyed
// event runs the normal shutdown path (persist
// resume point, shut the audio engine down) and
// doesn't bounce back into close-to-tray on any
// subsequent CloseRequested fired during teardown.
app.state::<QuitGate>().0.store(true, Ordering::Release);
}
}
// Real shutdown path: fired only after the QuitGate has
// been armed, so we can safely persist the resume point and
// shut the audio engine down.
WindowEvent::Destroyed => {
if window.label() != "main" {
return;
}
let app = window.app_handle().clone();
let quitting = app.state::<QuitGate>().0.load(Ordering::Acquire);
if !quitting {
return;
}
let _ = tauri::async_runtime::block_on(async move {
let state = app.state::<AppState>();
let engine = app.state::<Arc<AudioEngine>>();
// Silence the cpal output IMMEDIATELY. The rtrb
// ring still holds a few hundred ms of decoded
// samples from before the user paused; without
// this flag, those samples flush to the device
// while we persist resume state and the stream
// tears down, producing a jarring ~2 s of audio
// at shutdown.
engine.shared().paused_output.store(true, Ordering::Release);
let track_id = engine.shared().current_track_id.load(Ordering::Acquire);
let position_ms = engine.shared().current_position_ms();
if track_id > 0 {
if let Ok(pool) = state.require_profile_pool().await {
let _ = queue::persist_resume_point(&pool, track_id, position_ms).await;
}
}
// Tell the decoder thread to stop and drop the
// cpal stream cleanly.
let _ = engine.send(AudioCmd::Shutdown);
Ok::<_, error::AppError>(())
});
}
_ => {}
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
/// Bring the main window back to the front (used by the tray's left
/// click and the "Ouvrir WaveFlow" menu item). No-op if the window
/// already exists and is showing β `set_focus` handles that case.
fn show_main_window(app: &AppHandle) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}
/// Reveal the main window and close the splash, in that order.
///
/// Same ordering rule as the old frontend version: show main first,
/// then close splash, so there is never a moment where the desktop is
/// visible between the two on a multi-monitor / compositing setup.
///
/// Returns `true` only when *both* operations succeed (main shown +
/// splash closed, or splash already absent). On any failure, returns
/// `false` so the caller can clear its "done" flag and let the other
/// path (event listener or fallback timer) retry β without this,
/// a transient failure would leave the user stuck on an eternal
/// splash.
fn reveal_main_close_splash(app: &AppHandle) -> bool {
// Bail out *before* touching the splash if the main window isn't
// available or refuses to show β otherwise we'd close the only
// visible window the user has and leave them staring at the
// desktop with no way back into the app until they re-launch.
let Some(main) = app.get_webview_window("main") else {
tracing::warn!("splash handoff: main window missing at reveal time");
return false;
};
if let Err(err) = main.show() {
tracing::warn!(?err, "splash handoff: main.show failed");
return false;
}
let _ = main.set_focus();
if let Some(splash) = app.get_webview_window("splashscreen") {
if let Err(err) = splash.close() {
tracing::warn!(?err, "splash handoff: splash.close failed");
return false;
}
}
true
}
/// Toggle Pause / Resume from the tray. Looks at the engine's current
/// state (atomic, no async needed) so the menu item works as a single
/// "Lecture / Pause" entry instead of two stateful labels we'd have to
/// keep in sync.
fn toggle_play_pause(app: &AppHandle) {
let engine = app.state::<Arc<AudioEngine>>();
let cmd = match engine.shared().state() {
audio::PlayerState::Playing => AudioCmd::Pause,
audio::PlayerState::Paused | audio::PlayerState::Idle => AudioCmd::Resume,
// Loading / Ended β leave the decoder alone, it'll settle.
_ => return,
};
if let Err(err) = engine.send(cmd) {
tracing::warn!(%err, "tray play_pause: send failed");
}
}
/// Tray "Suivant" β async because it touches the per-profile DB to
/// advance the queue cursor. Mirrors `commands::player::player_next`
/// but called outside the Tauri command pipeline so we own the
/// scheduling here.
fn spawn_next(app: &AppHandle) {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let state = app.state::<AppState>();
let engine = app.state::<Arc<AudioEngine>>();
let pool = match state.require_profile_pool().await {
Ok(p) => p,
Err(err) => {
tracing::warn!(%err, "tray next: no profile pool");
return;
}
};
let profile_id = state.require_profile_id().await.ok();
let repeat = queue::read_repeat_mode(&pool).await;
let next = match queue::advance(&pool, Direction::Next, repeat).await {
Ok(Some(track)) => track,
Ok(None) => return,
Err(err) => {
tracing::warn!(%err, "tray next: advance failed");
return;
}
};
commands::player::emit_track_changed(&app, &state.paths, &next, profile_id);
commands::player::emit_queue_changed(&app);
let replay_gain_db = commands::player::fetch_replay_gain_db(&pool, next.id).await;
let _ = engine.send(AudioCmd::LoadAndPlay {
path: next.as_path(),
start_ms: 0,
track_id: next.id,
duration_ms: next.duration_ms.max(0) as u64,
source_type: "manual".into(),
source_id: None,
replay_gain_db,
});
});
}
/// Tray "PrΓ©cΓ©dent" β same Spotify-style "seek to 0 if past 3 s, else
/// jump back" rule the in-app previous button uses.
fn spawn_previous(app: &AppHandle) {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let state = app.state::<AppState>();
let engine = app.state::<Arc<AudioEngine>>();