@@ -38,6 +38,8 @@ public struct Wallpaper {
3838 case center
3939 }
4040
41+ /// Works around macOS bug where it sometimes returns a directory instead of an image.
42+ /// https://openradar.appspot.com/radar?id=4959084113559552
4143 private static func getFromDirectory( _ url: URL ) throws -> URL {
4244 let appSupportDirectory = try FileManager . default. url ( for: . applicationSupportDirectory, in: . userDomainMask, appropriateFor: nil , create: false )
4345 let dbURL = appSupportDirectory. appendingPathComponent ( " Dock/desktoppicture.db " )
@@ -60,6 +62,26 @@ public struct Wallpaper {
6062 return try wallpaperURLs. map { $0. isDirectory ? try getFromDirectory ( $0) : $0 }
6163 }
6264
65+ /// Works around a macOS bug where if you set a wallpaper to the same path as the existing wallpaper but with different content, it doesn't update.
66+ /// https://openradar.appspot.com/radar?id=6095446787227648
67+ private static func forceRefreshIfNeeded( _ image: URL , screen: Screen ) throws {
68+ var shouldSleep = false
69+ let currentImages = try get ( screen: screen)
70+
71+ for (index, nsScreen) in screen. nsScreens. enumerated ( ) {
72+ if image == currentImages [ index] {
73+ shouldSleep = true
74+ try NSWorkspace . shared. setDesktopImageURL ( URL ( fileURLWithPath: " " ) , for: nsScreen, options: [ : ] )
75+ }
76+ }
77+
78+ if shouldSleep {
79+ // We need to sleep for a little bit, otherwise it doesn't take effect.
80+ // It works with 0.3, but not with 0.2, so we're using 0.4 just to be sure.
81+ sleep ( for: 0.4 )
82+ }
83+ }
84+
6385 /// Set an image URL as wallpaper
6486 public static func set( _ image: URL , screen: Screen = . all, scale: Scale = . auto) throws {
6587 var options = [ NSWorkspace . DesktopImageOptionKey: Any] ( )
@@ -81,6 +103,8 @@ public struct Wallpaper {
81103 options [ . allowClipping] = false
82104 }
83105
106+ try forceRefreshIfNeeded ( image, screen: screen)
107+
84108 for nsScreen in screen. nsScreens {
85109 try NSWorkspace . shared. setDesktopImageURL ( image, for: nsScreen, options: options)
86110 }
0 commit comments