-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVIGIL.ps1
More file actions
2328 lines (2136 loc) · 91.7 KB
/
VIGIL.ps1
File metadata and controls
2328 lines (2136 loc) · 91.7 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
# VIGIL - Personal Task Command Center
# Phase 1: widget + data layer + Apple-styled UI (reduce-motion variant)
#
# Environment requirements verified by preflight.ps1 (schema v2, 58/60):
# - #31 BitLocker OFF -> tasks.json is DPAPI-wrapped (CurrentUser scope)
# - #45 MinAnimate OFF -> all WPF Storyboards removed (static UI)
#
# Usage: powershell -ExecutionPolicy Bypass -WindowStyle Hidden -File .\VIGIL.ps1
param(
[switch]$NoUI
)
# Build stamp - bumped on every commit. Visible in status bar + vigil.log.
# Format: YYYY-MM-DD HH:MM (UTC) buildN
$script:VigilVersion = '2026-04-13 16:30 UTC build66 sync-fix-taskbar-icon'
$ErrorActionPreference = 'Stop'
# --- OS detection (allows running core logic on Linux/macOS pwsh for tests) ---
$script:IsWindowsHost = $true
if ($PSVersionTable.PSVersion.Major -ge 6) {
if ($IsLinux -or $IsMacOS) { $script:IsWindowsHost = $false }
}
if ($script:IsWindowsHost) {
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName System.Security
Add-Type -AssemblyName System.Windows.Forms
}
# --- Win32 P/Invoke (foreground tracking + window activation) --------------
# Mica/Fluent is delegated to .NET 9 WPF's built-in ThemeMode="System" - no DWM code needed.
if ($script:IsWindowsHost -and -not ([System.Management.Automation.PSTypeName]'VigilWin32').Type) {
Add-Type -ErrorAction Stop -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class VigilWin32 {
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
}
"@
}
# --- Fluent (Mica + dark title bar) capability detection ------------------
# Requires pwsh 7.5+, .NET 9+, Windows 11 (build 22000+).
$script:HasFluent = $false
$script:FluentDiag = 'not-detected'
if ($script:IsWindowsHost) {
try {
$psVer = $PSVersionTable.PSVersion
$netVer = [Environment]::Version
# Environment.OSVersion.Version.Build is unreliable on Win11 under
# legacy compat manifests (can report 19041). Read from registry
# for the actual current build.
$winBuild = 0
try {
$regKey = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
$cb = (Get-ItemProperty -Path $regKey -Name CurrentBuildNumber -ErrorAction Stop).CurrentBuildNumber
$winBuild = [int]$cb
} catch {
try { $winBuild = [Environment]::OSVersion.Version.Build } catch { $winBuild = 0 }
}
$psOk = ($psVer.Major -gt 7) -or ($psVer.Major -eq 7 -and $psVer.Minor -ge 5)
$netOk = ($netVer.Major -ge 9)
$winOk = ($winBuild -ge 22000)
$script:FluentDiag = 'ps={0}.{1} net={2}.{3} winBuild={4} ps_ok={5} net_ok={6} win_ok={7}' -f `
$psVer.Major, $psVer.Minor, $netVer.Major, $netVer.Minor, $winBuild, $psOk, $netOk, $winOk
if ($psOk -and $netOk -and $winOk) { $script:HasFluent = $true }
} catch {
$script:FluentDiag = 'detection error: ' + $_.Exception.Message
}
}
# --- Hotkey helper (C# bridge so PS avoids HwndSourceHook ref-delegate cast)
if ($script:IsWindowsHost -and -not ([System.Management.Automation.PSTypeName]'VigilHotkey').Type) {
# Use exact paths of already-loaded WPF assemblies. On PS 7.5 + .NET 9,
# passing short names "PresentationCore,WindowsBase" mixes net9 PresentationCore
# with .NET Framework 4.0 WindowsBase and the compiler throws CS1705.
$wbPath = [System.Windows.Threading.Dispatcher].Assembly.Location
$pcPath = [System.Windows.Media.Color].Assembly.Location
Add-Type -ErrorAction Stop -ReferencedAssemblies $wbPath, $pcPath -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Windows.Interop;
public static class VigilHotkey {
public static event Action HotkeyPressed;
private const int WM_HOTKEY = 0x0312;
private const int HOTKEY_ID = 9001;
private static HwndSource _src;
public static bool Register(IntPtr hwnd, uint mods, uint vk) {
_src = HwndSource.FromHwnd(hwnd);
if (_src == null) return false;
_src.AddHook(WndProc);
return RegisterHotKey(hwnd, HOTKEY_ID, mods, vk);
}
public static void Unregister(IntPtr hwnd) {
try { UnregisterHotKey(hwnd, HOTKEY_ID); } catch { }
if (_src != null) { try { _src.RemoveHook(WndProc); } catch { } _src = null; }
}
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {
if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID) {
var h = HotkeyPressed;
if (h != null) h();
}
return IntPtr.Zero;
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
"@
}
# --- Single instance (Windows UI only; skip on Linux or -NoUI) ------------
if ($script:IsWindowsHost -and -not $NoUI) {
$script:Mutex = New-Object System.Threading.Mutex($false, 'Global\VIGIL_TaskTracker')
if (-not $script:Mutex.WaitOne(0, $false)) {
$h = [VigilWin32]::FindWindow($null, 'VIGIL')
if ($h -ne [IntPtr]::Zero) {
[VigilWin32]::ShowWindow($h, 9) | Out-Null
[VigilWin32]::SetForegroundWindow($h) | Out-Null
}
exit 0
}
}
# --- Paths -----------------------------------------------------------------
# Storage root: script directory (.vigil lives next to VIGIL.ps1), falls back to UserProfile.
$script:UserHome = [Environment]::GetFolderPath('UserProfile')
if (-not $script:UserHome) { $script:UserHome = $HOME }
function Resolve-VigilStorageRoot {
# Co-located: .vigil lives next to VIGIL.ps1 so it follows the script wherever it runs.
$scriptPath = $PSCommandPath
if (-not $scriptPath) { $scriptPath = $MyInvocation.MyCommand.Path }
if ($scriptPath) {
$scriptDir = Split-Path -Parent $scriptPath
if ($scriptDir -and (Test-Path $scriptDir)) { return $scriptDir }
}
return $script:UserHome
}
$script:StorageRoot = Resolve-VigilStorageRoot
$script:VigilDir = Join-Path $script:StorageRoot '.vigil'
$script:TasksPath = Join-Path $script:VigilDir 'tasks.json'
$script:BackupPath = Join-Path $script:VigilDir 'tasks.backup.json'
$script:TmpPath = Join-Path $script:VigilDir 'tasks.tmp.json'
$script:SettingsPath = Join-Path $script:VigilDir 'settings.json'
$script:LogPath = Join-Path $script:VigilDir 'vigil.log'
if (-not (Test-Path $script:VigilDir)) { New-Item -ItemType Directory -Path $script:VigilDir -Force | Out-Null }
# One-time migration: if a legacy ~/.vigil exists and the new root differs, copy files over.
$script:LegacyVigilDir = Join-Path $script:UserHome '.vigil'
if ($script:LegacyVigilDir -ne $script:VigilDir -and (Test-Path $script:LegacyVigilDir)) {
foreach ($f in 'tasks.json','settings.json','tasks.backup.json') {
$src = Join-Path $script:LegacyVigilDir $f
$dst = Join-Path $script:VigilDir $f
if ((Test-Path $src) -and -not (Test-Path $dst)) {
try { Copy-Item -LiteralPath $src -Destination $dst -Force } catch {}
}
}
}
function Write-VigilLog([string]$msg) {
$ts = Get-Date -Format 'yyyy-MM-ddTHH:mm:ss'
"$ts $msg" | Add-Content -Path $script:LogPath -Encoding UTF8
}
# Log rotation: keep last 500 lines
try {
if ((Test-Path $script:LogPath) -and (Get-Content $script:LogPath).Count -gt 500) {
$tail = Get-Content $script:LogPath -Tail 500
$logUtf8 = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllLines($script:LogPath, $tail, $logUtf8)
}
} catch { }
# --- DPAPI wrap / unwrap (Windows-only; pass-through on Linux/macOS) -------
function Protect-VigilBytes([byte[]]$plain) {
if (-not $script:IsWindowsHost) { return $plain }
[System.Security.Cryptography.ProtectedData]::Protect(
$plain, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
}
function Unprotect-VigilBytes([byte[]]$cipher) {
if (-not $script:IsWindowsHost) { return $cipher }
[System.Security.Cryptography.ProtectedData]::Unprotect(
$cipher, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
}
# --- Data layer ------------------------------------------------------------
function New-VigilTask {
param(
[string]$Title,
[ValidateSet('low','normal','high','critical')][string]$Priority = 'normal',
[datetime]$DueDate = [datetime]::MinValue,
[string]$Source = 'manual',
[string]$Notes = ''
)
$dueIso = ''
if ($DueDate -gt [datetime]::MinValue) { $dueIso = $DueDate.ToString('o') }
[pscustomobject]@{
id = [guid]::NewGuid().ToString()
title = $Title
priority = $Priority
dueDate = $dueIso
source = $Source
category = ''
notes = $Notes
done = $false
createdAt = (Get-Date).ToString('o')
doneAt = ''
}
}
function Load-VigilTasks {
if (-not (Test-Path $script:TasksPath)) {
Write-VigilLog "Load: no tasks file at $script:TasksPath"
return @()
}
foreach ($path in @($script:TasksPath, $script:BackupPath)) {
if (-not (Test-Path $path)) { continue }
try {
$cipher = [System.IO.File]::ReadAllBytes($path)
if ($cipher.Length -eq 0) {
Write-VigilLog "Load: $path is empty"
continue
}
$plain = Unprotect-VigilBytes $cipher
$json = [System.Text.Encoding]::UTF8.GetString($plain)
if ([string]::IsNullOrWhiteSpace($json)) {
Write-VigilLog "Load: $path decrypted but JSON is empty"
continue
}
$parsed = ConvertFrom-Json $json
$arr = @($parsed)
$lmsg = 'Load: read {0} tasks from {1}' -f $arr.Count, $path
Write-VigilLog $lmsg
return $arr
} catch {
$lfmsg = 'Load FAILED for {0} : {1}' -f $path, $_.Exception.Message
Write-VigilLog $lfmsg
continue
}
}
Write-VigilLog 'Load: both primary and backup failed - returning empty'
return @()
}
function Save-VigilTasks([object[]]$tasks) {
try {
$arr = @($tasks)
$json = ConvertTo-Json -InputObject $arr -Depth 6 -Compress
if ([string]::IsNullOrWhiteSpace($json)) { $json = '[]' }
$plain = [System.Text.Encoding]::UTF8.GetBytes($json)
$cipher = Protect-VigilBytes $plain
[System.IO.File]::WriteAllBytes($script:TmpPath, $cipher)
if (Test-Path $script:TasksPath) {
[System.IO.File]::Replace($script:TmpPath, $script:TasksPath, $script:BackupPath)
} else {
[System.IO.File]::Move($script:TmpPath, $script:TasksPath)
}
$msg = 'Save: wrote {0} tasks ({1} bytes cipher)' -f $arr.Count, $cipher.Length
Write-VigilLog $msg
} catch {
$emsg = 'Save FAILED: {0}' -f $_.Exception.Message
Write-VigilLog $emsg
throw
}
}
# --- Settings --------------------------------------------------------------
function Load-VigilSettings {
$default = @{
posX = 1200; posY = 400; collapsed = $false; showCompleted = $false
outlookSync = $false; syncIntervalMin = 15; opacity = 1.0
lastSyncTime = ''; activeFilter = 'all'; autoStartInstalled = $false
sortMode = 'smart'; searchText = ''; welcomeShown = $false
}
$loaded = @{}
if (Test-Path $script:SettingsPath) {
try {
$utf8 = New-Object System.Text.UTF8Encoding($false)
$raw = [System.IO.File]::ReadAllText($script:SettingsPath, $utf8)
$parsed = ConvertFrom-Json $raw
foreach ($p in $parsed.PSObject.Properties) { $loaded[$p.Name] = $p.Value }
} catch {
$smsg = 'Settings load failed: {0}' -f $_.Exception.Message
Write-VigilLog $smsg
}
}
# Merge loaded over defaults - guarantees every key exists on the returned object
$merged = @{}
foreach ($k in $default.Keys) { $merged[$k] = $default[$k] }
foreach ($k in $loaded.Keys) { $merged[$k] = $loaded[$k] }
[pscustomobject]$merged
}
function Save-VigilSettings($settings) {
try {
$json = ConvertTo-Json -InputObject $settings -Depth 4
$utf8 = New-Object System.Text.UTF8Encoding($false)
$bytes = $utf8.GetBytes($json)
$tmp = $script:SettingsPath + '.tmp'
[System.IO.File]::WriteAllBytes($tmp, $bytes)
if (Test-Path $script:SettingsPath) {
[System.IO.File]::Delete($script:SettingsPath)
}
[System.IO.File]::Move($tmp, $script:SettingsPath)
} catch {
$m = 'Save-VigilSettings FAILED: {0}' -f $_.Exception.Message
Write-VigilLog $m
}
}
# --- Phase 5: Task mutation helpers (logic-only, testable cross-platform) ---
# Each helper reloads from disk, mutates, atomic-saves, updates $Global:VigilTasks.
# UI event handlers call these so the closures never mutate shared state directly.
function Add-VigilTask($task) {
$cur = @(Load-VigilTasks)
$clean = @()
foreach ($t in $cur) { if ($null -ne $t -and $t.id) { $clean += $t } }
$clean += $task
Save-VigilTasks $clean
$Global:VigilTasks = $clean
return $task
}
function Remove-VigilTask([string]$id) {
$cur = @(Load-VigilTasks)
$new = @()
foreach ($t in $cur) {
if ($null -ne $t -and $t.id -and $t.id -ne $id) { $new += $t }
}
Save-VigilTasks $new
$Global:VigilTasks = $new
return ($new.Count -lt $cur.Count)
}
function Get-VigilTaskById([string]$id) {
$cur = @(Load-VigilTasks)
foreach ($t in $cur) {
if ($null -ne $t -and $t.id -eq $id) { return $t }
}
return $null
}
function Update-VigilTask {
param(
[string]$Id,
[string]$Title,
[string]$Priority,
[string]$DueDate,
[string]$Notes,
$Done
)
$cur = @(Load-VigilTasks)
$found = $false
foreach ($t in $cur) {
if ($null -eq $t -or $t.id -ne $Id) { continue }
$found = $true
if ($PSBoundParameters.ContainsKey('Title') -and $Title) {
$t.title = $Title
}
if ($PSBoundParameters.ContainsKey('Priority') -and $Priority) {
if (@('low','normal','high','critical') -contains $Priority) {
$t.priority = $Priority
}
}
if ($PSBoundParameters.ContainsKey('DueDate')) {
$t.dueDate = [string]$DueDate
}
if ($PSBoundParameters.ContainsKey('Notes')) {
$t.notes = [string]$Notes
}
if ($PSBoundParameters.ContainsKey('Done') -and $null -ne $Done) {
$t.done = [bool]$Done
if ($t.done) { $t.doneAt = (Get-Date).ToString('o') } else { $t.doneAt = '' }
}
break
}
if ($found) {
Save-VigilTasks $cur
$Global:VigilTasks = $cur
}
return $found
}
function Get-VigilOverdueTasks([object[]]$tasks) {
$now = Get-Date
$out = @()
foreach ($t in $tasks) {
if ($null -eq $t -or -not $t.id) { continue }
if ($t.done) { continue }
if (-not $t.dueDate) { continue }
try {
$d = [datetime]::Parse($t.dueDate)
if ($d -lt $now) { $out += $t }
} catch {}
}
return $out
}
function Export-VigilMarkdown {
param(
[object[]]$tasks,
[switch]$IncludeCalendar
)
$now = Get-Date
$sb = New-Object System.Text.StringBuilder
[void]$sb.AppendLine('# VIGIL Tasks')
[void]$sb.AppendLine('')
[void]$sb.AppendLine(('_Generated {0}_' -f $now.ToString('yyyy-MM-dd HH:mm')))
[void]$sb.AppendLine('')
$overdue = @(); $active = @(); $done = @()
foreach ($t in $tasks) {
if ($null -eq $t -or -not $t.id) { continue }
# Calendar items are excluded from markdown export by default - they
# are meeting reminders, not actionable work the user wants in a list.
if (-not $IncludeCalendar -and $t.source -eq 'outlook-cal') { continue }
if ($t.done) { $done += $t; continue }
$isOverdue = $false
if ($t.dueDate) {
try { if ([datetime]::Parse($t.dueDate) -lt $now) { $isOverdue = $true } } catch {}
}
if ($isOverdue) { $overdue += $t } else { $active += $t }
}
if ($overdue.Count -gt 0) {
[void]$sb.AppendLine('## Overdue')
[void]$sb.AppendLine('')
foreach ($t in @(Sort-VigilTasks -tasks $overdue -mode 'priority')) {
$line = '- [ ] **{0}** ({1}) - {2}' -f $t.title, $t.priority, (Format-DueLabel $t.dueDate)
[void]$sb.AppendLine($line)
}
[void]$sb.AppendLine('')
}
if ($active.Count -gt 0) {
[void]$sb.AppendLine('## Active')
[void]$sb.AppendLine('')
foreach ($t in @(Sort-VigilTasks -tasks $active -mode 'smart')) {
$due = Format-DueLabel $t.dueDate
if ($due) {
$line = '- [ ] {0} ({1}) - {2}' -f $t.title, $t.priority, $due
} else {
$line = '- [ ] {0} ({1})' -f $t.title, $t.priority
}
[void]$sb.AppendLine($line)
}
[void]$sb.AppendLine('')
}
if ($done.Count -gt 0) {
[void]$sb.AppendLine('## Completed')
[void]$sb.AppendLine('')
foreach ($t in $done) {
[void]$sb.AppendLine(('- [x] {0}' -f $t.title))
}
}
return $sb.ToString()
}
# --- Phase 3: Outlook COM sync --------------------------------------------
function Test-OutlookAvailable {
if (-not $script:IsWindowsHost) { return $false }
$ol = $null
try {
$ol = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Outlook.Application')
return $true
} catch {
return $false
} finally {
if ($null -ne $ol) {
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($ol) } catch {}
}
[GC]::Collect(); [GC]::WaitForPendingFinalizers()
}
}
function Set-VigilSourceRef {
param($task, [string]$ref)
if ($task.PSObject.Properties.Match('sourceRef').Count -eq 0) {
Add-Member -InputObject $task -MemberType NoteProperty -Name sourceRef -Value $ref -Force
} else {
$task.sourceRef = $ref
}
}
function Sync-VigilFromOutlook {
if (-not $script:IsWindowsHost) { return $false }
$ol = $null; $ns = $null
$added = 0; $completed = 0
try {
# Try to attach to running Outlook first (GetActiveObject is unreliable on .NET 9,
# so always fall through to New-Object regardless of the outlookSync setting).
try { $ol = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Outlook.Application') } catch { $ol = $null }
if (-not $ol) {
try { $ol = New-Object -ComObject Outlook.Application } catch {
Write-VigilLog ('Outlook COM unavailable: ' + $_.Exception.Message)
return $false
}
}
$ns = $ol.GetNamespace('MAPI')
# Reload from disk (bulletproof against in-memory staleness)
$current = @(Load-VigilTasks)
$cleaned = @()
foreach ($t in $current) { if ($null -ne $t -and $t.id) { $cleaned += $t } }
$current = $cleaned
# Build dedup set: 'source|sourceRef' -> existing task
$existing = @{}
foreach ($t in $current) {
$ref = ''
if ($t.PSObject.Properties.Match('sourceRef').Count -gt 0) { $ref = [string]$t.sourceRef }
if ($t.source -and $ref) {
$existing[([string]$t.source + '|' + $ref)] = $t
}
}
# ---- Calendar (next 24h meetings) ----
$cal = $null; $calItems = $null; $restricted = $null
try {
$cal = $ns.GetDefaultFolder(9)
$calItems = $cal.Items
$calItems.IncludeRecurrences = $true
$calItems.Sort('[Start]')
$start = (Get-Date).ToString('g')
$end = (Get-Date).AddHours(24).ToString('g')
$filter = "[Start] >= '" + $start + "' AND [Start] <= '" + $end + "'"
$restricted = $calItems.Restrict($filter)
foreach ($apt in $restricted) {
try {
$entryId = [string]$apt.EntryID
$key = 'outlook-cal|' + $entryId
if (-not $existing.ContainsKey($key)) {
$subject = [string]$apt.Subject
if ([string]::IsNullOrWhiteSpace($subject)) { $subject = '(no subject)' }
$task = New-VigilTask -Title $subject -Priority 'high' -Source 'outlook-cal'
$task.dueDate = $apt.Start.ToString('o')
Set-VigilSourceRef $task $entryId
$current += $task
$added++
}
} finally {
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($apt) } catch {}
}
}
} finally {
foreach ($o in @($restricted, $calItems, $cal)) {
if ($null -ne $o) { try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($o) } catch {} }
}
}
# ---- Flagged emails ----
$inb = $null; $inbItems = $null; $flagged = $null
try {
$inb = $ns.GetDefaultFolder(6)
$inbItems = $inb.Items
$flagged = $inbItems.Restrict('[FlagStatus] = 2')
foreach ($mail in $flagged) {
try {
$entryId = [string]$mail.EntryID
$key = 'outlook-flag|' + $entryId
if (-not $existing.ContainsKey($key)) {
$subject = [string]$mail.Subject
if ([string]::IsNullOrWhiteSpace($subject)) { $subject = '(no subject)' }
if ($subject.Length -gt 80) { $subject = $subject.Substring(0, 77) + '...' }
$task = New-VigilTask -Title $subject -Priority 'normal' -Source 'outlook-flag'
try {
if ($mail.TaskDueDate -and $mail.TaskDueDate.Year -gt 2000) {
$task.dueDate = $mail.TaskDueDate.ToString('o')
}
} catch {}
Set-VigilSourceRef $task $entryId
$current += $task
$added++
}
} finally {
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($mail) } catch {}
}
}
} finally {
foreach ($o in @($flagged, $inbItems, $inb)) {
if ($null -ne $o) { try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($o) } catch {} }
}
}
# ---- Outlook Tasks folder (incomplete only) ----
$tks = $null; $tksItems = $null; $openTasks = $null
try {
$tks = $ns.GetDefaultFolder(13)
$tksItems = $tks.Items
$openTasks = $tksItems.Restrict('[Complete] = False')
$priMap = @{ 0 = 'low'; 1 = 'normal'; 2 = 'high' }
foreach ($ot in $openTasks) {
try {
$entryId = [string]$ot.EntryID
$key = 'outlook-task|' + $entryId
if (-not $existing.ContainsKey($key)) {
$subject = [string]$ot.Subject
if ([string]::IsNullOrWhiteSpace($subject)) { $subject = '(no subject)' }
$pri = 'normal'
try {
$imp = [int]$ot.Importance
if ($priMap.ContainsKey($imp)) { $pri = $priMap[$imp] }
} catch {}
$task = New-VigilTask -Title $subject -Priority $pri -Source 'outlook-task'
try {
if ($ot.DueDate -and $ot.DueDate.Year -gt 2000) {
$task.dueDate = $ot.DueDate.ToString('o')
}
} catch {}
Set-VigilSourceRef $task $entryId
$current += $task
$added++
}
} finally {
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($ot) } catch {}
}
}
} finally {
foreach ($o in @($openTasks, $tksItems, $tks)) {
if ($null -ne $o) { try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($o) } catch {} }
}
}
# Auto-complete past calendar items
$now = Get-Date
foreach ($t in $current) {
if ($t.source -eq 'outlook-cal' -and -not $t.done -and $t.dueDate) {
try {
$d = [datetime]::Parse($t.dueDate)
if ($d -lt $now) {
$t.done = $true
$t.doneAt = $now.ToString('o')
$completed++
}
} catch {}
}
}
Save-VigilTasks $current
$Global:VigilTasks = $current
$Global:VigilSettings.lastSyncTime = (Get-Date).ToString('o')
Save-VigilSettings $Global:VigilSettings
$msg = 'Outlook sync OK: +{0} new, {1} auto-completed' -f $added, $completed
Write-VigilLog $msg
return $true
} catch {
$em = 'Outlook sync FAILED: ' + $_.Exception.Message
Write-VigilLog $em
return $false
} finally {
foreach ($o in @($ns, $ol)) {
if ($null -ne $o) { try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($o) } catch {} }
}
[GC]::Collect(); [GC]::WaitForPendingFinalizers()
[GC]::Collect(); [GC]::WaitForPendingFinalizers()
}
}
# --- Phase 4: Auto-start shortcut + filter helpers -------------------------
function Find-VigilPwshExe {
# Prefer pwsh 7.x over Windows PowerShell 5.1 for Fluent support.
$candidates = @()
if ($env:ProgramFiles) {
$candidates += (Join-Path $env:ProgramFiles 'PowerShell\7\pwsh.exe')
}
$pf86 = [Environment]::GetEnvironmentVariable('ProgramFiles(x86)')
if ($pf86) { $candidates += (Join-Path $pf86 'PowerShell\7\pwsh.exe') }
if ($env:LOCALAPPDATA) {
$candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\PowerShell\7\pwsh.exe')
}
foreach ($c in $candidates) {
if ($c -and (Test-Path $c)) { return $c }
}
try {
$cmd = Get-Command pwsh -ErrorAction SilentlyContinue
if ($cmd -and $cmd.Source) { return $cmd.Source }
} catch {}
return $null
}
function Install-VigilStartupShortcut {
if (-not $script:IsWindowsHost) { return }
try {
if ($Global:VigilSettings.autoStartInstalled) { return }
$startupDir = [Environment]::GetFolderPath('Startup')
if (-not (Test-Path $startupDir)) { return }
$lnkPath = Join-Path $startupDir 'VIGIL.lnk'
# VIGIL requires PowerShell 7.x (pwsh.exe). Do not fall back to 5.1.
$launcher = Find-VigilPwshExe
if (-not $launcher) {
Write-VigilLog 'Startup shortcut skipped: pwsh.exe not found (PowerShell 7+ required)'
return
}
$wsh = New-Object -ComObject WScript.Shell
try {
$shortcut = $wsh.CreateShortcut($lnkPath)
$shortcut.TargetPath = $launcher
$scriptPath = $PSCommandPath
if (-not $scriptPath) { $scriptPath = $MyInvocation.MyCommand.Path }
$shortcut.Arguments = '-ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $scriptPath + '"'
$shortcut.WorkingDirectory = Split-Path $scriptPath
$shortcut.Description = 'VIGIL - Personal Task Command Center'
$shortcut.WindowStyle = 7 # minimized
$shortcut.Save()
} finally {
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($wsh) } catch {}
}
$Global:VigilSettings.autoStartInstalled = $true
Save-VigilSettings $Global:VigilSettings
Write-VigilLog ('Startup shortcut installed: ' + $launcher)
} catch {
$em = 'Startup shortcut install failed: ' + $_.Exception.Message
Write-VigilLog $em
}
}
function Install-VigilDesktopShortcut {
if (-not $script:IsWindowsHost) { return }
try {
$desktopDir = [Environment]::GetFolderPath('Desktop')
if (-not $desktopDir -or -not (Test-Path $desktopDir)) { return }
$lnkPath = Join-Path $desktopDir 'VIGIL.lnk'
if (Test-Path $lnkPath) { return }
# VIGIL requires PowerShell 7.x (pwsh.exe). Do not fall back to 5.1.
$launcher = Find-VigilPwshExe
if (-not $launcher) {
Write-VigilLog 'Desktop shortcut skipped: pwsh.exe not found (PowerShell 7+ required)'
return
}
$scriptPath = $PSCommandPath
if (-not $scriptPath) { $scriptPath = $MyInvocation.MyCommand.Path }
$wsh = New-Object -ComObject WScript.Shell
try {
$shortcut = $wsh.CreateShortcut($lnkPath)
$shortcut.TargetPath = $launcher
$shortcut.Arguments = '-ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $scriptPath + '"'
$shortcut.WorkingDirectory = Split-Path $scriptPath
$shortcut.Description = 'VIGIL - Personal Task Command Center'
$shortcut.WindowStyle = 7
$shortcut.Save()
} finally {
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($wsh) } catch {}
}
Write-VigilLog ('Desktop shortcut installed: ' + $lnkPath)
} catch {
Write-VigilLog ('Desktop shortcut install failed: ' + $_.Exception.Message)
}
}
function Filter-VigilTasks([object[]]$tasks, [string]$mode) {
if (-not $mode) { $mode = 'all' }
$now = Get-Date
$out = @()
if ($null -eq $tasks) { return $out }
foreach ($t in $tasks) {
if ($null -eq $t -or -not $t.id) { continue }
$keep = $false
switch ($mode) {
'cal' { $keep = ($t.source -eq 'outlook-cal') }
'task' { $keep = ($t.source -ne 'outlook-cal') }
'manual' { $keep = ($t.source -eq 'manual') }
'outlook' { $keep = ($t.source -like 'outlook-*') }
'urgent' { $keep = ($t.priority -eq 'critical' -or $t.priority -eq 'high') }
'high' { $keep = ($t.priority -eq 'high') }
'crit' {
if ($t.priority -eq 'critical') {
$keep = $true
} elseif ($t.dueDate -and -not $t.done) {
try { $keep = ([datetime]::Parse($t.dueDate) -lt $now) } catch { $keep = $false }
}
}
default { $keep = $true }
}
if ($keep) { $out += $t }
}
return $out
}
function Search-VigilTasks([object[]]$tasks, [string]$query) {
if ([string]::IsNullOrWhiteSpace($query)) { return ,$tasks }
$needle = $query.Trim().ToLower()
$out = @()
foreach ($t in $tasks) {
if ($null -eq $t -or -not $t.title) { continue }
if ($t.title.ToLower().Contains($needle)) {
$out += $t; continue
}
if ($t.notes -and $t.notes.ToString().ToLower().Contains($needle)) {
$out += $t
}
}
# comma operator wraps the array so PS does not unwrap it to $null when empty
return ,$out
}
# --- Sort + priority helpers -----------------------------------------------
$script:PriorityRank = @{ critical = 0; high = 1; normal = 2; low = 3 }
function Sort-VigilTasks([object[]]$tasks, [string]$mode = 'smart') {
$now = Get-Date
$annotated = foreach ($t in $tasks) {
$due = [datetime]::MaxValue
if ($t.dueDate) {
try { $due = [datetime]::Parse($t.dueDate) } catch {}
}
$overdue = 1
if (($due -lt $now) -and (-not $t.done)) { $overdue = 0 }
$prank = 9
$pkey = 'normal'
if ($t.priority) { $pkey = [string]$t.priority }
if ($script:PriorityRank.ContainsKey($pkey)) {
$prank = $script:PriorityRank[$pkey]
}
$created = [datetime]::MinValue
if ($t.createdAt) {
try { $created = [datetime]::Parse($t.createdAt) } catch {}
}
[pscustomobject]@{
_task = $t
_overdue = $overdue
_priority = $prank
_due = $due
_created = $created
}
}
$annotatedArr = @($annotated)
if ($mode -eq 'added') {
$sorted = @($annotatedArr | Sort-Object -Property _created -Descending)
} elseif ($mode -eq 'priority') {
$sorted = @($annotatedArr | Sort-Object -Property _priority, _due)
} elseif ($mode -eq 'due') {
$sorted = @($annotatedArr | Sort-Object -Property _due, _priority)
} else {
$sorted = @($annotatedArr | Sort-Object -Property _overdue, _priority, _due)
}
$out = @()
foreach ($row in $sorted) { $out += $row._task }
return $out
}
function Format-DueLabel([string]$iso) {
if ([string]::IsNullOrWhiteSpace($iso)) { return '' }
try {
$d = [datetime]::Parse($iso)
$now = Get-Date
$today = $now.Date
$tomorrow = $today.AddDays(1)
# Overdue check FIRST so tasks due earlier today don't show "Today 3PM"
# when it's already 5PM. Overdue is the more useful signal.
if ($d -lt $now) {
if ($d.Date -eq $today) { return ('Overdue {0}' -f $d.ToString('h:mm tt')) }
return ('Overdue {0}' -f $d.ToString('MMM d'))
}
if ($d.Date -eq $today) { return ('Today {0}' -f $d.ToString('h:mm tt')) }
if ($d.Date -eq $tomorrow) { return ('Tomorrow {0}' -f $d.ToString('h:mm tt')) }
if (($d - $now).Days -lt 7) { return $d.ToString('dddd h:mm tt') }
return $d.ToString('MMM d')
} catch { return '' }
}
# --- Core logic above this line is cross-platform and independent of UI ---
# Below this line is Windows WPF only. Tests run with -NoUI and return here.
if ($NoUI -or -not $script:IsWindowsHost) { return }
# --- XAML (custom dark theme, designed from scratch, reduce-motion) --------
$xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="VIGIL"
Width="420" SizeToContent="Height"
WindowStyle="None" ResizeMode="NoResize"
AllowsTransparency="False" Background="{x:Null}" {{THEMEMODE}}
Topmost="True" ShowInTaskbar="True"
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Grayscale"
UseLayoutRounding="True"
SnapsToDevicePixels="True"
>
<Border x:Name="OuterFrame" CornerRadius="0" Background="Transparent"
BorderThickness="0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Toolbar (chromeless title bar - all items uniform 22px height) -->
<Border Grid.Row="0" x:Name="TitleBar" Background="Transparent" Padding="10,6">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
<Border x:Name="CountCalBadge" Background="{DynamicResource AccentFillColorDefaultBrush}"
CornerRadius="0" Padding="8,2" Height="22" Tag="cal" Cursor="Hand"
VerticalAlignment="Center" MinWidth="44" ToolTip="Click to filter: Calendar items">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="CAL " FontSize="9" FontWeight="Bold" Opacity="0.75"
Foreground="{DynamicResource TextOnAccentFillColorPrimaryBrush}"
VerticalAlignment="Center"/>
<TextBlock x:Name="CountCalText" Text="0" FontSize="9" FontWeight="Bold"
Foreground="{DynamicResource TextOnAccentFillColorPrimaryBrush}"
VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border x:Name="CountTaskBadge" Background="{DynamicResource ControlFillColorDefaultBrush}"
BorderBrush="{DynamicResource ControlStrokeColorDefaultBrush}" BorderThickness="1"
CornerRadius="0" Padding="8,1" Margin="6,0,0,0" Height="22" Tag="task" Cursor="Hand"
VerticalAlignment="Center" MinWidth="44" ToolTip="Click to filter: Tasks">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="TASK " FontSize="9" FontWeight="Bold" Opacity="0.75"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
VerticalAlignment="Center"/>
<TextBlock x:Name="CountTaskText" Text="0" FontSize="9" FontWeight="Bold"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border x:Name="CountCritBadge" Background="{DynamicResource SystemFillColorCriticalBrush}"
CornerRadius="0" Padding="8,2" Margin="6,0,0,0" Height="22" Tag="crit" Cursor="Hand"
VerticalAlignment="Center" MinWidth="44" ToolTip="Click to filter: Critical / overdue">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="CRIT " FontSize="9" FontWeight="Bold" Opacity="0.85"
Foreground="#FFFFFF" VerticalAlignment="Center"/>
<TextBlock x:Name="CountCritText" Text="0" FontSize="9" FontWeight="Bold"
Foreground="#FFFFFF" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border x:Name="CountHighBadge" Background="{DynamicResource SystemFillColorCautionBrush}"
CornerRadius="0" Padding="8,2" Margin="6,0,0,0" Height="22" Tag="high" Cursor="Hand"
VerticalAlignment="Center" MinWidth="44" ToolTip="Click to filter: High priority">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="HIGH " FontSize="9" FontWeight="Bold" Opacity="0.85"
Foreground="#000000" VerticalAlignment="Center"/>
<TextBlock x:Name="CountHighText" Text="0" FontSize="9" FontWeight="Bold"
Foreground="#000000" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Center">
<Button x:Name="BtnSync" Content="SYNC"
Height="22" Padding="8,0" FontSize="9"
Margin="0,0,4,0" ToolTip="Sync from Outlook"/>
<Button x:Name="BtnSort" Content="SMART"
Height="22" Padding="8,0" FontSize="9"
Margin="0,0,4,0" ToolTip="Sort / Filter"/>
<ToggleButton x:Name="BtnShowDone" Content="DONE"
Height="22" Padding="8,0" FontSize="9"
ToolTip="Show completed tasks"/>
</StackPanel>
</Grid>
</Border>
<!-- Task list area: tabbed (TASKS | CALENDAR) -->
<Border Grid.Row="1" x:Name="TaskArea" Background="Transparent">
<DockPanel>
<TextBox x:Name="SearchInput" DockPanel.Dock="Top"
Margin="12,8,12,4" FontSize="12"
VerticalContentAlignment="Center"
ToolTip="Filter tasks by title or notes (Ctrl+F)"/>