import AppKit import AppKit class WallpaperManager { static let shared = WallpaperManager() private init() {} /// Downloads the file to a temporary location and returns the local URL. func download(from url: URL) async throws -> URL { let (data, _) = try await URLSession.shared.data(from: url) let filename = url.lastPathComponent let tempDir = FileManager.default.temporaryDirectory let fileURL = tempDir.appendingPathComponent(filename) try data.write(to: fileURL) return fileURL } /// Sets the desktop image from a local file URL. @MainActor func setDesktopImage(from fileURL: URL, screen: NSScreen? = nil) throws { if let screen = screen { try NSWorkspace.shared.setDesktopImageURL(fileURL, for: screen, options: [:]) } else { // Set for all screens or just main? Let's default to main for safety, // but the UI will likely drive this. // If no screen specified, maybe set for the 'active' one. let targetScreen = NSScreen.main ?? NSScreen.screens.first! try NSWorkspace.shared.setDesktopImageURL(fileURL, for: targetScreen, options: [:]) } } /// Copies the file to the specified destination directory. func saveToFolder(from sourceURL: URL, to folderURL: URL) throws { // Ensure folder exists try FileManager.default.createDirectory(at: folderURL, withIntermediateDirectories: true) let destinationURL = folderURL.appendingPathComponent(sourceURL.lastPathComponent) // If file exists, maybe don't overwrite or handle gracefully? // For now, we'll remove it if it exists to ensure we have the fresh one, or just skip. if FileManager.default.fileExists(atPath: destinationURL.path) { try FileManager.default.removeItem(at: destinationURL) } try FileManager.default.copyItem(at: sourceURL, to: destinationURL) } // Legacy support wrapper (optional, but cleaner to update call sites) @MainActor func setWallpaper(from url: URL, screen: NSScreen? = nil) async throws { let localURL = try await download(from: url) try setDesktopImage(from: localURL, screen: screen) } }