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:
Generated
+17
@@ -260,6 +260,7 @@ dependencies = [
|
||||
"tauri-plugin-clipboard-manager",
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tokio",
|
||||
"trash",
|
||||
@@ -4808,6 +4809,22 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "2.14.1"
|
||||
|
||||
@@ -38,6 +38,7 @@ tauri = { version = "2", features = ["image-png"] }
|
||||
tauri-plugin-clipboard-manager = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
trash = "5.4.0"
|
||||
|
||||
@@ -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();
|
||||
|
||||
+22
-1
@@ -65,7 +65,28 @@
|
||||
"type": "downloadBootstrapper"
|
||||
}
|
||||
},
|
||||
"createUpdaterArtifacts": true
|
||||
"createUpdaterArtifacts": true,
|
||||
"fileAssociations": [
|
||||
{
|
||||
"ext": [
|
||||
"mp3",
|
||||
"flac",
|
||||
"wav",
|
||||
"m4a",
|
||||
"aac",
|
||||
"ogg",
|
||||
"oga",
|
||||
"opus",
|
||||
"aiff",
|
||||
"aif",
|
||||
"wma",
|
||||
"alac"
|
||||
],
|
||||
"name": "Audio file",
|
||||
"description": "Audio file",
|
||||
"role": "Viewer"
|
||||
}
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
|
||||
@@ -241,6 +241,7 @@ async function init() {
|
||||
bindPlaybackSettings();
|
||||
bindSearch();
|
||||
bindTools();
|
||||
bindOpenFiles();
|
||||
bindStats();
|
||||
await listen("atmosphere://job", (e) => onJob(e.payload));
|
||||
await listen("atmosphere://probe", (e) => onProbe(e.payload));
|
||||
@@ -406,9 +407,17 @@ function bindShell() {
|
||||
const t = e.target;
|
||||
if (t.nodeType !== 1 || (t.getAttribute("draggable") !== "true" && !t.closest?.('[draggable="true"]'))) e.preventDefault();
|
||||
});
|
||||
document.addEventListener("dragover", (e) => e.preventDefault());
|
||||
document.addEventListener("dragover", (e) => {
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer.types.includes("Files")) showDropHint();
|
||||
});
|
||||
document.addEventListener("dragleave", (e) => {
|
||||
if (!e.relatedTarget) hideDropHint();
|
||||
});
|
||||
document.addEventListener("drop", (e) => {
|
||||
e.preventDefault();
|
||||
hideDropHint();
|
||||
if (e.dataTransfer.files?.length) return importDropped([...e.dataTransfer.files]);
|
||||
const text = (e.dataTransfer.getData("text/uri-list") || e.dataTransfer.getData("text/plain") || "").trim();
|
||||
if (/^https?:\/\//i.test(text)) {
|
||||
go("get");
|
||||
|
||||
@@ -1141,3 +1141,10 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa
|
||||
.info-path { display: grid; gap: var(--s2); justify-items: start; }
|
||||
.info-path code { font-size: 12px; color: var(--text-2); overflow-wrap: anywhere; padding: 6px 10px; border-radius: 8px; background: var(--surface-2, var(--surface)); border: 1px solid var(--hairline); width: 100%; box-sizing: border-box; }
|
||||
#sleepBtn[aria-pressed="true"] { color: var(--accent); }
|
||||
|
||||
/* dropping files */
|
||||
.drop-hint { position: fixed; inset: 12px; z-index: 130; border: 2px dashed color-mix(in srgb, var(--accent) 70%, transparent); border-radius: 18px; background: color-mix(in srgb, var(--bg) 82%, transparent); display: grid; place-items: center; pointer-events: none; animation: fadeOnly 120ms var(--ease); }
|
||||
.drop-hint > div { display: grid; justify-items: center; gap: 6px; text-align: center; }
|
||||
.drop-hint .i svg { width: 40px; height: 40px; color: var(--accent); }
|
||||
.drop-hint strong { font: 650 18px/1.3 var(--font-display); }
|
||||
.drop-hint span { color: var(--text-2); font-size: 13px; }
|
||||
|
||||
+47
-1
@@ -1,4 +1,4 @@
|
||||
// atmosphere · tools.js · Everyday player tools: song info, save the queue as a playlist, sleep timer and resuming long tracks
|
||||
// atmosphere · tools.js · Everyday player tools: song info, save queue, sleep timer, resuming long tracks, and opening or dropping audio files
|
||||
const Sleep = { until: 0, endOfSong: false, timer: 0, tick: 0, fading: false };
|
||||
const RESUME_KEY = "atmo.resume";
|
||||
const RESUME_MIN_MS = 20 * 60 * 1000;
|
||||
@@ -175,3 +175,49 @@ function bindTools() {
|
||||
Player.on("pause", saveResume);
|
||||
renderSleep();
|
||||
}
|
||||
|
||||
const AUDIO_FILE = /\.(mp3|flac|wav|m4a|aac|ogg|oga|opus|aiff?|wma|alac)$/i;
|
||||
|
||||
function showDropHint() {
|
||||
if ($("#dropHint")) return;
|
||||
document.body.append(h("div", { class: "drop-hint", id: "dropHint" }, h("div", {}, icon("music"), h("strong", {}, "Drop to add to your library"), h("span", {}, "Songs are copied into an Imported folder and start playing."))));
|
||||
}
|
||||
|
||||
function hideDropHint() {
|
||||
$("#dropHint")?.remove();
|
||||
}
|
||||
|
||||
async function importDropped(files) {
|
||||
const audio = files.filter((f) => AUDIO_FILE.test(f.name));
|
||||
if (!audio.length) return toast("Those aren't audio files Atmosphere can play.", "err");
|
||||
toast(`Adding ${plural(audio.length, "song")}…`, "");
|
||||
const tracks = [];
|
||||
for (const f of audio) {
|
||||
try {
|
||||
const bytes = new Uint8Array(await f.arrayBuffer());
|
||||
tracks.push(await invoke("import_file", bytes, { headers: { "x-file-name": encodeURIComponent(f.name) } }));
|
||||
} catch (e) {
|
||||
toast(`${f.name}: ${errText(e)}`, "err");
|
||||
}
|
||||
}
|
||||
if (!tracks.length) return;
|
||||
await loadLibrary();
|
||||
const fresh = tracks.map((t) => Lib.byId.get(t.id) || t);
|
||||
Player.setQueue(fresh, 0);
|
||||
toast(`Added ${plural(fresh.length, "song")} to your library`, "ok");
|
||||
}
|
||||
|
||||
async function openFiles(paths) {
|
||||
if (!paths?.length) return;
|
||||
const tracks = await invoke("open_files", { paths }).catch(() => []);
|
||||
if (!tracks.length) return toast("Atmosphere couldn't open that file.", "err");
|
||||
Player.setQueue(tracks.map((t) => Lib.byId.get(t.id) || t), 0);
|
||||
toast(tracks.length === 1 ? `Playing “${tracks[0].title}”` : `Playing ${plural(tracks.length, "song")}`, "");
|
||||
}
|
||||
|
||||
async function bindOpenFiles() {
|
||||
listen("atmosphere://open-files", (e) => openFiles(e.payload));
|
||||
const waitLib = () => (Lib.restored ? Promise.resolve() : new Promise((r) => setTimeout(() => waitLib().then(r), 200)));
|
||||
await waitLib();
|
||||
openFiles(await invoke("startup_files").catch(() => []));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user