-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSet-SpaceWallpapers.ps1
More file actions
318 lines (283 loc) · 13.1 KB
/
Copy pathSet-SpaceWallpapers.ps1
File metadata and controls
318 lines (283 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# Set-SpaceWallpapers.ps1
# MULTI-MONITOR wallpaper using ONLY James Webb Space Telescope (JWST) photos.
# Primary source: scraping of esawebb.org (categories sorted by ranking).
# Fallback: Wikimedia Commons (category "Images by the James Webb Space Telescope").
# Fit mode: "Fit" (whole image, no cropping). Per-monitor wallpapers via the IDesktopWallpaper COM API.
#
# Usage:
# .\Set-SpaceWallpapers.ps1 -> changes ALL monitors (used by the scheduled task)
# .\Set-SpaceWallpapers.ps1 -Monitor 0 -> changes only the monitor with index 0 (0-based)
# .\Set-SpaceWallpapers.ps1 -GUI -> opens the chooser window (used by the desktop icon)
param([int]$Monitor = -1, [switch]$GUI)
$ErrorActionPreference = 'Stop'
# Folder where this script lives (makes everything portable to any PC/path)
$baseDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
$imgDir = Join-Path $baseDir 'images'
$logFile = Join-Path $baseDir 'nasa-wallpaper.log'
$ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
$esaCats = @('nebulae', 'anniversary', 'galaxies', 'stars') # esawebb categories (sorted by ranking)
$maxDimDefault = 3840 # max side of the saved image (px)
$POS_FIT = 3 # 3 = DWPOS_FIT ("Fit")
$script:pool = $null # list of image references (esawebb ids or Commons titles)
$script:poolSource = '' # 'esawebb' | 'commons'
function Write-Log($msg) {
$line = '{0} {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $msg
Add-Content -Path $logFile -Value $line
Write-Host $line
}
# IDesktopWallpaper COM interface definition (methods must be in the exact vtable order)
$dwCode = @'
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct RECT { public int Left, Top, Right, Bottom; }
[ComImport, Guid("B92B56A9-8B55-4E14-9A89-0199BBB6F93B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDesktopWallpaper {
void SetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string monitorID, [MarshalAs(UnmanagedType.LPWStr)] string wallpaper);
[return: MarshalAs(UnmanagedType.LPWStr)] string GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string monitorID);
[return: MarshalAs(UnmanagedType.LPWStr)] string GetMonitorDevicePathAt(uint monitorIndex);
uint GetMonitorDevicePathCount();
void GetMonitorRECT([MarshalAs(UnmanagedType.LPWStr)] string monitorID, out RECT displayRect);
void SetBackgroundColor(uint color);
uint GetBackgroundColor();
void SetPosition(int position);
}
[ComImport, Guid("C2CF3110-460E-4fc1-B9D0-8A1C0C9CC4BD")]
public class DesktopWallpaperClass { }
public static class DW {
static IDesktopWallpaper _i;
static IDesktopWallpaper I() { if (_i == null) _i = (IDesktopWallpaper)new DesktopWallpaperClass(); return _i; }
public static uint Count() { return I().GetMonitorDevicePathCount(); }
public static string Id(uint i) { return I().GetMonitorDevicePathAt(i); }
public static int Width(string id) { RECT r; I().GetMonitorRECT(id, out r); return r.Right - r.Left; }
public static int Height(string id) { RECT r; I().GetMonitorRECT(id, out r); return r.Bottom - r.Top; }
public static void Set(string id, string path) { I().SetWallpaper(id, path); }
public static void Pos(int p) { I().SetPosition(p); }
}
'@
# esawebb.org scraping: returns the image ids of the categories, in ranking order (deduped).
function Get-EsawebbPool {
$ids = New-Object System.Collections.ArrayList
$skip = @('archive', 'search', 'potm', 'viewall', 'categories')
foreach ($c in $esaCats) {
try {
$html = (Invoke-WebRequest -Uri "https://esawebb.org/images/archive/category/$c/?sort=-priority" -UserAgent $ua -TimeoutSec 60 -UseBasicParsing).Content
foreach ($m in [regex]::Matches($html, 'href="/images/([\w-]+)/"')) {
$id = $m.Groups[1].Value
if ($id -notin $skip -and $ids -notcontains $id) { [void]$ids.Add($id) }
}
}
catch { Write-Log "Scraping of category '$c' failed: $($_.Exception.Message)" }
}
return $ids
}
# Wikimedia Commons fallback: image file titles of the JWST category.
function Get-CommonsPool {
$api = 'https://commons.wikimedia.org/w/api.php'
$cat = 'Category:Images by the James Webb Space Telescope'
$u = "$api`?action=query&format=json&list=categorymembers&cmtitle=$([uri]::EscapeDataString($cat))&cmtype=file&cmlimit=500"
$r = Invoke-RestMethod -Uri $u -TimeoutSec 60
return @($r.query.categorymembers | Where-Object { $_.title -match '\.(jpg|jpeg|png)$' } | ForEach-Object { $_.title })
}
# URL of the Commons thumbnail resized to $width px wide.
function Get-CommonsThumbUrl($title, $width) {
$api = 'https://commons.wikimedia.org/w/api.php'
$u = "$api`?action=query&format=json&prop=imageinfo&iiprop=url&iiurlwidth=$([int]$width)&titles=$([uri]::EscapeDataString($title))"
$r = Invoke-RestMethod -Uri $u -TimeoutSec 60
return (($r.query.pages.PSObject.Properties.Value).imageinfo[0]).thumburl
}
# Builds the pool only once: esawebb first, otherwise Commons.
function Initialize-Pool {
if ($script:pool -and $script:pool.Count -gt 0) { return }
$ids = Get-EsawebbPool
if ($ids.Count -ge 10) {
$script:pool = $ids; $script:poolSource = 'esawebb'
Write-Log "ESA/Webb pool (ranking): $($ids.Count) images."
}
else {
Write-Log "ESA/Webb scraping insufficient ($($ids.Count)) -> Wikimedia Commons fallback."
$script:pool = Get-CommonsPool; $script:poolSource = 'commons'
Write-Log "Commons pool: $($script:pool.Count) images."
}
}
# Downloads $url, resizes it if the longest side exceeds $maxDim, saves JPEG to $destPath.
# Returns the ORIGINAL dimensions as a hashtable @{Width;Height}.
function Get-PreparedImage($url, $destPath, $maxDim) {
Add-Type -AssemblyName System.Drawing
$tmp = [System.IO.Path]::GetTempFileName()
try {
Invoke-WebRequest -Uri $url -UserAgent $ua -OutFile $tmp -TimeoutSec 300 -UseBasicParsing
$img = [System.Drawing.Image]::FromFile($tmp)
$w = $img.Width; $h = $img.Height
$maxSide = [math]::Max($w, $h)
if ($maxSide -gt $maxDim) {
$scale = $maxDim / $maxSide
$nw = [int]($w * $scale); $nh = [int]($h * $scale)
$bmp = New-Object System.Drawing.Bitmap $nw, $nh
$g = [System.Drawing.Graphics]::FromImage($bmp)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.DrawImage($img, 0, 0, $nw, $nh)
$g.Dispose(); $img.Dispose()
$bmp.Save($destPath, [System.Drawing.Imaging.ImageFormat]::Jpeg)
$bmp.Dispose()
}
else {
$img.Dispose()
Copy-Item $tmp $destPath -Force
}
return @{ Width = $w; Height = $h }
}
finally { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
}
# Sets the wallpaper of a single monitor (0-based index). Returns $true on success.
function Set-OneMonitor($index, $usedRefs) {
$monId = [DW]::Id([uint32]$index)
$w = [DW]::Width($monId)
$h = [DW]::Height($monId)
if ($w -le 0 -or $h -le 0) { Write-Log "Monitor [$index] not active: skipping."; return $false }
$maxDim = [math]::Max($maxDimDefault, [math]::Max($w, $h))
$candidates = @($script:pool | Where-Object { $usedRefs -notcontains $_ } | Sort-Object { Get-Random })
if ($candidates.Count -eq 0) { $candidates = @($script:pool | Sort-Object { Get-Random }) }
foreach ($ref in ($candidates | Select-Object -First 6)) {
try {
if ($script:poolSource -eq 'esawebb') {
$url = "https://esawebb.org/media/archives/images/large/$ref.jpg"
}
else {
$url = Get-CommonsThumbUrl $ref ([math]::Max($w, 2560))
}
$safe = ($ref -replace '[^\w\-]', '_')
$dest = Join-Path $imgDir ("mon$index-$safe.jpg")
$dims = Get-PreparedImage $url $dest $maxDim
[DW]::Set($monId, $dest)
[void]$usedRefs.Add($ref)
Write-Log "Monitor [$index] ($($w)x$($h)) <- JWST [$($script:poolSource)] '$ref' (orig $($dims.Width)x$($dims.Height))"
return $true
}
catch { Write-Log "Monitor [$index]: '$ref' failed ($($_.Exception.Message)), trying another." }
}
return $false
}
# Changes the wallpapers of the passed monitor indices; returns how many were updated.
function Invoke-Switch($indices) {
Initialize-Pool
if (-not $script:pool -or $script:pool.Count -eq 0) { Write-Log "ERROR: no images available."; return 0 }
$used = New-Object System.Collections.ArrayList
$ok = 0
foreach ($i in $indices) {
try { if (Set-OneMonitor $i $used) { $ok++ } }
catch { Write-Log "Monitor [$i]: error ($($_.Exception.Message))." }
}
[DW]::Pos($POS_FIT) # "Fit" for all monitors
return $ok
}
# Chooser window (Windows Forms)
function Show-Chooser {
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$count = [int][DW]::Count()
$form = New-Object System.Windows.Forms.Form
$form.Text = 'JWST Wallpapers'
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Font = New-Object System.Drawing.Font('Segoe UI', 9)
$lbl = New-Object System.Windows.Forms.Label
$lbl.Text = 'Which wallpaper do you want to change? (James Webb photos)'
$lbl.AutoSize = $true
$lbl.Location = New-Object System.Drawing.Point(15, 15)
$form.Controls.Add($lbl)
$y = 45
$radios = New-Object System.Collections.ArrayList
$rbAll = New-Object System.Windows.Forms.RadioButton
$rbAll.Text = "All monitors ($count)"
$rbAll.Location = New-Object System.Drawing.Point(20, $y)
$rbAll.AutoSize = $true
$rbAll.Checked = $true
$form.Controls.Add($rbAll)
$y += 28
for ($i = 0; $i -lt $count; $i++) {
$monId = [DW]::Id([uint32]$i)
$w = [DW]::Width($monId); $h = [DW]::Height($monId)
$parts = $monId -split '#'
$model = if ($parts.Count -ge 2) { $parts[1] } else { 'Monitor' }
$rb = New-Object System.Windows.Forms.RadioButton
$rb.Text = "Monitor $($i + 1) - $model ($($w)x$($h))"
$rb.Location = New-Object System.Drawing.Point(20, $y)
$rb.AutoSize = $true
$rb.Tag = $i
$form.Controls.Add($rb)
[void]$radios.Add($rb)
$y += 28
}
$y += 6
$status = New-Object System.Windows.Forms.Label
$status.Text = ''
$status.AutoSize = $true
$status.MaximumSize = New-Object System.Drawing.Size(340, 0)
$status.Location = New-Object System.Drawing.Point(20, $y)
$status.ForeColor = [System.Drawing.Color]::DimGray
$form.Controls.Add($status)
$y += 40
$btnGo = New-Object System.Windows.Forms.Button
$btnGo.Text = 'Change'
$btnGo.Location = New-Object System.Drawing.Point(185, $y)
$btnGo.Size = New-Object System.Drawing.Size(80, 28)
$form.Controls.Add($btnGo)
$btnClose = New-Object System.Windows.Forms.Button
$btnClose.Text = 'Close'
$btnClose.Location = New-Object System.Drawing.Point(275, $y)
$btnClose.Size = New-Object System.Drawing.Size(80, 28)
$btnClose.Add_Click({ $form.Close() })
$form.Controls.Add($btnClose)
$form.ClientSize = New-Object System.Drawing.Size(375, ($y + 44))
$form.AcceptButton = $btnGo
$btnGo.Add_Click({
if ($rbAll.Checked) {
$indices = 0..($count - 1)
}
else {
$sel = $radios | Where-Object { $_.Checked } | Select-Object -First 1
$indices = @([int]$sel.Tag)
}
$btnGo.Enabled = $false; $btnClose.Enabled = $false
$status.ForeColor = [System.Drawing.Color]::DimGray
$status.Text = 'Changing, please wait...'
$form.Refresh()
[System.Windows.Forms.Application]::DoEvents()
try {
$n = Invoke-Switch $indices
$status.ForeColor = [System.Drawing.Color]::ForestGreen
$status.Text = "Done: $n wallpaper(s) updated."
}
catch {
$status.ForeColor = [System.Drawing.Color]::Firebrick
$status.Text = "Error: $($_.Exception.Message)"
}
$btnGo.Enabled = $true; $btnClose.Enabled = $true
})
[void]$form.ShowDialog()
}
try {
if (-not (Test-Path $imgDir)) { New-Item -ItemType Directory -Path $imgDir -Force | Out-Null }
Add-Type -TypeDefinition $dwCode
$count = [int][DW]::Count()
if ($count -le 0) { Write-Log "ERROR: no monitor detected."; exit 1 }
if ($GUI) {
Show-Chooser
}
elseif ($Monitor -ge 0) {
if ($Monitor -ge $count) { Write-Log "ERROR: monitor $Monitor does not exist (valid indices 0..$($count - 1))."; exit 1 }
$n = Invoke-Switch @($Monitor)
Write-Log "Completed: updated $n monitor (index $Monitor)."
}
else {
$n = Invoke-Switch (0..($count - 1))
Write-Log "Completed: wallpapers set on $n of $count monitors."
}
}
catch {
Write-Log "ERROR: $($_.Exception.Message)"
exit 1
}