Mulberry/App/MulberryApp.swift
astar76 8e6f8a86a4 Mulberry for iOS: initial SwiftUI port of the Android app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:30:49 -05:00

77 lines
2.7 KiB
Swift

import SwiftUI
import AVFoundation
@main
struct MulberryApp: App {
@Environment(\.scenePhase) var phase
init() {
_ = Player.shared
Library.shared.startWatching()
Library.shared.scan()
IntentRouter.handler = { cmd in
let p = Player.shared
switch cmd {
case .toggle: p.toggle()
case .next: p.next()
case .previous: p.prev()
case .shuffle: p.setShuffle(!Prefs.shared.shuffle)
case .repeatMode: p.cycleRepeat()
case .favourite: if let s = p.current { PlayStats.shared.setFav(s, !PlayStats.shared.fav(s)) }
}
}
Theme.shared.update()
Player.shared.publishWidget()
}
var body: some Scene {
WindowGroup {
RootView()
.environmentObjects()
.onOpenURL { url in
// mulberry://nowplaying from the widget, files opened "in place" from other apps.
if url.scheme == "mulberry" {
if url.host == "nowplaying" { UIState.shared.nowPlaying = Player.shared.current != nil }
} else if url.isFileURL {
openFile(url)
}
}
}
.onChange(of: phase) { p in
switch p {
case .background:
Player.shared.persistNow()
Player.shared.publishWidget()
case .active:
Library.shared.rescanSoon()
Scrobbler.shared.flush()
default: break
}
}
}
/// Files shared to Mulberry: copy audio into Music and play it; import playlists.
private func openFile(_ url: URL) {
let ok = url.startAccessingSecurityScopedResource()
defer { if ok { url.stopAccessingSecurityScopedResource() } }
let ext = url.pathExtension.lowercased()
if Library.playlistExts.contains(ext) {
if let (pl, n, total) = try? Playlists.shared.importFile(url) {
UIState.shared.show("\(pl.name): \(n)/\(total) songs found")
UIState.shared.tab = 1
}
return
}
guard Library.audioExts.contains(ext) else { return }
var target = url
if !url.path.hasPrefix(Library.root.path) {
target = Library.root.appendingPathComponent("Music").appendingPathComponent(url.lastPathComponent)
try? FileManager.default.removeItem(at: target)
try? FileManager.default.copyItem(at: url, to: target)
}
var s = Song(path: Library.relPath(target))
Library.fill(&s, target)
Player.shared.playList([s])
Library.shared.scan()
}
}