-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesktopNotes.ps1
More file actions
760 lines (682 loc) · 29 KB
/
DesktopNotes.ps1
File metadata and controls
760 lines (682 loc) · 29 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
param(
[switch]$AddNote,
[switch]$Background,
[switch]$InitialNote
)
$ErrorActionPreference = 'Stop'
$ScriptRoot = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
$VbsLauncher = Join-Path $ScriptRoot 'Hidden.vbs'
$NotesDir = Join-Path $env:APPDATA 'DesktopNotes'
$NotesFile = Join-Path $NotesDir 'notes.json'
$TriggerFile = Join-Path $NotesDir '.trigger'
$ShutdownFile = Join-Path $NotesDir '.shutdown'
if (-not (Test-Path $NotesDir)) { New-Item -ItemType Directory -Path $NotesDir -Force | Out-Null }
$mutexName = "Local\DesktopNotes_$($env:USERNAME)"
$mutex = New-Object System.Threading.Mutex($false, $mutexName)
# ==========================================================================
# MODO -AddNote : invocado pelo menu de contexto. Captura posicao do
# cursor, grava no trigger file e dispara/sobe a instancia background.
# ==========================================================================
if ($AddNote -and -not $Background) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public class WinCursor {
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT lpPoint);
}
'@ -ErrorAction SilentlyContinue
$pt = New-Object WinCursor+POINT
[WinCursor]::GetCursorPos([ref]$pt) | Out-Null
$payload = "$([guid]::NewGuid())|$($pt.X)|$($pt.Y)"
$acquired = $false
try { $acquired = $mutex.WaitOne(0) } catch { $acquired = $false }
Set-Content -Path $TriggerFile -Value $payload -Encoding ascii -Force
if ($acquired) {
try { $mutex.ReleaseMutex() } catch {}
Start-Process -FilePath 'wscript.exe' `
-ArgumentList "`"$VbsLauncher`" `"$($MyInvocation.MyCommand.Path)`" -Background" `
-WindowStyle Hidden
}
exit 0
}
# ==========================================================================
# MODO -Background : a instancia real, com janelas WPF e tray icon.
# ==========================================================================
# Single-instance enforcement
$acquired = $false
try { $acquired = $mutex.WaitOne(0) } catch { $acquired = $false }
if (-not $acquired) {
if ($InitialNote) {
Set-Content -Path $TriggerFile -Value ([guid]::NewGuid().ToString()) -Encoding ascii -Force
}
exit 0
}
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Application precisa existir ANTES de qualquer Window ser criada via XamlReader.Load,
# senao o WPF cria um Application implicito com ShutdownMode=OnLastWindowClose,
# o que faz com que fechar a primeira nota mate o app inteiro (e todas as outras notas).
if (-not [System.Windows.Application]::Current) {
$script:App = New-Object System.Windows.Application
} else {
$script:App = [System.Windows.Application]::Current
}
$script:App.ShutdownMode = [System.Windows.ShutdownMode]::OnExplicitShutdown
$script:NotesList = @{}
$script:Saving = $false
if (Test-Path $ShutdownFile) { Remove-Item $ShutdownFile -Force -ErrorAction SilentlyContinue }
function Get-NoteXamlContent {
param($rtb)
try { return [System.Windows.Markup.XamlWriter]::Save($rtb.Document) } catch { return '' }
}
function Set-NoteContent {
param($rtb, [string]$content)
if (-not $content) {
$doc = New-Object System.Windows.Documents.FlowDocument
$doc.Blocks.Add((New-Object System.Windows.Documents.Paragraph))
$doc.PagePadding = New-Object System.Windows.Thickness 8,6,8,6
$doc.LineHeight = 1
$rtb.Document = $doc
return
}
$trimmed = $content.TrimStart()
if ($trimmed.StartsWith('<')) {
try {
$sr = New-Object System.IO.StringReader $content
$xr = [System.Xml.XmlReader]::Create($sr)
$doc = [System.Windows.Markup.XamlReader]::Load($xr)
$rtb.Document = $doc
$rtb.Document.PagePadding = New-Object System.Windows.Thickness 8,6,8,6
return
} catch { }
}
# Fallback: texto plano (notas antigas)
$doc = New-Object System.Windows.Documents.FlowDocument
$doc.PagePadding = New-Object System.Windows.Thickness 8,6,8,6
$doc.LineHeight = 1
foreach ($ln in ($content -split "`r?`n")) {
$p = New-Object System.Windows.Documents.Paragraph
if ($ln) { $p.Inlines.Add((New-Object System.Windows.Documents.Run $ln)) }
$doc.Blocks.Add($p)
}
$rtb.Document = $doc
}
function Find-CharPointer {
param([System.Windows.Documents.TextPointer]$Start, [int]$Offset)
if ($Offset -le 0) { return $Start }
$tp = $Start
$rem = $Offset
while ($rem -gt 0 -and $tp) {
$ctx = $tp.GetPointerContext([System.Windows.Documents.LogicalDirection]::Forward)
if ($ctx -eq [System.Windows.Documents.TextPointerContext]::None) { break }
$next = $tp.GetPositionAtOffset(1, [System.Windows.Documents.LogicalDirection]::Forward)
if (-not $next) { break }
if ($ctx -eq [System.Windows.Documents.TextPointerContext]::Text) { $rem-- }
$tp = $next
}
return $tp
}
function Invoke-Linkify {
param(
[System.Windows.Documents.TextPointer]$Start,
[System.Windows.Documents.TextPointer]$End,
[string]$Url
)
try { $uri = New-Object System.Uri($Url) } catch { return $false }
$rng = New-Object System.Windows.Documents.TextRange $Start, $End
$rng.Text = ''
$run = New-Object System.Windows.Documents.Run $Url
$hl = New-Object System.Windows.Documents.Hyperlink $run, $Start
$hl.NavigateUri = $uri
$hl.Foreground = (New-Object System.Windows.Media.SolidColorBrush ([System.Windows.Media.Color]::FromRgb(37, 99, 235)))
$hl.TextDecorations = [System.Windows.TextDecorations]::Underline
$hl.Cursor = [System.Windows.Input.Cursors]::Hand
$hl.ToolTip = $Url
return $true
}
function Add-MarkdownShortcuts {
param([System.Windows.Controls.RichTextBox]$rtb)
# Click direto em hyperlink abre no browser (sem precisar Ctrl)
$rtb.Add_PreviewMouseLeftButtonDown({
param($s, $e)
$pt = $e.GetPosition($s)
$tp = $s.GetPositionFromPoint($pt, $true)
if (-not $tp) { return }
$element = $tp.Parent
while ($element) {
if ($element -is [System.Windows.Documents.Hyperlink]) {
$uri = $element.NavigateUri
if ($uri) {
try { Start-Process $uri.AbsoluteUri } catch {}
$e.Handled = $true
}
return
}
if ($element -isnot [System.Windows.DependencyObject]) { return }
$element = [System.Windows.LogicalTreeHelper]::GetParent($element)
}
})
# Fallback caso o RequestNavigate seja disparado (ex: Ctrl+Click padrao do WPF)
$rtb.AddHandler(
[System.Windows.Documents.Hyperlink]::RequestNavigateEvent,
[System.Windows.Navigation.RequestNavigateEventHandler]{
param($sender, $e)
try { Start-Process $e.Uri.AbsoluteUri } catch {}
$e.Handled = $true
}
)
# Atalhos de inicio de linha (Space) + reset de heading no Enter + linkify
$rtb.Add_PreviewKeyDown({
param($s, $e)
if ($e.Key -ne [System.Windows.Input.Key]::Space -and $e.Key -ne [System.Windows.Input.Key]::Return) { return }
$cp = $s.CaretPosition
$para = $cp.Paragraph
if (-not $para) { return }
# Reset heading no Enter
if ($e.Key -eq [System.Windows.Input.Key]::Return) {
if ($para.FontSize -gt 14.5) {
$oldPara = $para
$s.Dispatcher.BeginInvoke([Action]{
$np = $s.CaretPosition.Paragraph
if ($np -and -not [object]::ReferenceEquals($np, $oldPara)) {
$np.FontSize = 14
$np.FontWeight = [System.Windows.FontWeights]::Normal
}
}) | Out-Null
}
# mesmo no Enter, tenta linkify a ultima palavra antes do caret
$rngEnt = New-Object System.Windows.Documents.TextRange $para.ContentStart, $cp
$textBeforeEnt = $rngEnt.Text
if ($textBeforeEnt -match '(?:^|\s)(https?://\S+)$') {
$rawUrl = $matches[1]
$cleanUrl = $rawUrl -replace '[.,;:!?\)\]\}]+$', ''
if ($cleanUrl.Length -gt 0) {
$startIdx = $textBeforeEnt.Length - $rawUrl.Length
$endIdx = $startIdx + $cleanUrl.Length
$tpS = Find-CharPointer $para.ContentStart $startIdx
$tpE = Find-CharPointer $para.ContentStart $endIdx
if ($tpS -and $tpE) { [void](Invoke-Linkify $tpS $tpE $cleanUrl) }
}
}
return
}
$rng = New-Object System.Windows.Documents.TextRange $para.ContentStart, $cp
$line = $rng.Text
$action = $null
switch ($line) {
'-' { $action = 'bullet' }
'*' { $action = 'bullet' }
'1.' { $action = 'number' }
'[]' { $action = 'check' }
'#' { $action = 'h1' }
'##' { $action = 'h2' }
}
if (-not $action) {
# Tenta linkify URL imediatamente antes do caret
if ($line -match '(?:^|\s)(https?://\S+)$') {
$rawUrl = $matches[1]
$cleanUrl = $rawUrl -replace '[.,;:!?\)\]\}]+$', ''
if ($cleanUrl.Length -gt 0) {
$startIdx = $line.Length - $rawUrl.Length
$endIdx = $startIdx + $cleanUrl.Length
$tpS = Find-CharPointer $para.ContentStart $startIdx
$tpE = Find-CharPointer $para.ContentStart $endIdx
if ($tpS -and $tpE) { [void](Invoke-Linkify $tpS $tpE $cleanUrl) }
}
}
return
}
$e.Handled = $true
$rng.Text = ''
switch ($action) {
'bullet' { [System.Windows.Documents.EditingCommands]::ToggleBullets.Execute($null, $s) }
'number' { [System.Windows.Documents.EditingCommands]::ToggleNumbering.Execute($null, $s) }
'check' {
$np = $s.CaretPosition.Paragraph
if ($np) {
$run = New-Object System.Windows.Documents.Run ([char]0x2610 + ' ')
if ($np.Inlines.Count -gt 0) {
$np.Inlines.InsertBefore($np.Inlines.FirstInline, $run)
} else {
$np.Inlines.Add($run)
}
$s.CaretPosition = $np.ContentEnd
}
}
'h1' {
$cur = $s.CaretPosition.Paragraph
if ($cur) {
$cur.FontSize = 17
$cur.FontWeight = [System.Windows.FontWeights]::SemiBold
}
}
'h2' {
$cur = $s.CaretPosition.Paragraph
if ($cur) {
$cur.FontSize = 15
$cur.FontWeight = [System.Windows.FontWeights]::SemiBold
}
}
}
})
# Inline pairs: !texto! -> bold, /texto/ -> strike
$rtb.Add_PreviewTextInput({
param($s, $e)
$marker = $e.Text
if ($marker -ne '!' -and $marker -ne '/') { return }
$cp = $s.CaretPosition
$para = $cp.Paragraph
if (-not $para) { return }
$caretRng = New-Object System.Windows.Documents.TextRange $para.ContentStart, $cp
$textBefore = $caretRng.Text
$lastIdx = $textBefore.LastIndexOf($marker)
if ($lastIdx -lt 0) { return }
$between = $textBefore.Substring($lastIdx + 1)
if ($between.Length -eq 0 -or $between.Trim() -eq '') { return }
if ($marker -eq '/') {
if ($between -match '[\s/]') { return }
if ($lastIdx -gt 0) {
$prev = $textBefore[$lastIdx - 1]
if ($prev -match '[a-zA-Z0-9:.]') { return }
}
}
$tpOpen = Find-CharPointer $para.ContentStart $lastIdx
$tpAfterOpen = Find-CharPointer $para.ContentStart ($lastIdx + 1)
if (-not $tpOpen -or -not $tpAfterOpen) { return }
$e.Handled = $true
$openRng = New-Object System.Windows.Documents.TextRange $tpOpen, $tpAfterOpen
$openRng.Text = ''
$newCp = $s.CaretPosition
$innerRng = New-Object System.Windows.Documents.TextRange $tpOpen, $newCp
if ($marker -eq '!') {
$innerRng.ApplyPropertyValue([System.Windows.Documents.TextElement]::FontWeightProperty, [System.Windows.FontWeights]::Bold)
$s.Selection.Select($newCp, $newCp)
$s.Selection.ApplyPropertyValue([System.Windows.Documents.TextElement]::FontWeightProperty, [System.Windows.FontWeights]::Normal)
} else {
$deco = New-Object System.Windows.TextDecorationCollection
$deco.Add([System.Windows.TextDecorations]::Strikethrough[0])
$innerRng.ApplyPropertyValue([System.Windows.Documents.Inline]::TextDecorationsProperty, $deco)
$s.Selection.Select($newCp, $newCp)
$s.Selection.ApplyPropertyValue([System.Windows.Documents.Inline]::TextDecorationsProperty, $null)
}
})
# Click em ☐/☑ alterna o estado
$rtb.Add_PreviewMouseLeftButtonUp({
param($s, $e)
$pt = $e.GetPosition($s)
$tp = $s.GetPositionFromPoint($pt, $true)
if (-not $tp) { return }
foreach ($dir in @([System.Windows.Documents.LogicalDirection]::Forward, [System.Windows.Documents.LogicalDirection]::Backward)) {
$other = $tp.GetPositionAtOffset(1, $dir)
if (-not $other) { continue }
$r = if ($dir -eq [System.Windows.Documents.LogicalDirection]::Forward) {
New-Object System.Windows.Documents.TextRange $tp, $other
} else {
$back = $tp.GetPositionAtOffset(-1, [System.Windows.Documents.LogicalDirection]::Backward)
if (-not $back) { continue }
New-Object System.Windows.Documents.TextRange $back, $tp
}
$ch = $r.Text
if ($ch -eq [char]0x2610) { $r.Text = [string][char]0x2611; $e.Handled = $true; return }
if ($ch -eq [char]0x2611) { $r.Text = [string][char]0x2610; $e.Handled = $true; return }
}
})
}
function Save-AllNotes {
if ($script:Saving) { return }
$script:Saving = $true
try {
$list = @()
foreach ($id in @($script:NotesList.Keys)) {
$entry = $script:NotesList[$id]
if ($null -eq $entry -or $null -eq $entry.Window) { continue }
$w = $entry.Window
$list += [PSCustomObject]@{
id = $id
title = $entry.TitleBox.Text
text = (Get-NoteXamlContent $entry.RichTextBox)
left = [double]$w.Left
top = [double]$w.Top
width = [double]$w.Width
height = [double]$w.Height
color = $entry.Color
}
}
$json = $list | ConvertTo-Json -Depth 4
if ($null -eq $json) { $json = '[]' }
# Garante array mesmo com 1 nota
if ($list.Count -eq 1) { $json = "[$json]" }
if ($list.Count -eq 0) { $json = '[]' }
Set-Content -Path $NotesFile -Value $json -Encoding utf8 -Force
} finally {
$script:Saving = $false
}
}
function Load-Notes {
if (-not (Test-Path $NotesFile)) { return @() }
try {
$raw = Get-Content $NotesFile -Raw -Encoding utf8
if ([string]::IsNullOrWhiteSpace($raw)) { return @() }
$parsed = $raw | ConvertFrom-Json
if ($null -eq $parsed) { return @() }
if ($parsed -is [array]) { return $parsed }
return @($parsed)
} catch {
return @()
}
}
[xml]$NoteXaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Desktop Note"
WindowStyle="None" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False"
AllowsTransparency="True" Background="Transparent"
Width="260" Height="240" MinWidth="160" MinHeight="120" Topmost="False">
<Border Name="OuterBorder" CornerRadius="6" BorderThickness="1" BorderBrush="#FFA8A29E" Background="#FFD6D3D1">
<Border.Effect>
<DropShadowEffect BlurRadius="14" ShadowDepth="2" Opacity="0.35"/>
</Border.Effect>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Name="Header" Grid.Row="0" Background="#FF44403C" CornerRadius="5,5,0,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Name="TitleBox" Grid.Column="0"
Text="Note"
Foreground="#FFE5E7EB" Background="Transparent" CaretBrush="#FFE5E7EB" SelectionBrush="#FF6B7280"
BorderThickness="0" Padding="6,0,2,0"
VerticalAlignment="Center" HorizontalAlignment="Left"
FontWeight="SemiBold" FontSize="12" FontFamily="Segoe UI"
MaxWidth="180" MinWidth="40"
AcceptsReturn="False" AcceptsTab="False"
Cursor="IBeam" ToolTip="Click para editar o titulo"/>
<Button Name="BtnColor" Grid.Column="1" Width="26" Height="26" Margin="0,2" Content="◐" Background="Transparent" BorderThickness="0" FontWeight="Bold" Foreground="#FFE5E7EB" Cursor="Hand" ToolTip="Trocar cor"/>
<Button Name="BtnAdd" Grid.Column="2" Width="26" Height="26" Margin="0,2" Content="+" Background="Transparent" BorderThickness="0" FontWeight="Bold" Foreground="#FFE5E7EB" FontSize="14" Cursor="Hand" ToolTip="Nova anotacao"/>
<Button Name="BtnClose" Grid.Column="3" Width="26" Height="26" Margin="0,2,4,0" Content="✕" Background="Transparent" BorderThickness="0" Foreground="#FFE5E7EB" FontWeight="Bold" Cursor="Hand" ToolTip="Apagar anotacao"/>
</Grid>
</Border>
<RichTextBox Name="RtbNote" Grid.Row="1" Background="Transparent" BorderThickness="0"
Padding="0" FontSize="14" FontFamily="Segoe UI" Foreground="#FF1F2937"
VerticalScrollBarVisibility="Auto" AcceptsReturn="True" AcceptsTab="True"
IsDocumentEnabled="True"/>
</Grid>
</Border>
</Window>
"@
$Colors = @(
@{ Bg = '#FFD6D3D1'; Header = '#FF44403C' }, # taupe / sepia (padrao - executive)
@{ Bg = '#FFE5E7EB'; Header = '#FF374151' }, # grafite claro
@{ Bg = '#FFD1D5DB'; Header = '#FF1F2937' }, # grafite medio
@{ Bg = '#FFCBD5E1'; Header = '#FF334155' }, # azul ardosia (slate)
@{ Bg = '#FFDBEAFE'; Header = '#FF1E3A8A' }, # azul corporativo
@{ Bg = '#FFE5E5E5'; Header = '#FF262626' } # carvao
)
function Find-ColorIndex([string]$bg) {
for ($i = 0; $i -lt $Colors.Count; $i++) {
if ($Colors[$i].Bg -eq $bg) { return $i }
}
return 0
}
function New-NoteWindow {
param(
[string]$Id = ([guid]::NewGuid().ToString()),
[string]$Text = '',
[string]$Title = 'Note',
$Left = $null,
$Top = $null,
$Width = $null,
$Height= $null,
[string]$Color = '#FFD6D3D1',
$CursorX = $null,
$CursorY = $null
)
$reader = New-Object System.Xml.XmlNodeReader $NoteXaml
$window = [Windows.Markup.XamlReader]::Load($reader)
if ($null -ne $Width) { $window.Width = [double]$Width }
if ($null -ne $Height) { $window.Height = [double]$Height }
$window.WindowStartupLocation = 'Manual'
if ($null -ne $Left -and $null -ne $Top) {
# Restaurando nota salva
$window.Left = [double]$Left
$window.Top = [double]$Top
} else {
# Nova nota - posicionar perto do cursor
if ($null -eq $CursorX -or $null -eq $CursorY) {
$cp = [System.Windows.Forms.Cursor]::Position
$CursorX = $cp.X
$CursorY = $cp.Y
}
# DPI scaling (Cursor.Position e screen sao em pixels fisicos;
# WPF Window.Left/Top sao em DIPs)
$dpiScale = 1.0
try {
$gtmp = [System.Drawing.Graphics]::FromHwnd([IntPtr]::Zero)
$dpiScale = [double]$gtmp.DpiX / 96.0
$gtmp.Dispose()
} catch {}
$defW = [double]$window.Width
$defH = [double]$window.Height
# Ancora a janela proximo ao cursor, com offset pequeno
$left = ($CursorX / $dpiScale) - 30
$top = ($CursorY / $dpiScale) - 15
# Clamp pro monitor onde o cursor esta
try {
$pt = New-Object System.Drawing.Point ([int]$CursorX, [int]$CursorY)
$screen = [System.Windows.Forms.Screen]::FromPoint($pt).WorkingArea
$sL = $screen.Left / $dpiScale
$sT = $screen.Top / $dpiScale
$sR = $screen.Right / $dpiScale
$sB = $screen.Bottom / $dpiScale
if ($left + $defW -gt $sR) { $left = $sR - $defW - 8 }
if ($top + $defH -gt $sB) { $top = $sB - $defH - 8 }
if ($left -lt $sL) { $left = $sL + 8 }
if ($top -lt $sT) { $top = $sT + 8 }
} catch {}
$window.Left = $left
$window.Top = $top
}
$outer = $window.FindName('OuterBorder')
$header = $window.FindName('Header')
$titleBox = $window.FindName('TitleBox')
$rtb = $window.FindName('RtbNote')
$btnClose = $window.FindName('BtnClose')
$btnAdd = $window.FindName('BtnAdd')
$btnColor = $window.FindName('BtnColor')
if ($Title) { $titleBox.Text = $Title } else { $titleBox.Text = 'Note' }
Set-NoteContent $rtb $Text
Add-MarkdownShortcuts $rtb
# aplicar cor
$idx = Find-ColorIndex $Color
$outer.Background = (New-Object System.Windows.Media.SolidColorBrush ([System.Windows.Media.ColorConverter]::ConvertFromString($Colors[$idx].Bg)))
$header.Background = (New-Object System.Windows.Media.SolidColorBrush ([System.Windows.Media.ColorConverter]::ConvertFromString($Colors[$idx].Header)))
$entry = [pscustomobject]@{
Window = $window
RichTextBox = $rtb
TitleBox = $titleBox
Color = $Colors[$idx].Bg
SaveTimer = $null
}
$script:NotesList[$Id] = $entry
$saveTimer = New-Object System.Windows.Threading.DispatcherTimer
$saveTimer.Interval = [TimeSpan]::FromMilliseconds(600)
$saveTimer.Tag = $Id
$saveTimer.Add_Tick({
param($sender, $e)
$sender.Stop()
Save-AllNotes
})
$entry.SaveTimer = $saveTimer
# arrastar pela header (mas nao quando clicar no TextBox de titulo
# ou nos botoes do header - DragMove() entra em loop de mensagens Win32 e
# ABSORVE o WM_LBUTTONUP, impedindo o evento Click dos botoes de disparar)
$header.Add_MouseLeftButtonDown({
param($s, $e)
if ($e.OriginalSource -is [System.Windows.Controls.TextBox]) { return }
if ($e.OriginalSource -is [System.Windows.Controls.Primitives.ButtonBase]) { return }
# Tambem cobre clicks no Content ou outros children dos botoes
$src = $e.OriginalSource
while ($src -and $src -isnot [System.Windows.Controls.Primitives.ButtonBase]) {
if ($src -isnot [System.Windows.DependencyObject]) { break }
$src = [System.Windows.Media.VisualTreeHelper]::GetParent($src)
}
if ($src -is [System.Windows.Controls.Primitives.ButtonBase]) { return }
try { $window.DragMove() } catch {}
}.GetNewClosure())
$rtb.Add_TextChanged({
$saveTimer.Stop(); $saveTimer.Start()
}.GetNewClosure())
$titleBox.Add_TextChanged({
$saveTimer.Stop(); $saveTimer.Start()
}.GetNewClosure())
$window.Add_LocationChanged({
$saveTimer.Stop(); $saveTimer.Start()
}.GetNewClosure())
$window.Add_SizeChanged({
$saveTimer.Stop(); $saveTimer.Start()
}.GetNewClosure())
# Captura explicita de variaveis (mais robusto que depender so do GetNewClosure
# com defaults dinamicos em PS 5.1)
$thisId = $Id
$thisWindow = $window
$thisEntry = $entry
$btnClose.Add_Click({
try { $thisEntry.SaveTimer.Stop() } catch {}
try {
if ($script:NotesList.ContainsKey($thisId)) { [void]$script:NotesList.Remove($thisId) }
} catch {}
try { $thisWindow.Close() } catch {}
try { Save-AllNotes } catch {}
}.GetNewClosure())
$btnAdd.Add_Click({
$w = New-NoteWindow
$w.Show()
Save-AllNotes
}.GetNewClosure())
$btnColor.Add_Click({
$cur = Find-ColorIndex $entry.Color
$next = ($cur + 1) % $Colors.Count
$entry.Color = $Colors[$next].Bg
$outer.Background = (New-Object System.Windows.Media.SolidColorBrush ([System.Windows.Media.ColorConverter]::ConvertFromString($Colors[$next].Bg)))
$header.Background = (New-Object System.Windows.Media.SolidColorBrush ([System.Windows.Media.ColorConverter]::ConvertFromString($Colors[$next].Header)))
Save-AllNotes
}.GetNewClosure())
return $window
}
# Carrega notas existentes
$saved = Load-Notes
foreach ($n in $saved) {
try {
$titleVal = $n.title
if (-not $titleVal) { $titleVal = 'Note' }
$w = New-NoteWindow -Id $n.id -Title $titleVal -Text $n.text -Left $n.left -Top $n.top -Width $n.width -Height $n.height -Color $n.color
$w.Show()
} catch {}
}
function Invoke-PendingTrigger {
if (-not (Test-Path $TriggerFile)) { return $false }
try {
$content = Get-Content $TriggerFile -Raw -ErrorAction SilentlyContinue
Remove-Item $TriggerFile -Force -ErrorAction SilentlyContinue
$cx = $null; $cy = $null
if ($content -and ($content -match '\|(\d+)\|(\d+)')) {
$cx = [int]$matches[1]
$cy = [int]$matches[2]
}
$w = New-NoteWindow -CursorX $cx -CursorY $cy
$w.Show()
$w.Activate()
Save-AllNotes
return $true
} catch { return $false }
}
# Consome trigger pendente do cold-start (gravado pelo -AddNote handler)
[void](Invoke-PendingTrigger)
# Compatibilidade: -InitialNote sem trigger ainda cria nota vazia
if ($InitialNote -and -not (Test-Path $TriggerFile)) {
if (-not ($script:NotesList.Count -gt 0 -and -not (Test-Path $TriggerFile))) {
# so cria se nao tiver criado nada antes
}
}
# Tray icon (System.Windows.Forms.NotifyIcon)
$tray = New-Object System.Windows.Forms.NotifyIcon
try {
$iconPath = "$env:SystemRoot\System32\imageres.dll"
$extracted = [System.Drawing.Icon]::ExtractAssociatedIcon("$env:SystemRoot\System32\notepad.exe")
if ($extracted) { $tray.Icon = $extracted } else { $tray.Icon = [System.Drawing.SystemIcons]::Information }
} catch {
$tray.Icon = [System.Drawing.SystemIcons]::Information
}
$tray.Text = 'Desktop Notes'
$tray.Visible = $true
$ctx = New-Object System.Windows.Forms.ContextMenuStrip
$miAdd = $ctx.Items.Add('Nova anotacao')
$miAdd.Add_Click({
$w = New-NoteWindow
$w.Show()
$w.Activate()
Save-AllNotes
})
$miShow = $ctx.Items.Add('Mostrar todas')
$miShow.Add_Click({
foreach ($id in $script:NotesList.Keys) {
$w = $script:NotesList[$id].Window
if ($w) { $w.Show(); $w.Activate() }
}
})
[void]$ctx.Items.Add('-')
$miExit = $ctx.Items.Add('Sair')
$miExit.Add_Click({
Save-AllNotes
$tray.Visible = $false
[System.Windows.Application]::Current.Shutdown()
})
$tray.ContextMenuStrip = $ctx
# Polling do trigger e shutdown files
$pollTimer = New-Object System.Windows.Threading.DispatcherTimer
$pollTimer.Interval = [TimeSpan]::FromMilliseconds(450)
$pollTimer.Add_Tick({
# shutdown
if (Test-Path $ShutdownFile) {
try { Remove-Item $ShutdownFile -Force -ErrorAction SilentlyContinue } catch {}
Save-AllNotes
$tray.Visible = $false
[System.Windows.Application]::Current.Shutdown()
return
}
# add note trigger
[void](Invoke-PendingTrigger)
})
$pollTimer.Start()
# Salvar e sair em logoff/shutdown
[Microsoft.Win32.SystemEvents]::add_SessionEnding({
Save-AllNotes
[System.Windows.Application]::Current.Shutdown()
})
# Captura unhandled exceptions do dispatcher: loga em arquivo e marca handled
# pra nao matar o app (importante: sem isso, qualquer bug em handler de
# evento derrubaria o app inteiro - resultando em "fechar uma fecha todas").
$script:App.add_DispatcherUnhandledException({
param($s, $e)
try {
$errLog = Join-Path $NotesDir 'error.log'
$line = "[$(Get-Date -f 'yyyy-MM-dd HH:mm:ss.fff')] $($e.Exception.GetType().FullName): $($e.Exception.Message)`r`n$($e.Exception.StackTrace)`r`n"
[System.IO.File]::AppendAllText($errLog, $line)
} catch {}
$e.Handled = $true
})
[void]$script:App.Run()
try { $tray.Visible = $false; $tray.Dispose() } catch {}
try { $mutex.ReleaseMutex() } catch {}
try { $mutex.Dispose() } catch {}