mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Open audio files with Atmosphere, and drop files onto the window
- Audio files can be opened with Atmosphere (file associations in the installer) - Opening a file while Atmosphere runs hands it to the open window instead of a second copy - Files outside your library play without being added; library files play as themselves - Dropping audio files on the window copies them into an Imported folder and plays them - macOS "Open with" works through the app's open-file event
This commit is contained in:
@@ -652,3 +652,58 @@ pub async fn artist_media(app: AppHandle, state: State<'_, AppState>, name: Stri
|
||||
};
|
||||
state.library.artist_media(&name, &kind, image.as_deref()).map_err(err)
|
||||
}
|
||||
|
||||
pub fn audio_args<I: IntoIterator<Item = String>>(args: I) -> Vec<String> {
|
||||
args.into_iter()
|
||||
.filter(|a| !a.starts_with('-'))
|
||||
.map(|a| a.strip_prefix("file://").map(|p| p.to_string()).unwrap_or(a))
|
||||
.filter(|a| {
|
||||
let p = Path::new(a);
|
||||
p.is_file() && crate::library::is_audio(p)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_files(state: State<'_, AppState>, paths: Vec<String>) -> Vec<Track> {
|
||||
let list: Vec<PathBuf> = paths.into_iter().map(PathBuf::from).collect();
|
||||
state.library.open_paths(&list)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn startup_files(state: State<'_, AppState>) -> Vec<String> {
|
||||
std::mem::take(&mut *state.pending_open.lock().unwrap())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn import_file(app: AppHandle, state: State<'_, AppState>, request: tauri::ipc::Request<'_>) -> CmdResult<Track> {
|
||||
let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else { return Err("Expected file contents".into()) };
|
||||
let raw_name = request.headers().get("x-file-name").and_then(|v| v.to_str().ok()).unwrap_or("Imported song");
|
||||
let name: String = url::form_urlencoded::parse(format!("n={raw_name}").as_bytes()).next().map(|(_, v)| v.into_owned()).unwrap_or_default();
|
||||
let name: String = name.chars().map(|c| if r#"<>:"/\|?*"#.contains(c) || c.is_control() { '_' } else { c }).collect();
|
||||
let path0 = Path::new(&name);
|
||||
if !crate::library::is_audio(path0) || bytes.is_empty() {
|
||||
return Err("That isn't an audio file Atmosphere can play.".into());
|
||||
}
|
||||
let s = state.snapshot();
|
||||
let dir = PathBuf::from(&s.output_dir).join("Imported");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let stem = path0.file_stem().and_then(|x| x.to_str()).unwrap_or("Imported song").to_string();
|
||||
let ext = path0.extension().and_then(|x| x.to_str()).unwrap_or("mp3").to_string();
|
||||
let mut dest = dir.join(format!("{stem}.{ext}"));
|
||||
let mut n = 2;
|
||||
while dest.exists() {
|
||||
if std::fs::metadata(&dest).map(|m| m.len() as usize == bytes.len()).unwrap_or(false) {
|
||||
break;
|
||||
}
|
||||
dest = dir.join(format!("{stem} ({n}).{ext}"));
|
||||
n += 1;
|
||||
}
|
||||
if !dest.exists() {
|
||||
std::fs::write(&dest, bytes).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let (_, pl) = dirs(&state);
|
||||
let track = state.library.add_file(&dest, &pl).map_err(err)?;
|
||||
changed(&app);
|
||||
Ok(track)
|
||||
}
|
||||
|
||||
+17
-1
@@ -148,6 +148,7 @@ pub struct Library {
|
||||
artists: RwLock<HashMap<String, ArtistMeta>>,
|
||||
hidden: RwLock<HashSet<String>>,
|
||||
linked: RwLock<Vec<Linked>>,
|
||||
opened: RwLock<HashMap<String, Track>>,
|
||||
scanning: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -294,6 +295,7 @@ impl Library {
|
||||
artists: RwLock::new(load("artists.json")),
|
||||
hidden: RwLock::new(load("hidden.json")),
|
||||
linked: RwLock::new(load("linked.json")),
|
||||
opened: RwLock::new(HashMap::new()),
|
||||
scanning: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
@@ -304,7 +306,21 @@ impl Library {
|
||||
}
|
||||
|
||||
pub fn track(&self, id: &str) -> Option<Track> {
|
||||
self.tracks.read().unwrap().get(id).cloned()
|
||||
self.tracks.read().unwrap().get(id).cloned().or_else(|| self.opened.read().unwrap().get(id).cloned())
|
||||
}
|
||||
|
||||
pub fn open_paths(&self, paths: &[PathBuf]) -> Vec<Track> {
|
||||
let mut out = Vec::new();
|
||||
for p in paths.iter().filter(|p| p.is_file() && is_audio(p)) {
|
||||
let key = p.to_string_lossy();
|
||||
if let Some(t) = self.tracks.read().unwrap().values().find(|t| t.path == key).cloned() {
|
||||
out.push(t);
|
||||
} else if let Ok(t) = read_track(p, None) {
|
||||
self.opened.write().unwrap().insert(t.id.clone(), t.clone());
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn art_path(&self, key: &str) -> Option<PathBuf> {
|
||||
|
||||
+27
-1
@@ -38,6 +38,7 @@ pub(crate) struct AppState {
|
||||
history: Arc<History>,
|
||||
pub(crate) library: Arc<library::Library>,
|
||||
startup_cleanup: Mutex<Option<(usize, u64)>>,
|
||||
pending_open: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
pub(crate) type CmdResult<T> = Result<T, String>;
|
||||
@@ -443,6 +444,17 @@ fn main() {
|
||||
.expect("http client");
|
||||
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
|
||||
if let Some(w) = app.get_webview_window("main") {
|
||||
let _ = w.unminimize();
|
||||
let _ = w.show();
|
||||
let _ = w.set_focus();
|
||||
}
|
||||
let files = libcmd::audio_args(argv.into_iter().skip(1));
|
||||
if !files.is_empty() {
|
||||
let _ = app.emit("atmosphere://open-files", files);
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
@@ -456,7 +468,7 @@ fn main() {
|
||||
let cleaned = storage::startup(&settings.lock().unwrap());
|
||||
let library = Arc::new(library::Library::load());
|
||||
let dl = Arc::new(Downloader::new(app.handle().clone(), settings.clone(), history.clone(), library.clone(), http.clone()));
|
||||
app.manage(AppState { settings: settings.clone(), http: http.clone(), prober: Arc::new(Prober::default()), dl, history, library, startup_cleanup: Mutex::new(Some(cleaned)) });
|
||||
app.manage(AppState { settings: settings.clone(), http: http.clone(), prober: Arc::new(Prober::default()), dl, history, library, startup_cleanup: Mutex::new(Some(cleaned)), pending_open: Mutex::new(libcmd::audio_args(std::env::args().skip(1))) });
|
||||
app.manage(api::ApiHub::load());
|
||||
api::apply(app.handle());
|
||||
libcmd::spawn_scan(app.handle().clone());
|
||||
@@ -535,6 +547,9 @@ fn main() {
|
||||
libcmd::playlist_link,
|
||||
libcmd::track_loudness,
|
||||
libcmd::tracks_edit,
|
||||
libcmd::open_files,
|
||||
libcmd::startup_files,
|
||||
libcmd::import_file,
|
||||
libcmd::artist_fetch,
|
||||
libcmd::artist_media,
|
||||
libcmd::playlist_cover,
|
||||
@@ -544,6 +559,17 @@ fn main() {
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building atmosphere")
|
||||
.run(|app, event| {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let tauri::RunEvent::Opened { urls } = &event {
|
||||
let files: Vec<String> = urls.iter().filter_map(|u| u.to_file_path().ok()).map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
let files = libcmd::audio_args(files);
|
||||
if !files.is_empty() {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
state.pending_open.lock().unwrap().extend(files.clone());
|
||||
}
|
||||
let _ = app.emit("atmosphere://open-files", files);
|
||||
}
|
||||
}
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
state.dl.cancel_all();
|
||||
|
||||
Reference in New Issue
Block a user