-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathat.ps1
More file actions
1652 lines (1228 loc) · 59.2 KB
/
at.ps1
File metadata and controls
1652 lines (1228 loc) · 59.2 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Changes the active Windows theme based on a predefined/daylight schedule. Works in Windows 10/11.
.DESCRIPTION
This highly-sophisticated Powershell script automatically switches the Windows Theme depending on Sunrise and Sunset, or hours set by the user.
It can activate Windows Dark and Light mode directly, also handling wallpaper changes natively.
It can also activate given `.theme` files, which may allow for a higher degree of customization and compatibility.
The script is designed to run in the background as a scheduled task, ensuring that the system theme is updated without user intervention.
It will automatically create the next temporary task for the next daylight event.
Such tasks ("Auto Theme sunrise" and "Auto Theme sunset") will be overwritten as a matter of course to avoid clutter.
It only connects to the internet to verify Location, if it cannot be retrieved from the system.
It can stay completely offline operating on fixed hours provided by the user.
When ran as the command `./at.ps1` from terminal or desktop shortcut, the script will only toggle between themes.
IMPORTANT: Edit `at-config.ps1` to configure this script. The file contains all necessary explanations.
OPTIONALLY: Run `./at-setup.ps1` to create the main Scheduled Task and verify the configuration is in place.
For more information, refer to the README file.
.LINK
https://github.com/unalignedcoder/auto-theme/
.NOTES
- Fixed a parsing error in the Setup script
#>
# ============ Script Parameters ==============
param (
[switch]$Toggle, # Force a theme flip
[switch]$Schedule, # Force the daylight calculation
[switch]$Next # Force a wallpaper skip
)
# ============= Script Version ==============
# This is automatically updated
$scriptVersion = "1.0.46"
# ============= Config file ==============
$ConfigPath = Join-Path $PSScriptRoot "at-config.ps1"
# ============= FUNCTIONS ==============
# Determine if the script runs interactively
function Test-TerminalSession {
# Get the current process ID
$proc = Get-CimInstance Win32_Process -Filter "ProcessId = $pid"
# Get the parent process ID
$parent = Get-CimInstance Win32_Process -Filter "ProcessId = $($proc.ParentProcessId)"
# Check for svchost or Schedule (Standard Task Scheduler)
if ($parent.Name -eq "svchost.exe" -or $parent.CommandLine -like "*Schedule*") {
return $false
}
# Use the config variable to detect the specific launcher used
switch ($terminalVisibility) {
"ch" {
# If we expect headless, check if parent is conhost with the headless flag
if ($parent.Name -eq "conhost.exe" -and $parent.CommandLine -like "*--headless*") { return $false }
}
"wt" {
# If we expect Windows Terminal, check if parent is wt.exe
if ($parent.Name -eq "wt.exe") { return $false }
}
}
# Default to true (Interactive) if no scheduled parent is detected
return $true
}
# Create the logging system
function Write-Log {
param (
[string]$message,
[bool]$verboseMessage = $false # Default to false if not specified
)
try {
# Only proceed if in debug mode
if (-not $log) { return }
<# Check for verbosity:
If the message is verbose, but verbose is false, end the Function
If the message is verbose, but verbose is true, continue
If the message is not verbose, continue #>
if ($verboseMessage -and -not $verbose) { return }
# Interactive: print to console (no prefix). Verbose messages are shown only when $verbose is true.
if (Test-TerminalSession) {
Write-Information -MessageData $message -InformationAction Continue
# Optionally also append to the log file when requested from interactive sessions
if ($logFromTerminal) { Add-Content -Path $logFile -Value $message }
}
else {
# Non-interactive: always append to log file
Add-Content -Path $logFile -Value $message
}
} catch {
# Write-Host avoids emitting pipeline output from the logger
Write-Information -MessageData "Error in Write-Log: $_" -InformationAction Continue
}
}
# Trim old log entries
function Limit-LogHistory {
param (
[string]$logFilePath, # Path to the log file
[int]$maxSessions = 5 # Maximum number of log sessions to keep
)
if (-Not ($trimLog)) {
return
}
if (-Not (Test-Path $logFilePath)) {
# Log file doesn't exist, no need to trim
Write-Output "Log file doesn't exist, no need to trim"
return
}
# Read all lines from the log file
Write-Output "Reading all lines from the log file"
$logLines = Get-Content -Path $logFilePath
# Find the indices of all session start lines
$sessionStartIndices = @()
for ($i = 0; $i -lt $logLines.Count; $i++) {
if ($logLines[$i] -match '=== Auto-Theme script started \(Version: .*?\)') {
$sessionStartIndices += $i
}
}
# Check if the number of sessions exceeds the maximum allowed
if ($sessionStartIndices.Count -le $maxSessions) {
# No need to trim the log
Write-Output "Log file is small, no need to trim"
return
}
# Calculate how many sessions to remove
$sessionsToRemove = $sessionStartIndices.Count - $maxSessions
# Identify the range of lines to keep
$startIndexToKeep = $sessionStartIndices[$sessionsToRemove]
# Extract the lines to keep and overwrite the log file
Write-Output "Extracting the log lines to keep, and overwriting the log file"
$linesToKeep = $logLines[$startIndexToKeep..($logLines.Count - 1)]
Set-Content -Path $logFilePath -Value $linesToKeep
}
# Handle BurntToast Notifications
function Show-Notification {
param(
# Accept either a single string or an array of strings.
[object]$Text,
[string]$AppLogo
)
# Install the BurntToast module if not already installed
if (-not (Get-Module -Name BurntToast -ListAvailable)) {
try {
Write-Log "Installing the BurnToast Notifications module"
Install-Module -Name BurntToast -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -Confirm:$false
} catch {
Write-Log "Failed to install BurntToast module: $_"
return
}
}
# for when the above is commented out or fails, we double-check.
if (Get-Module -Name BurntToast -ListAvailable) {
try {
Write-Log "Creating BurnToast notification" -verboseMessage $true
# create Burntoast header
$BurnHeader = New-BTHeader -Title 'Auto Theme'
# show notification
New-BurntToastNotification -Header $BurnHeader -Text $Text -AppLogo $AppLogo
Write-Log "Displayed BurntToast notification with text: $(
if ($Text -is [System.Array]) { ($Text -join ' | ') } else { $Text }
)" -verboseMessage $true
} catch {
Write-Log "Error displaying BurntToast notification: $_" -verboseMessage $true
}
} else {
Write-Log "BurntToast module is not installed. Cannot display system notifications."
}
}
# Prepare BurntToast notification content
function Send-ThemeNotification {
param(
[string]$MainLine,
[string]$SelectedWallpaper = ""
)
# If user disabled showing wallpaper names, show only main line
if ($SelectedWallpaper -and $showWallName) {
# Blank line for spacing, then wallpaper line
Show-Notification -Text @($MainLine, "", "Wallpaper: $SelectedWallpaper") -AppLogo $appLogo
} else {
Show-Notification -Text $MainLine -AppLogo $appLogo
}
}
# Check if the script has been run in the last interval
function Test-LastRunTime {
Write-Log "Checking if script was run in the last $lastRunInterval minutes" -verboseMessage $true
if (Test-Path $lastRunFile) {
$lastRun = Get-Content $lastRunFile | Out-String
$lastRun = [DateTime]::Parse($lastRun)
$now = Get-Date
$timeSinceLastRun = $now - $lastRun
if ($timeSinceLastRun.TotalMinutes -lt $lastRunInterval) {
Write-Log "Script was run within the last $lastRunInterval minutes. Exiting."
exit
}
}
}
# Update the last run time
function Update-LastRunTime {
$now = Get-Date
$now | Out-File -FilePath $lastRunFile -Force
}
# Check whether wallpaper shuffle is enabled in .theme file
function Test-DoWeShuffle {
param (
[string]$themeFilePath
)
Write-Log "Checking if the .theme file shuffles wallpapers" -verboseMessage $true
# Read the content of the theme file
$themeContent = Get-Content -Path $themeFilePath
# Flag to indicate if we are inside the [Slideshow] section
$inSlideshowSection = $false
foreach ($line in $themeContent) {
# Write-Log "Processing line: $line" -verboseMessage $true
# Check for the start of the [Slideshow] section
if ($line -match '^\[Slideshow\]') {
Write-Log "Found Slideshow section" -verboseMessage $true
$inSlideshowSection = $true
continue
}
# If we are inside the [Slideshow] section, look for 'shuffle' setting
if ($inSlideshowSection) {
if ($line -match '(?i)shuffle=(\d)') { # Case-insensitive match for 'shuffle'
Write-Log "Found shuffle setting: $line" -verboseMessage $true
return $matches[1] -eq '1'
}
# If we encounter the next section or end of file, break out of the loop
if ($line -match '^\[.*\]') {
Write-Log "Leaving [Slideshow] section" -verboseMessage $true
break
}
}
}
# If no shuffle setting is found, return false
Write-Log "No, the .theme file does not." -verboseMessage $true
return $false
}
<# Prepend the substring '_0_at_' to one randomly chosen
wallpaper filename, so as to make it first pick. #>
function Get-RandomFirstWall {
param (
[string]$wallpaperDirectory
)
# Will return basename (no path, no extension) or empty string
[string]$SelectedWallpaperBasename = ""
# Removed the unhelpful "Get-RandomFirstWall: entry" log line
if (-Not ($randomFirst)) {
Write-Log "The first wallpaper will not be randomized." -verboseMessage $true
return $SelectedWallpaperBasename
}
Write-Log "Randomizing first wallpaper." -verboseMessage $true
Write-Log "Looking in $wallpaperDirectory" -verboseMessage $true
# Build list of folders to sanitize (remove any existing _0_at_ prefixes)
$dirsToSanitize = @($wallpaperDirectory)
# If global light/dark wallpaper paths exist and are different, include them
if ($null -ne $wallLightPath -and $wallLightPath -ne "" -and $wallLightPath -ne $wallpaperDirectory) {
$dirsToSanitize += $wallLightPath
}
if ($null -ne $wallDarkPath -and $wallDarkPath -ne "" -and $wallDarkPath -ne $wallpaperDirectory -and $wallDarkPath -ne $wallLightPath) {
$dirsToSanitize += $wallDarkPath
}
# Deduplicate and filter to existing directories
$dirsToSanitize = $dirsToSanitize | Where-Object { $_ } | Get-Unique
foreach ($dir in $dirsToSanitize) {
if (-Not (Test-Path $dir)) {
Write-Log "Wallpaper folder not found: $dir" -verboseMessage $true
continue
}
# Retrieve all wallpaper files in this directory
$wallpapers = Get-ChildItem -Path $dir -File -ErrorAction SilentlyContinue
if (-not $wallpapers) {
Write-Log "No wallpapers in $dir" -verboseMessage $true
continue
}
# Find renamed files with prefix and restore original names
$existingRenamedWallpapers = $wallpapers | Where-Object { $_.Name -match '^_0_at_' }
if ($existingRenamedWallpapers.Count -gt 0) {
foreach ($wallpaper in $existingRenamedWallpapers) {
try {
$originalName = $wallpaper.Name -replace '^_0_at_', ''
Write-Log "Restoring original name: $($wallpaper.FullName) → $originalName" -verboseMessage $true
# Use only the name in -NewName to avoid path issues
Rename-Item -Path $wallpaper.FullName -NewName $originalName -Force -ErrorAction Stop | Out-Null
} catch {
Write-Log "Failed restoring $($wallpaper.FullName): $_" -verboseMessage $true
}
}
}
}
# Now operate on the requested target directory to pick and prefix a random wallpaper.
if (-Not (Test-Path $wallpaperDirectory)) {
Write-Log "Target wallpaper directory not found: $wallpaperDirectory" -verboseMessage $true
return $SelectedWallpaperBasename
}
# Refresh the list of wallpapers in the target folder and exclude already-prefixed files
$wallpapers = Get-ChildItem -Path $wallpaperDirectory -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -notmatch '^_0_at_' }
# Ensure there are wallpapers available
if (-Not $wallpapers -or $wallpapers.Count -eq 0) {
Write-Log "No wallpapers available in target folder: $wallpaperDirectory" -verboseMessage $true
return $SelectedWallpaperBasename
}
# Select a random wallpaper and rename it with the prefix
$randomFirstWallpaper = $wallpapers | Get-Random
$newWallpaperName = "_0_at_" + $randomFirstWallpaper.Name
try {
Rename-Item -Path $randomFirstWallpaper.FullName -NewName $newWallpaperName -Force -ErrorAction Stop | Out-Null
$newWallpaperNameFull = Join-Path $wallpaperDirectory $newWallpaperName
Write-Log "Renamed $($randomFirstWallpaper.FullName) to $newWallpaperNameFull" -verboseMessage $true
# Prepare basename (no path, no extension) to return
$SelectedWallpaperBasename = [System.IO.Path]::GetFileNameWithoutExtension($randomFirstWallpaper.Name)
} catch {
Write-Log "Failed to rename $($randomFirstWallpaper.FullName): $_" -verboseMessage $true
$SelectedWallpaperBasename = ""
}
# Return only the basename string
return $SelectedWallpaperBasename
}
# Get the currently selected wallpaper's basename (no path, no extension)
function Get-WallpaperName {
param (
[string]$wallpaperDirectory,
[string]$themeFilePath
)
if ([string]::IsNullOrWhiteSpace($wallpaperDirectory)) {
Write-Log "Get-WallpaperName: wallpaperDirectory is null or empty." -verboseMessage $true
return ""
}
[string]$selected = ""
try {
# return empty string if wallpaper path is not found
if (-not (Test-Path $wallpaperDirectory)) { return $selected }
# If theme uses shuffle, use the "Rename Trick" to force a random start
if ($useThemeFiles -and (Test-DoWeShuffle -themeFilePath $themeFilePath)) {
$selected = Get-RandomFirstWall -wallpaperDirectory $wallpaperDirectory
}
# Fallback (or if static): Just get the first file alphabetically
if (-not $selected) {
$first = Get-ChildItem -Path $wallpaperDirectory -File | Sort-Object Name | Select-Object -First 1
if ($first) { $selected = [System.IO.Path]::GetFileNameWithoutExtension($first.Name) }
}
} catch {
Write-Log "Get-WallpaperName error: $_"
}
if ($selected) { $selected = $selected -replace '^_0_at_', '' }
return $selected
}
# Handles the creation and management of the native wallpaper slideshow task
function Set-WallpaperRotationTask {
param (
[string]$Mode # "light" or "dark"
)
# 1. Setup Variables
$TaskName = "Auto Theme wallpaper changer"
$wallPathToPass = if ($Mode -eq "light") { $wallLightPath } else { $wallDarkPath }
$wallpaperDesc = "Triggers wallpaper change based on user-defined intervals. Managed by the main Auto Theme task."
# --- THE LOGIC CHECK ---
$isFolder = Test-Path $wallPathToPass -PathType Container
if ($useThemeFiles -or $slideShowInterval -le 0 -or $noWallpaperChange -or -not $isFolder) {
if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) {
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
Write-Log "Wallpaper rotation not needed (Fixed image or disabled). Removed task." -verboseMessage $true
}
return
}
# 2. Verify worker script exists
$workerScript = Join-Path $PSScriptRoot "at-wallpaper.ps1"
if (-not (Test-Path $workerScript)) {
Write-Log "Error: Worker script not found at $workerScript. Cannot schedule rotation."
return
}
# 3. Define the Start Time (1 interval in the future)
$triggerTime = (Get-Date).AddMinutes([int]$slideShowInterval)
# 4. Prepare specific arguments for the worker script
$workerArgs = "-Path `"$wallPathToPass`""
try {
# 5. Call the Helper with the CUSTOM script and arguments
# This tells the task to run 'at-wallpaper.ps1' instead of 'at.ps1'
Register-Task -Name $TaskName `
-NextTriggerTime $triggerTime `
-Description $wallpaperDesc `
-CustomFile $workerScript `
-Arguments $workerArgs
# 6. Apply the Repetition Patch
# Register-Task creates a standard trigger; we must modify it for repeating intervals.
$task = Get-ScheduledTask -TaskName $TaskName
# We switch to a Daily trigger so it persists across reboots
$task.Triggers[0] = New-ScheduledTaskTrigger -Daily -At ($triggerTime.ToString("HH:mm"))
# ISO 8601 format (PT#M) prevents the XML formatting error
$task.Triggers[0].Repetition.Interval = "PT$($slideShowInterval)M"
$task.Triggers[0].Repetition.Duration = "" # Indefinite repetition
# Ensure it runs even if the PC was off during a scheduled tick
$task.Settings.StartWhenAvailable = $true
$task.Settings.MultipleInstances = "IgnoreNew"
Set-ScheduledTask -InputObject $task | Out-Null
Write-Log "Native Slideshow scheduled: Every $slideShowInterval minutes using $Mode wallpapers."
Write-Log "Worker: $workerScript" -verboseMessage $true
} catch {
Write-Log "Failed to register wallpaper rotation task: $_"
}
}
# Helper to launch processes without admin privileges
function Start-ProcessUnelevated {
param (
[string]$FilePath,
[string]$ArgumentList = ""
)
try {
<# Use the Shell COM object to ask the standard user desktop shell
to launch the process for us, bypassing the script's Admin token. #>
$shell = New-Object -ComObject Shell.Application
$shell.ShellExecute($FilePath, $ArgumentList, "", "open", 1)
Write-Log "Launched unelevated: $FilePath" -verboseMessage $true
} catch {
Write-Log "Failed to launch unelevated ($FilePath): $_"
}
}
# Restart the 'Themes' Service
function Restart-ThemeService {
[bool]$IsAdmin = Test-IsAdmin
if ($restartThemeService -and $IsAdmin) {
try {
Write-Log "Restarting the Themes service." -verboseMessage $true
Restart-Service -Name "Themes" -Force -ErrorAction SilentlyContinue
Write-Log "Themes service restarted successfully." -verboseMessage $true
} catch {
Write-Log "Failed to restart Themes service: $_" -verboseMessage $true
}
}
}
# Modify TrueLaunchBar default colors
function Update-TrueLaunch {
param (
[string]$themeMode # Expected values: "dark" or "light"
)
# Check if TrueLaunch modification is enabled
if (-Not $customizeTrueLaunch) {
Write-Log "TrueLaunchBar modification is disabled in config.ps1. Skipping." -verboseMessage $true
return
}
# Validate if the file exists
if (-Not (Test-Path $trueLaunchIniFilePath)) {
Write-Log "True Launch Bar settings file not found: $trueLaunchIniFilePath" -verboseMessage $true
return
}
Write-Log "Modifying True Launch Bar settings for $themeMode theme." -verboseMessage $true
Write-Log "Using $trueLaunchIniFilePath." -verboseMessage $true
<# Define settings for dark and light themes
Study TLB Setup.ini for more customizations #>
$settingsDark = @{
"MenuActiveColor2" = "10053120"
"MenuActiveColor" = "10053120"
"MenuActiveTextColor" = "16777215"
"MenuBackgroundColor" = "2960685"
"menuSeparatorColor1" = "0"
"menuSeparatorColor2" = "6908265"
"MenuTextColor" = "16777215"
}
$settingsLight = @{
"MenuActiveColor2" = "-1"
"MenuActiveColor" = "-1"
"MenuActiveTextColor" = "-1"
"MenuBackgroundColor" = "-1"
"menuSeparatorColor1" = "-1"
"menuSeparatorColor2" = "-1"
"MenuTextColor" = "-1"
}
# Select settings based on the theme mode
$settingsToApply = if ($themeMode -eq "dark") { $settingsDark } else { $settingsLight }
# Read existing INI file content
$iniContent = Get-Content -Path $trueLaunchIniFilePath -Raw
$updatedContent = $iniContent
# Modify settings under [settings] section
foreach ($key in $settingsToApply.Keys) {
$regex = "(?<=\b$key=)[\-\d]+"
if ($updatedContent -match "\b$key=") {
# Update existing key
$updatedContent = $updatedContent -replace $regex, $settingsToApply[$key]
Write-Log "Updated $key to $($settingsToApply[$key])" -verboseMessage $true
} else {
# If key is missing, append it (shouldn't happen, but just in case)
$updatedContent = $updatedContent -replace "\[settings\]", "[settings]`r`n$key=$($settingsToApply[$key])"
Write-Log "Added missing key: $key=$($settingsToApply[$key])" -verboseMessage $true
}
}
# Save the updated content back to the INI file
Set-Content -Path $trueLaunchIniFilePath -Value $updatedContent -Encoding UTF8
Write-Log "True Launch Bar settings updated." -verboseMessage $true
}
# Change T-Clock Text Color
function Set-TClockColor {
param (
[string]$ThemeMode # "dark" or "light"
)
# Define Colors (Decimal format for DWORD)
# White = 16777215 (0xFFFFFF) Visible on Dark Taskbar
# Black = 0 (0x000000) Visible on Light Taskbar
$newColor = if ($ThemeMode -eq "dark") { 16777215 } else { 0 }
# Portable Mode Method
if ($tClockPath -and (Test-Path $tClockPath)) {
$iniPath = Join-Path (Split-Path -Parent $tClockPath) "T-Clock.ini"
# if T-Clock is running from a portable folder with an INI file
if (Test-Path $iniPath) {
try {
$content = Get-Content -Path $iniPath -Raw
# Regex replace ForeColor
if ($content -match "(?m)^ForeColor=[-0-9]+") {
$content = $content -replace "(?m)^ForeColor=[-0-9]+", "ForeColor=$newColor"
} else {
$content = $content -replace "\[Clock\]", "[Clock]`r`nForeColor=$newColor"
}
# Regex remove BackColor (Crash prevention)
$content = $content -replace "(?m)^BackColor=[-0-9]+\r?\n?", ""
Set-Content -Path $iniPath -Value $content -NoNewline
Write-Log "INI: Updated portable settings." -verboseMessage $true
} catch {
Write-Log "INI update failed: $_"
}
# If there is no portable .ini file, check registry
} else {
# Registry Method
$regKey = "HKCU:\SOFTWARE\Stoic Joker's\T-Clock 2010\Clock"
if (Test-Path $regKey) {
try {
# Set Text Color
Set-ItemProperty -Path $regKey -Name "ForeColor" -Value $newColor -Type DWORD -Force
Write-Log "Registry: Set T-Clock ForeColor to $newColor ($ThemeMode)" -verboseMessage $true
# SAFETY MEASURE: Remove BackColor to prevent Shell Crashes
# We silently continue if it's already gone.
Remove-ItemProperty -Path $regKey -Name "BackColor" -ErrorAction SilentlyContinue
Write-Log "Registry: Ensured BackColor is removed (Crash prevention)." -verboseMessage $true
} catch {
Write-Log "Registry update failed: $_"
}
}
}
}
# Restart T-Clock
# This applies the changes immediately
if ($restartTClockColor) {
Write-Log "Restarting T-Clock to apply new color." -verboseMessage $true
$proc = Get-Process -Name "Clock64" -ErrorAction SilentlyContinue
if (-not $proc) { $proc = Get-Process -Name "Clock" -ErrorAction SilentlyContinue }
if (-not $proc) { $proc = Get-Process -Name "T-Clock" -ErrorAction SilentlyContinue }
if ($proc) {
Stop-Process -Id $proc.Id -Force
Start-Sleep -Milliseconds 250
if ($tClockPath) {
Start-ProcessUnelevated -FilePath $tClockPath
} else {
# Try to restart from the path of the process we just killed
Start-ProcessUnelevated -FilePath $proc.Path
}
} elseif ($tClockPath) {
Start-ProcessUnelevated -FilePath $tClockPath
}
}
}
# Restart Sysinternals Process Explorer
function Restart-ProcessExplorer {
# Check if procexp.exe or procexp64.exe are running
$proc = Get-Process | Where-Object { $_.ProcessName -match "procexp(64)?" }
if ($proc) {
# Retrieve the executable path safely
$exePath = ($proc | Select-Object -First 1).Path
if (-not $exePath) {
Write-Log "Error: Could not retrieve Process Explorer's path." -verboseMessage $true
return
}
Write-Log "Restarting Process Explorer: $exePath" -verboseMessage $true
# Stop Process Explorer
Stop-Process -Id $proc.Id -Force
Start-Sleep -Seconds 2 # Ensure it has fully closed
# Restart minimized
if ($restartProcexpElevated) {
Start-Process -FilePath $exePath -ArgumentList "-t" -WindowStyle Minimized
Write-Log "Started Process Explorer with elevated rights." -verboseMessage $true
} else {
<# If not elevated, we close and restart via COM.
Note: We manually handle the pathing here since Restart-ProcessExplorer uses Start-Process. #>
$proc = Get-Process | Where-Object { $_.ProcessName -match "procexp(64)?" }
if ($proc) {
$exePath = ($proc | Select-Object -First 1).Path
Stop-Process -Id $proc.Id -Force
Start-Sleep -Seconds 2
Start-ProcessUnelevated -FilePath $exePath -ArgumentList "-t"
}
Write-Log "Started Process Explorer without elevated rights." -verboseMessage $true
}
} else {
Write-Log "Process Explorer is not running. No restart needed." -verboseMessage $true
}
}
# Restart Windows Explorer
function Restart-Explorer {
Write-Log "Waiting $waitExplorer seconds before restarting Windows Explorer..." -verboseMessage $true
# Delay so that it doesn't mess with Windows startup programs
Start-Sleep -Seconds $waitExplorer
Write-Log "Restarting Windows Explorer." -verboseMessage $true
# Attempt 1: The "Polite" Request (CloseMainWindow)
# This sends a close signal (like clicking 'X'), giving Explorer time to save state
# and notify background tasks (preventing the surge).
# $explorerProc = Get-Process -Name explorer -ErrorAction SilentlyContinue
# if ($explorerProc) {
# foreach ($proc in $explorerProc) {
# # This is the magic command missing from the previous snippet
# $proc.CloseMainWindow() | Out-Null
# }
# # Wait up to 5 seconds for it to close gracefully
# $timeout = 0
# while ((Get-Process -Name explorer -ErrorAction SilentlyContinue) -and ($timeout -lt 5)) {
# Start-Sleep -Seconds 1
# $timeout++
# }
# }
# Attempt 2: The "Hard" Kill (Only if it stuck)
# If it's still running after 5 seconds, it's hung, so we force kill it.
if (Get-Process -Name explorer -ErrorAction SilentlyContinue) {
#Write-Log "Explorer did not close gracefully. Forcing close..." -verboseMessage $true
Stop-Process -Name explorer -Force -ErrorAction SilentlyContinue
}
# Delay to ensure the system registers the closure
Start-Sleep -Seconds 2
# Delay to ensure it's fully closed
Start-Sleep -Seconds 3
$explorer = Get-Process | Where-Object { $_.ProcessName -eq "explorer" } -ErrorAction SilentlyContinue
# Start if it hasn't already started (avoids new window)
if (-Not ($explorer)) {Start-ProcessUnelevated "explorer.exe" -ErrorAction SilentlyContinue}
Write-Log "Windows Explorer restarted." -verboseMessage $true
}
# Combined function to configure/restart apps
function Update-Apps {
param (
[string]$themeMode # "light" or "dark"
)
try {
# extra apps
if ($restartProcexp) {Restart-ProcessExplorer}
if ($customizeTrueLaunch) {Update-TrueLaunch -themeMode $themeMode }
if ($RestartMusicBee) {Restart-MusicBee}
if ($updateTClockColor) {Set-TClockColor -ThemeMode $themeMode}
# Restart Explorer
Restart-Explorer
} catch {
Write-Log "Update-Apps error: $_" -verboseMessage $true
}
}
# Function to check if the script is running as admin
function Test-IsAdmin {
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
# Run script as Administrator
function Invoke-AsAdmin {
if (-Not (Test-IsAdmin)) {
Write-Log "Requesting elevation. Forwarding parameters..." -verboseMessage $true
# We use $script:PSBoundParameters to reach outside the function's scope
$paramsToPass = $script:PSBoundParameters.Keys | ForEach-Object { "-$_" }
$argList = @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$PSCommandPath`"") + $paramsToPass
try {
# Added -WindowStyle Hidden here to keep the secondary window from "flashing"
Start-Process -FilePath "powershell.exe" -ArgumentList $argList -Verb RunAs -WindowStyle Hidden
exit 0
} catch {
Write-Log "Elevation failed: $_" -Level Error
exit 1
}
}
}
# Return coordinates for Sunrise API (may require Internet connectivity)
function Get-Geolocation {
param (
[double]$FallbackLatitude = $userLat,
[double]$FallbackLongitude = $userLng
)
Write-Log "Getting location coordinates." -verboseMessage $true
$finalCoords = @{ Latitude = 0; Longitude = 0 }
# 1. User-defined Override
if ($useUserLoc) {
Write-Log "Using user-defined coordinates from config."
$finalCoords = @{ Latitude = $FallbackLatitude; Longitude = $FallbackLongitude }
}
# 2. Windows Sensor
elseif ($null -ne (Get-Service -Name "lfsvc" -ErrorAction SilentlyContinue) -and (Get-Service -Name "lfsvc").StartType -ne 'Disabled') {
try {
Add-Type -AssemblyName 'Windows.Devices.Geolocation'
$geolocator = New-Object Windows.Devices.Geolocation.Geolocator
$asyncOp = $geolocator.GetGeopositionAsync()
$counter = 0
while ($asyncOp.Status -eq 'Started' -and $counter -lt 50) { Start-Sleep -Milliseconds 100; $counter++ }
if ($asyncOp.Status -eq 'Completed') {
$pos = $asyncOp.GetResults().Coordinate.Point.Position
$finalCoords = @{ Latitude = [double]$pos.Latitude; Longitude = [double]$pos.Longitude }
}
} catch { Write-Log "Device sensor unavailable." -verboseMessage $true }
}
# 3. IP Fallback if sensor failed
if ($finalCoords.Latitude -eq 0) {
try {
$res = Invoke-RestMethod -Uri "http://ip-api.com/json" -TimeoutSec 5
if ($res.status -eq "success") {
$finalCoords = @{ Latitude = [double]$res.lat; Longitude = [double]$res.lon }
}
} catch { Write-Log "Online IP location unreachable." -verboseMessage $true }
}
# 4. Final Default
if ($finalCoords.Latitude -eq 0) {
$finalCoords = @{ Latitude = $FallbackLatitude; Longitude = $FallbackLongitude }
}
# --- Check for possible incongruity between time zone and longitude ---
$systemOffset = [System.TimeZoneInfo]::Local.GetUtcOffset((Get-Date)).TotalHours
$expectedOffset = [Math]::Round($finalCoords.Longitude / 15)
if ([Math]::Abs($systemOffset - $expectedOffset) -gt 1) {
Write-Log "Warning: System Timezone ($systemOffset) differs from Longitude-based timezone ($expectedOffset). Check coordinates in config." -verboseMessage $true
}
return $finalCoords
}
# Calculate Sunrise and Sunset times based on coordinates and date
function Get-SolarTimes {
param (
[double]$lat,
[double]$lng,
[DateTime]$date = (Get-Date)
)
# --- 1. Basic Solar Geometry ---
$dayOfYear = $date.DayOfYear
# Fractional year in radians
$gamma = 2 * [Math]::PI / 365 * ($dayOfYear - 1)
# Equation of time (minutes) - accounts for Earth's elliptical orbit
$eqtime = 229.18 * (0.000075 + 0.001868 * [Math]::Cos($gamma) - 0.032077 * [Math]::Sin($gamma) - 0.014615 * [Math]::Cos(2 * $gamma) - 0.040849 * [Math]::Sin(2 * $gamma))
# Solar declination (radians) - accounts for Earth's axial tilt
$decl = 0.006918 - 0.399912 * [Math]::Cos($gamma) + 0.070257 * [Math]::Sin($gamma) - 0.006758 * [Math]::Cos(2 * $gamma) + 0.000907 * [Math]::Sin(2 * $gamma)
# --- 2. Calculate Hour Angle ---
# -0.833 degrees is the standard for sunrise/sunset (accounting for atmospheric refraction)
$zenithRad = 90.833 * [Math]::PI / 180
$latRad = $lat * [Math]::PI / 180
$cosHA = ([Math]::Cos($zenithRad) / ([Math]::Cos($latRad) * [Math]::Cos($decl))) - ([Math]::Tan($latRad) * [Math]::Tan($decl))
# Handle edge cases (Polar Day/Night)
if ($cosHA -ge 1) { return @{ sunrise = $null; sunset = $null; status = "Polar Night" } }
if ($cosHA -le -1) { return @{ sunrise = $null; sunset = $null; status = "Polar Day" } }
$ha = [Math]::Acos($cosHA) * 180 / [Math]::PI
# --- 3. Final UTC Calculation ---
$sunriseUTC = 720 - 4 * ($lng + $ha) - $eqtime
$sunsetUTC = 720 - 4 * ($lng - $ha) - $eqtime
# --- 4. Local Conversion ---
# We grab the current system's timezone offset automatically
$offset = [System.TimeZoneInfo]::Local.GetUtcOffset($date).TotalHours
return @{
sunrise = $date.Date.AddMinutes($sunriseUTC).AddHours($offset)
sunset = $date.Date.AddMinutes($sunsetUTC).AddHours($offset)
status = "Success"
}
}
# Debug function. Turn off accent color in taskbar. This is called by the Set-ThemeFile function.
function Disable-TaskbarAccent {
param (
[ValidateSet("On","Off")]
[string]$State
)
$value = if ($State -eq "On") { 1 } else { 0 }
# This controls "Show accent color on Start and taskbar"
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name "ColorPrevalence" -Value $value -Force
}
# Sets the system color mode directly via registry and refreshes the UI
function Set-ThemeMode {
param ([string]$Mode)
$value = if ($Mode -eq "light") { 1 } else { 0 }
$path = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize"
Write-Log "Setting native $Mode mode via registry." -verboseMessage $true