Repository navigation
Expand file tree
/
Copy pathTaskbarWidget.xaml.cs
More file actions
948 lines (802 loc) · 34 KB
/
Copy pathTaskbarWidget.xaml.cs
File metadata and controls
948 lines (802 loc) · 34 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
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Windows.ApplicationModel.DataTransfer;
using WinRT.Interop;
namespace NoteUI;
public sealed partial class TaskbarWidget : Window
{
private readonly ClipboardHistoryManager _clipboardHistory;
private readonly SnippetManager _snippetManager;
private readonly NotesManager? _notesManager;
private IntPtr _hWnd;
private IntPtr _taskbarHandle;
private IntPtr _trayHandle;
private DispatcherTimer? _positionTimer;
private IntPtr _activeHwndBeforeFlyout;
private IDisposable? _acrylicController;
private SystemBackdropConfiguration? _configSource;
private Dictionary<string, bool> _modules;
private const int WindowHeight = 30;
private const int RightPadding = 6;
private const int FallbackRightPadding = 140;
// Win32 constants
private const int GWL_STYLE = -16;
private const int GWL_EXSTYLE = -20;
private const long WS_CAPTION = 0x00C00000;
private const long WS_THICKFRAME = 0x00040000;
private const long WS_EX_TOOLWINDOW = 0x00000080;
private const long WS_EX_NOACTIVATE = 0x08000000;
private const long WS_EX_TRANSPARENT = 0x00000020;
private const int DWMWA_WINDOW_CORNER_PREFERENCE = 33;
private const int DWMWCP_DONOTROUND = 1;
private static readonly IntPtr HWND_TOPMOST = new(-1);
private const uint SWP_NOACTIVATE = 0x0010;
private const uint SWP_SHOWWINDOW = 0x0040;
private const uint SWP_HIDEWINDOW = 0x0080;
private const uint SWP_NOMOVE = 0x0002;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_FRAMECHANGED = 0x0020;
private const uint WM_WINDOWPOSCHANGING = 0x0046;
private const uint WM_ACTIVATE = 0x0006;
private const uint WM_NCACTIVATE = 0x0086;
private delegate IntPtr SubclassProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData);
// prevent GC of the delegate
private static SubclassProc? _subclassProc;
public TaskbarWidget(ClipboardHistoryManager clipboardHistory, SnippetManager snippetManager, NotesManager? notesManager = null)
{
this.InitializeComponent();
_clipboardHistory = clipboardHistory;
_snippetManager = snippetManager;
_notesManager = notesManager;
_modules = AppSettings.LoadWidgetModules();
BuildButtons();
_hWnd = WindowNative.GetWindowHandle(this);
// Transparent title bar
ExtendsContentIntoTitleBar = false;
var transparent = new Windows.UI.Color { A = 0, R = 0, G = 0, B = 0 };
AppWindow.TitleBar.BackgroundColor = transparent;
AppWindow.TitleBar.InactiveBackgroundColor = transparent;
AppWindow.TitleBar.ButtonBackgroundColor = transparent;
AppWindow.TitleBar.ButtonInactiveBackgroundColor = transparent;
// Presenter setup
var presenter = GetOverlappedPresenter();
presenter.SetBorderAndTitleBar(false, false);
presenter.IsResizable = false;
presenter.IsAlwaysOnTop = true;
// Win32 styling
RemoveWindowBorder();
DisableRoundedCorners();
SetWindowStyles();
// Subclass to keep TOPMOST and handle activation
_subclassProc = SubclassWndProc;
SetWindowSubclass(_hWnd, _subclassProc, IntPtr.Zero, IntPtr.Zero);
// Apply backdrop and theme
var backdrop = AppSettings.LoadSettings();
var theme = AppSettings.LoadThemeSetting();
AppSettings.ApplyToWindow(this, backdrop, ref _acrylicController, ref _configSource);
AppSettings.ApplyThemeToWindow(this, theme, _configSource);
// Right-click context menu
RootGrid.AddHandler(
UIElement.RightTappedEvent,
(RightTappedEventHandler)RootGrid_RightTapped,
handledEventsToo: true);
// Position timer - keep placement tight
_positionTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
_positionTimer.Tick += (_, _) => EnsureTaskbarPlacement();
_positionTimer.Start();
this.Closed += OnClosed;
DispatcherQueue.TryEnqueue(EnsureTaskbarPlacement);
}
// ── Dynamic button building ─────────────────────────────────
public void BuildButtons()
{
ButtonPanel.Children.Clear();
_modules = AppSettings.LoadWidgetModules();
var moduleDefinitions = new (string Key, string Glyph, Action<Button> OnClick)[]
{
("clipboard", "\uE16F", btn => { _activeHwndBeforeFlyout = GetForegroundWindow(); BuildClipboardFlyout().ShowAt(btn); }),
("notes", "\uE70B", btn => { BuildNotesFlyout().ShowAt(btn); }),
("favorites", "\uE734", btn => { BuildFavoritesFlyout().ShowAt(btn); }),
("folders", "\uE8B7", btn => { BuildFoldersFlyout().ShowAt(btn); }),
("snippets", "\uE943", btn => { _activeHwndBeforeFlyout = GetForegroundWindow(); BuildSnippetsFlyout().ShowAt(btn); }),
};
foreach (var (key, glyph, onClick) in moduleDefinitions)
{
if (!_modules.TryGetValue(key, out var enabled) || !enabled) continue;
var btn = new Button
{
Padding = new Thickness(4),
MinWidth = 28, MinHeight = 26, MaxWidth = 28, MaxHeight = 26,
Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent),
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(4),
Content = new FontIcon { Glyph = glyph, FontSize = 13 },
};
var capturedBtn = btn;
btn.Click += (_, _) => onClick(capturedBtn);
ButtonPanel.Children.Add(btn);
}
}
private int GetWidgetWidth() => Math.Max(28, 28 * ButtonPanel.Children.Count);
// ── Taskbar placement ────────────────────────────────────────
private void EnsureTaskbarPlacement()
{
if (_hWnd == IntPtr.Zero)
return;
var taskbarHandle = FindWindow("Shell_TrayWnd", null);
if (taskbarHandle == IntPtr.Zero)
return;
_taskbarHandle = taskbarHandle;
if (!GetWindowRect(_taskbarHandle, out var taskbarRect))
return;
var taskbarWidth = taskbarRect.Right - taskbarRect.Left;
var taskbarHeight = taskbarRect.Bottom - taskbarRect.Top;
if (taskbarWidth <= 0 || taskbarHeight <= 0)
return;
// Hide when a fullscreen app is active
if (IsFullscreenAppActive())
{
SetWindowPos(_hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW);
return;
}
var dpiScale = GetDpiForWindow(_taskbarHandle) / 96.0;
if (dpiScale <= 0)
dpiScale = 1.0;
var widthPx = Math.Max(24, (int)Math.Round(GetWidgetWidth() * dpiScale));
var heightPx = Math.Max(10, (int)Math.Round(WindowHeight * dpiScale));
try
{
AppWindow.Resize(new Windows.Graphics.SizeInt32(widthPx, heightPx));
}
catch
{
}
var left = ComputeLeftOffset(taskbarRect, taskbarWidth, widthPx);
var top = Math.Max(0, (taskbarHeight - heightPx) / 2);
SetWindowPos(_hWnd, HWND_TOPMOST,
taskbarRect.Left + left, taskbarRect.Top + top,
widthPx, heightPx,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
private bool IsFullscreenAppActive()
{
var fgHwnd = GetForegroundWindow();
if (fgHwnd == IntPtr.Zero || fgHwnd == _hWnd) return false;
// Ignore the desktop window (clicking the desktop should not hide the widget)
if (fgHwnd == GetShellWindow()) return false;
var className = new System.Text.StringBuilder(256);
GetClassName(fgHwnd, className, className.Capacity);
var cls = className.ToString();
if (cls is "Progman" or "WorkerW") return false;
if (!GetWindowRect(fgHwnd, out var wndRect)) return false;
// Get the monitor that contains the foreground window
var monitor = MonitorFromWindow(fgHwnd, MONITOR_DEFAULTTONEAREST);
var monitorInfo = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
if (!GetMonitorInfo(monitor, ref monitorInfo)) return false;
// Fullscreen = window covers the entire monitor
var screen = monitorInfo.rcMonitor;
return wndRect.Left <= screen.Left && wndRect.Top <= screen.Top
&& wndRect.Right >= screen.Right && wndRect.Bottom >= screen.Bottom;
}
private int ComputeLeftOffset(RECT taskbarRect, int taskbarWidth, int widthPx)
{
if (_trayHandle == IntPtr.Zero)
_trayHandle = FindWindowEx(_taskbarHandle, IntPtr.Zero, "TrayNotifyWnd", null);
if (_trayHandle != IntPtr.Zero && GetWindowRect(_trayHandle, out var trayRect))
{
var trayRelativeLeft = trayRect.Left - taskbarRect.Left;
var candidate = trayRelativeLeft - widthPx - RightPadding;
return Math.Clamp(candidate, 0, Math.Max(0, taskbarWidth - widthPx));
}
return Math.Max(0, taskbarWidth - widthPx - FallbackRightPadding);
}
// ── Subclass proc ────────────────────────────────────────────
private IntPtr SubclassWndProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam, IntPtr uIdSubclass, IntPtr dwRefData)
{
if (uMsg == WM_WINDOWPOSCHANGING)
{
var wp = Marshal.PtrToStructure<WINDOWPOS>(lParam);
wp.hwndInsertAfter = HWND_TOPMOST;
wp.flags &= ~SWP_NOZORDER;
Marshal.StructureToPtr(wp, lParam, false);
}
// Keep backdrop active even when shell focus changes.
if (uMsg == WM_ACTIVATE && (wParam.ToInt64() & 0xFFFF) == 0)
return DefSubclassProc(hWnd, uMsg, (IntPtr)1, lParam);
if (uMsg == WM_NCACTIVATE)
return DefSubclassProc(hWnd, uMsg, (IntPtr)1, lParam);
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
// ── Win32 helpers ────────────────────────────────────────────
private OverlappedPresenter GetOverlappedPresenter()
{
if (AppWindow.Presenter is OverlappedPresenter existing)
return existing;
var presenter = OverlappedPresenter.Create();
AppWindow.SetPresenter(presenter);
return presenter;
}
private void RemoveWindowBorder()
{
var style = (long)GetWindowLongPtr(_hWnd, GWL_STYLE);
style &= ~(WS_CAPTION | WS_THICKFRAME);
SetWindowLongPtr(_hWnd, GWL_STYLE, (IntPtr)style);
SetWindowPos(_hWnd, IntPtr.Zero, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
}
private void DisableRoundedCorners()
{
int preference = DWMWCP_DONOTROUND;
DwmSetWindowAttribute(_hWnd, DWMWA_WINDOW_CORNER_PREFERENCE,
ref preference, sizeof(int));
}
private void SetWindowStyles()
{
var exStyle = (long)GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exStyle |= WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE;
exStyle &= ~WS_EX_TRANSPARENT;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, (IntPtr)exStyle);
}
// ── Clipboard flyout ─────────────────────────────────────────
public event Action<string>? OpenNoteRequested;
private Flyout BuildClipboardFlyout()
{
var flyout = new Flyout { ShouldConstrainToRootBounds = false };
flyout.FlyoutPresenterStyle = ActionPanel.CreateFlyoutPresenterStyle(260, 340);
var panel = new StackPanel { Spacing = 0 };
// Header
panel.Children.Add(new TextBlock
{
Text = Lang.T("clipboard_history"),
FontSize = 12,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 8, 10, 4),
Opacity = 0.6
});
panel.Children.Add(CreateDivider());
var entries = _clipboardHistory.GetSorted();
if (entries.Count == 0)
{
panel.Children.Add(new TextBlock
{
Text = Lang.T("no_clipboard_entries"),
FontSize = 12,
Opacity = 0.4,
Padding = new Thickness(10, 8, 10, 8)
});
}
else
{
var count = Math.Min(entries.Count, 20);
for (var i = 0; i < count; i++)
{
var entry = entries[i];
if (entry.ContentType == "image" && entry.ImageData != null)
{
var imgEntry = entry;
var imgCard = CreateImageFlyoutItem(imgEntry);
imgCard.Tapped += (_, _) =>
{
flyout.Hide();
PasteToActiveWindow(() => CopyEntryToClipboard(imgEntry));
};
panel.Children.Add(imgCard);
}
else
{
var preview = entry.TextContent?.Length > 50
? entry.TextContent[..50].Replace("\n", " ") + "..."
: entry.TextContent?.Replace("\n", " ") ?? "";
var btn = CreateFlyoutButton(preview);
btn.Click += (_, _) =>
{
flyout.Hide();
PasteToActiveWindow(() => CopyEntryToClipboard(entry));
};
panel.Children.Add(btn);
}
}
}
// Clear all
panel.Children.Add(CreateDivider());
var clearBtn = CreateFlyoutButton(Lang.T("clipboard_clear_all"), "\uE74D", isDestructive: true);
clearBtn.Click += (_, _) =>
{
_clipboardHistory.Clear();
flyout.Hide();
};
panel.Children.Add(clearBtn);
var scrollViewer = new ScrollViewer
{
Content = panel,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
MaxHeight = 400
};
flyout.Content = scrollViewer;
return flyout;
}
// ── Favorites flyout ─────────────────────────────────────────
private Flyout BuildFavoritesFlyout()
{
var flyout = new Flyout { ShouldConstrainToRootBounds = false };
flyout.FlyoutPresenterStyle = ActionPanel.CreateFlyoutPresenterStyle(260, 340);
var panel = new StackPanel { Spacing = 0 };
panel.Children.Add(new TextBlock
{
Text = Lang.T("favorites"),
FontSize = 12,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 8, 10, 4),
Opacity = 0.6
});
panel.Children.Add(CreateDivider());
var favorites = _notesManager?.Notes
.Where(n => n.IsFavorite && !n.IsArchived)
.OrderByDescending(n => n.UpdatedAt)
.ToList() ?? [];
if (favorites.Count == 0)
{
panel.Children.Add(new TextBlock
{
Text = Lang.T("no_favorites"),
FontSize = 12,
Opacity = 0.4,
Padding = new Thickness(10, 8, 10, 8)
});
}
else
{
foreach (var note in favorites)
{
var noteId = note.Id;
var title = string.IsNullOrWhiteSpace(note.Title) ? Lang.T("untitled") : note.Title;
var btn = CreateFlyoutButton(title, "\uE734");
btn.Click += (_, _) =>
{
flyout.Hide();
OpenNoteRequested?.Invoke(noteId);
};
panel.Children.Add(btn);
}
}
var scrollViewer = new ScrollViewer
{
Content = panel,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
MaxHeight = 400
};
flyout.Content = scrollViewer;
return flyout;
}
// ── Notes flyout ─────────────────────────────────────────────
private Flyout BuildNotesFlyout()
{
var flyout = new Flyout { ShouldConstrainToRootBounds = false };
flyout.FlyoutPresenterStyle = ActionPanel.CreateFlyoutPresenterStyle(260, 340);
var panel = new StackPanel { Spacing = 0 };
panel.Children.Add(new TextBlock
{
Text = Lang.T("notes"),
FontSize = 12,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 8, 10, 4),
Opacity = 0.6
});
panel.Children.Add(CreateDivider());
var recentNotes = _notesManager?.Notes
.Where(n => !n.IsArchived)
.OrderByDescending(n => n.UpdatedAt)
.Take(15)
.ToList() ?? [];
if (recentNotes.Count == 0)
{
panel.Children.Add(new TextBlock
{
Text = Lang.T("no_notes_found"),
FontSize = 12,
Opacity = 0.4,
Padding = new Thickness(10, 8, 10, 8)
});
}
else
{
foreach (var note in recentNotes)
{
var noteId = note.Id;
var title = string.IsNullOrWhiteSpace(note.Title) ? Lang.T("untitled") : note.Title;
var btn = CreateFlyoutButton(title, "\uE70B");
btn.Click += (_, _) =>
{
flyout.Hide();
OpenNoteRequested?.Invoke(noteId);
};
panel.Children.Add(btn);
}
}
var scrollViewer = new ScrollViewer
{
Content = panel,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
MaxHeight = 400
};
flyout.Content = scrollViewer;
return flyout;
}
// ── Folders flyout ───────────────────────────────────────────
private Flyout BuildFoldersFlyout()
{
var flyout = new Flyout { ShouldConstrainToRootBounds = false };
flyout.FlyoutPresenterStyle = ActionPanel.CreateFlyoutPresenterStyle(260, 340);
var panel = new StackPanel { Spacing = 0 };
panel.Children.Add(new TextBlock
{
Text = Lang.T("folders"),
FontSize = 12,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 8, 10, 4),
Opacity = 0.6
});
panel.Children.Add(CreateDivider());
var folders = _notesManager?.GetAllFolders() ?? [];
if (folders.Count == 0)
{
panel.Children.Add(new TextBlock
{
Text = Lang.T("no_folders"),
FontSize = 12,
Opacity = 0.4,
Padding = new Thickness(10, 8, 10, 8)
});
}
else
{
foreach (var folder in folders)
{
// Folder header
panel.Children.Add(new TextBlock
{
Text = folder,
FontSize = 11,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 6, 10, 2),
Opacity = 0.5
});
var notesInFolder = _notesManager?.Notes
.Where(n => !n.IsArchived && string.Equals(n.Folder, folder, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(n => n.UpdatedAt)
.ToList() ?? [];
if (notesInFolder.Count == 0)
{
panel.Children.Add(new TextBlock
{
Text = Lang.T("no_notes_folder", folder),
FontSize = 12,
Opacity = 0.4,
Padding = new Thickness(18, 4, 10, 4)
});
}
else
{
foreach (var note in notesInFolder)
{
var noteId = note.Id;
var title = string.IsNullOrWhiteSpace(note.Title) ? Lang.T("untitled") : note.Title;
var btn = CreateFlyoutButton(title, "\uE70B");
btn.Padding = new Thickness(18, 6, 10, 6);
btn.Click += (_, _) =>
{
flyout.Hide();
OpenNoteRequested?.Invoke(noteId);
};
panel.Children.Add(btn);
}
}
}
}
var scrollViewer = new ScrollViewer
{
Content = panel,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
MaxHeight = 400
};
flyout.Content = scrollViewer;
return flyout;
}
// ── Snippets flyout ──────────────────────────────────────────
private Flyout BuildSnippetsFlyout()
{
var flyout = new Flyout { ShouldConstrainToRootBounds = false };
flyout.FlyoutPresenterStyle = ActionPanel.CreateFlyoutPresenterStyle(260, 340);
var panel = new StackPanel { Spacing = 0 };
panel.Children.Add(new TextBlock
{
Text = Lang.T("snippet"),
FontSize = 12,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 8, 10, 4),
Opacity = 0.6
});
panel.Children.Add(CreateDivider());
var categories = _snippetManager.GetAllCategories();
if (categories.Count == 0 && _snippetManager.Snippets.Count == 0)
{
panel.Children.Add(new TextBlock
{
Text = Lang.T("no_snippets"),
FontSize = 12,
Opacity = 0.4,
Padding = new Thickness(10, 8, 10, 8)
});
}
else
{
// Snippets with categories
foreach (var category in categories)
{
panel.Children.Add(new TextBlock
{
Text = category,
FontSize = 11,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
Padding = new Thickness(10, 6, 10, 2),
Opacity = 0.5
});
var snippetsInCat = _snippetManager.Snippets
.Where(s => string.Equals(s.Category, category, StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var snippet in snippetsInCat)
{
var s = snippet;
var label = $"{s.Keyword}: {(s.Content.Length > 40 ? s.Content[..40] + "..." : s.Content)}";
var btn = CreateFlyoutButton(label, "\uE943");
btn.Click += (_, _) =>
{
flyout.Hide();
PasteToActiveWindow(() =>
{
var dp = new DataPackage();
dp.SetText(s.Content);
Clipboard.SetContent(dp);
});
};
panel.Children.Add(btn);
}
}
// Snippets without categories
var uncategorized = _snippetManager.Snippets
.Where(s => string.IsNullOrEmpty(s.Category))
.ToList();
if (uncategorized.Count > 0)
{
foreach (var snippet in uncategorized)
{
var s = snippet;
var label = $"{s.Keyword}: {(s.Content.Length > 40 ? s.Content[..40] + "..." : s.Content)}";
var btn = CreateFlyoutButton(label, "\uE943");
btn.Click += (_, _) =>
{
flyout.Hide();
PasteToActiveWindow(() =>
{
var dp = new DataPackage();
dp.SetText(s.Content);
Clipboard.SetContent(dp);
});
};
panel.Children.Add(btn);
}
}
}
var scrollViewer = new ScrollViewer
{
Content = panel,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
MaxHeight = 400
};
flyout.Content = scrollViewer;
return flyout;
}
// ── Right-click context menu ─────────────────────────────────
private void RootGrid_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
var actions = new List<ActionPanel.ActionItem>
{
new("\uE711", Lang.T("close"), [], () => Close(), IsDestructive: true)
};
var flyout = ActionPanel.Create(Lang.T("widget"), actions);
flyout.ShouldConstrainToRootBounds = false;
flyout.ShowAt(RootGrid);
e.Handled = true;
}
// ── UI helpers ───────────────────────────────────────────────
private static Button CreateFlyoutButton(string label, string? glyph = null, bool isDestructive = false)
{
var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
if (glyph != null)
sp.Children.Add(new FontIcon { Glyph = glyph, FontSize = 12 });
sp.Children.Add(new TextBlock
{
Text = label,
FontSize = 12,
TextTrimming = TextTrimming.CharacterEllipsis,
MaxWidth = 280
});
var btn = new Button
{
Content = sp,
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent),
BorderThickness = new Thickness(0),
Padding = new Thickness(10, 6, 10, 6),
CornerRadius = new CornerRadius(4),
MinHeight = 0,
};
if (isDestructive)
btn.Foreground = new SolidColorBrush(Microsoft.UI.Colors.IndianRed);
return btn;
}
private static Border CreateImageFlyoutItem(ClipboardHistoryEntry entry)
{
var img = new Image
{
MaxHeight = 48,
MaxWidth = 200,
Stretch = Stretch.Uniform,
HorizontalAlignment = HorizontalAlignment.Left,
};
// Load thumbnail from byte array
_ = LoadImageFromBytes(img, entry.ImageData!);
var border = new Border
{
Child = img,
Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent),
Padding = new Thickness(10, 4, 10, 4),
CornerRadius = new CornerRadius(4),
HorizontalAlignment = HorizontalAlignment.Stretch,
CanDrag = true,
};
border.DragStarting += async (s, args) =>
{
args.AllowedOperations = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
var tempPath = Path.Combine(Path.GetTempPath(), $"NoteUI_clip_{entry.Id[..8]}.png");
await File.WriteAllBytesAsync(tempPath, entry.ImageData!);
var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(tempPath);
args.Data.SetStorageItems(new[] { file });
};
return border;
}
private static async Task LoadImageFromBytes(Image img, byte[] data)
{
try
{
var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
await stream.WriteAsync(data.AsBuffer());
stream.Seek(0);
var bmp = new Microsoft.UI.Xaml.Media.Imaging.BitmapImage();
await bmp.SetSourceAsync(stream);
img.Source = bmp;
}
catch { }
}
private static Border CreateDivider()
{
return new Border
{
Height = 1,
Background = (Brush)Application.Current.Resources["DividerStrokeColorDefaultBrush"],
Margin = new Thickness(6, 2, 6, 2)
};
}
private void PasteToActiveWindow(Action copyAction)
{
var targetHwnd = _activeHwndBeforeFlyout;
copyAction();
Task.Delay(100).ContinueWith(_ =>
{
SetForegroundWindow(targetHwnd);
const byte VK_CONTROL = 0x11;
const byte VK_V = 0x56;
const uint KEYEVENTF_KEYUP = 0x02;
keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero);
keybd_event(VK_V, 0, 0, UIntPtr.Zero);
keybd_event(VK_V, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
});
}
private static void CopyEntryToClipboard(ClipboardHistoryEntry entry)
{
var dp = new DataPackage();
if (entry.ContentType == "image" && entry.ImageData != null)
{
var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
stream.WriteAsync(entry.ImageData.AsBuffer()).AsTask().Wait();
stream.Seek(0);
dp.SetBitmap(Windows.Storage.Streams.RandomAccessStreamReference.CreateFromStream(stream));
}
else
{
if (entry.RtfContent != null) dp.SetRtf(entry.RtfContent);
if (entry.TextContent != null) dp.SetText(entry.TextContent);
}
Clipboard.SetContent(dp);
}
// ── Cleanup ──────────────────────────────────────────────────
private void OnClosed(object sender, WindowEventArgs e)
{
_positionTimer?.Stop();
_acrylicController?.Dispose();
if (_subclassProc != null)
RemoveWindowSubclass(_hWnd, _subclassProc, IntPtr.Zero);
}
// ── P/Invoke ─────────────────────────────────────────────────
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string? lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string? className, string? windowTitle);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetDpiForWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("comctl32.dll")]
private static extern bool SetWindowSubclass(IntPtr hWnd, SubclassProc pfnSubclass, IntPtr uIdSubclass, IntPtr dwRefData);
[DllImport("comctl32.dll")]
private static extern bool RemoveWindowSubclass(IntPtr hWnd, SubclassProc pfnSubclass, IntPtr uIdSubclass);
[DllImport("comctl32.dll")]
private static extern IntPtr DefSubclassProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attribute,
ref int pvAttribute, int cbAttribute);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern IntPtr GetShellWindow();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);
private const uint MONITOR_DEFAULTTONEAREST = 2;
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
private struct MONITORINFO
{
public int cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
[StructLayout(LayoutKind.Sequential)]
private struct WINDOWPOS
{
public IntPtr hwnd;
public IntPtr hwndInsertAfter;
public int x;
public int y;
public int cx;
public int cy;
public uint flags;
}
}