WallpaperManager.swift

2.3 KB · raw

1import AppKit23import AppKit45class WallpaperManager {6    static let shared = WallpaperManager()7    8    private init() {}9    10    /// Downloads the file to a temporary location and returns the local URL.11    func download(from url: URL) async throws -> URL {12        let (data, _) = try await URLSession.shared.data(from: url)13        14        let filename = url.lastPathComponent15        let tempDir = FileManager.default.temporaryDirectory16        let fileURL = tempDir.appendingPathComponent(filename)17        18        try data.write(to: fileURL)19        return fileURL20    }21    22    /// Sets the desktop image from a local file URL.23    @MainActor24    func setDesktopImage(from fileURL: URL, screen: NSScreen? = nil) throws {25        if let screen = screen {26            try NSWorkspace.shared.setDesktopImageURL(fileURL, for: screen, options: [:])27        } else {28            // Set for all screens or just main? Let's default to main for safety, 29            // but the UI will likely drive this.30            // If no screen specified, maybe set for the 'active' one.31            let targetScreen = NSScreen.main ?? NSScreen.screens.first!32            try NSWorkspace.shared.setDesktopImageURL(fileURL, for: targetScreen, options: [:])33        }34    }35    36    /// Copies the file to the specified destination directory.37    func saveToFolder(from sourceURL: URL, to folderURL: URL) throws {38        // Ensure folder exists39        try FileManager.default.createDirectory(at: folderURL, withIntermediateDirectories: true)40        41        let destinationURL = folderURL.appendingPathComponent(sourceURL.lastPathComponent)42        43        // If file exists, maybe don't overwrite or handle gracefully? 44        // For now, we'll remove it if it exists to ensure we have the fresh one, or just skip.45        if FileManager.default.fileExists(atPath: destinationURL.path) {46            try FileManager.default.removeItem(at: destinationURL)47        }48        49        try FileManager.default.copyItem(at: sourceURL, to: destinationURL)50    }51    52    // Legacy support wrapper (optional, but cleaner to update call sites)53    @MainActor54    func setWallpaper(from url: URL, screen: NSScreen? = nil) async throws {55        let localURL = try await download(from: url)56        try setDesktopImage(from: localURL, screen: screen)57    }58}