-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesPanelWindow.xaml.cs
More file actions
1253 lines (1049 loc) · 47.5 KB
/
Copy pathNotesPanelWindow.xaml.cs
File metadata and controls
1253 lines (1049 loc) · 47.5 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
using NoteIt.Models;
using NoteIt.Native;
using NoteIt.Services;
using NoteIt.UI;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Animation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.Graphics;
using WinRT.Interop;
namespace NoteIt;
/// <summary>
/// The sliding panel. Positioning/animation are ported from WorldClockTray's
/// ClockPanel (by way of the ClipboardTray app this project itself was
/// adapted from): the panel docks against whichever screen edge the anchor
/// point (tray icon click / cursor) is actually closest to, instead of
/// always assuming the taskbar is at the bottom. Both the window itself
/// (native SetWindowPos+DwmFlush tween, see WindowAnimator) and its content
/// (a separate XAML slide+fade, see TriggerContentAnimation) enter from that
/// same resolved edge.
///
/// Unlike a clipboard history panel, notes are user-authored and editable
/// in place: each row is a live TextBox rather than a read-only, click-to-
/// copy button, and nothing is ever silently trimmed off the bottom of the
/// list -- see OnNoteTextChanged and the absence of any Trim()/MaxItems
/// logic that a transient-capture history would have.
/// </summary>
public sealed partial class NotesPanelWindow : Window
{
private const double PanelWidthDip = 340;
// Height is no longer fixed: the panel grows to fit its content (down to
// this floor, so it never looks cramped when empty/near-empty) and up to
// this fraction of the current monitor's work area, beyond which it holds
// at that cap and the ListView's own built-in ScrollViewer takes over.
private const double MinPanelHeightDip = 220;
private const double MaxPanelHeightFraction = 0.75;
private const double ExtraFitHeightDip = 10;
private const double EdgeMarginDip = 10;
private const int SlideDurationMs = 280;
private const double ContentSlideOffsetDip = 14;
private const int ContentSlideDurationMs = 320;
private const int ContentFadeDurationMs = 150;
private const double ReopenDebounceSeconds = 0.25;
private const int HeightResizeDurationMs = 200;
// How long to wait after the last keystroke in a note before writing it
// to disk -- saving on every single character would mean a save-to-disk
// call per keypress while someone's mid-sentence. Coalesced the same way
// ScheduleWindowHeightUpdate coalesces a burst of layout changes, just on
// a longer, restartable timer instead of a one-shot dispatcher post.
private static readonly TimeSpan SaveDebounceDelay = TimeSpan.FromMilliseconds(600);
private DateTime _lastCloseTimeUtc = DateTime.MinValue;
public ObservableCollection<NoteItem> Items { get; } = new();
/// <summary>What PinnedList binds to: the subset of Items where
/// IsPinned is true, further narrowed by whatever the search box/
/// content filter currently restrict to. Kept in sync by ApplyFilter,
/// same as UnpinnedItems below -- splitting the old combined
/// FilteredItems into these two is what lets PinnedList sit in its own
/// sticky section (see the XAML) instead of scrolling away with the
/// rest of the notes, while still sharing all the same filter/search
/// logic.</summary>
public ObservableCollection<NoteItem> PinnedItems { get; } = new();
/// <summary>What HistoryList (the scrollable list) binds to: the
/// subset of Items where IsPinned is false, same filter/search
/// treatment as PinnedItems. Kept as separate collections, rather than
/// filtering Items in place, so pinning/persistence logic elsewhere
/// never has to know or care that a search is active -- TogglePin just
/// flips IsPinned and calls ApplyFilter, which moves the note from one
/// collection to the other for free.</summary>
public ObservableCollection<NoteItem> UnpinnedItems { get; } = new();
public bool IsPanelVisible { get; private set; }
/// <summary>Panel-level pin (distinct from NoteItem.IsPinned, which
/// pins individual notes to the top of the list). While true:
/// MouseHookWatcher's click-away check skips SlideOut entirely, so the
/// panel can be left open on screen like a sticky-note board while you
/// work.</summary>
public bool IsPanelPinned { get; private set; }
public IntPtr Hwnd => _hwnd;
public Visibility EmptyStateVisibility(int pinnedCount, int unpinnedCount) =>
pinnedCount == 0 && unpinnedCount == 0 ? Visibility.Visible : Visibility.Collapsed;
public string EmptyStateText(int pinnedCount, int unpinnedCount, int itemCount) =>
itemCount == 0 ? "No notes yet -- click + to add one" : "No matching notes";
/// <summary>Bound to the divider Border between PinnedList and
/// HistoryList: visible only once there's actually a pinned note above
/// it AND something unpinned below to separate it from.</summary>
public Visibility PinnedDividerVisibility(int pinnedCount, int unpinnedCount) =>
pinnedCount > 0 && unpinnedCount > 0 ? Visibility.Visible : Visibility.Collapsed;
public ThemeMode Theme { get; private set; }
public CornerStyle CornerStyle { get; private set; }
public bool IsDarkMode { get; private set; }
/// <summary>Fires whenever the panel's *resolved* light/dark state
/// changes -- used by App to swap the tray icon between its white/black
/// monochrome variants so it stays visible against either taskbar.</summary>
public event Action<bool>? EffectiveThemeChanged;
private readonly SettingsStore _settingsStore;
private readonly NotesStore _notesStore;
private readonly AppWindow _appWindow;
private readonly IntPtr _hwnd;
private readonly double _scale;
private string _lastEffectiveEdge = "right";
private PointInt32 _lastAnchor;
private bool _sizingInProgress;
private bool _heightUpdateQueued;
private readonly TranslateTransform _contentTransform = new();
private Storyboard? _contentStoryboard;
private CancellationTokenSource? _animCts;
private CancellationTokenSource? _resizeAnimCts;
private bool _slideInProgress;
private static readonly TimeSpan ScrollBarHideDelay = TimeSpan.FromSeconds(2);
private ScrollBar? _historyScrollBar;
private DispatcherTimer? _scrollBarHideTimer;
private Storyboard? _scrollBarFadeStoryboard;
private const double ScrollToTopThreshold = 80;
private ScrollViewer? _historyScrollViewer;
private Storyboard? _scrollToTopFadeStoryboard;
private DispatcherTimer? _saveDebounceTimer;
/// <summary>Open "edit in window" editors, keyed by NoteItem.Id, so
/// clicking the button again for a note that's already open activates
/// the existing window instead of stacking a second one on top of it.
/// Entries are removed on Closed. See OnOpenEditorClicked.</summary>
private readonly Dictionary<string, NoteEditorWindow> _openEditors = new();
/// <summary>Open pop-out mini windows, keyed by NoteItem.Id -- same
/// reuse-if-already-open convention as _openEditors (see
/// OnPopOutClicked / UI/StickyPopoutWindow).</summary>
private readonly Dictionary<string, UI.StickyPopoutWindow> _openPopouts = new();
/// <summary>Advances by one every time a pop-out is created, purely to
/// stagger each new window's spawn position a little from the last so
/// popping out several notes in a row doesn't stack them in an
/// identical spot directly on top of one another.</summary>
private int _popoutCascadeCount;
/// <summary>Standing restriction applied on top of the search text --
/// never resets automatically, same as the search text, until the user
/// picks a different option from FilterButton's menu.</summary>
private enum ContentFilterMode { All, Pinned }
private ContentFilterMode _contentFilter = ContentFilterMode.All;
public NotesPanelWindow(SettingsStore settingsStore, NotesStore notesStore)
{
this.InitializeComponent();
Container.RenderTransform = _contentTransform;
Items.CollectionChanged += (_, _) => ApplyFilter();
PinnedItems.CollectionChanged += (_, _) => ScheduleWindowHeightUpdate();
UnpinnedItems.CollectionChanged += (_, _) => ScheduleWindowHeightUpdate();
_settingsStore = settingsStore;
_notesStore = notesStore;
Theme = settingsStore.LoadThemeMode();
CornerStyle = settingsStore.LoadCornerStyle();
_hwnd = WindowNative.GetWindowHandle(this);
var windowId = global::Microsoft.UI.Win32Interop.GetWindowIdFromWindow(_hwnd);
_appWindow = AppWindow.GetFromWindowId(windowId);
_scale = WindowEffects.ScaleFactor(_hwnd);
_lastAnchor = new PointInt32(_appWindow.Position.X, _appWindow.Position.Y);
var widthPx = (int)Math.Round(PanelWidthDip * _scale);
var heightPx = (int)Math.Round(MinPanelHeightDip * _scale);
_appWindow.Resize(new SizeInt32(widthPx, heightPx));
_appWindow.IsShownInSwitchers = false;
ExtendsContentIntoTitleBar = true;
_appWindow.TitleBar.PreferredHeightOption = TitleBarHeightOption.Collapsed;
_appWindow.TitleBar.ExtendsContentIntoTitleBar = true;
if (_appWindow.Presenter is OverlappedPresenter presenter)
{
presenter.IsResizable = false;
presenter.IsMaximizable = false;
presenter.IsMinimizable = false;
presenter.SetBorderAndTitleBar(true, true);
}
WindowEffects.HideFromTaskbar(_hwnd);
WindowEffects.ApplyShadow(_hwnd);
WindowEffects.ApplyCornerStyle(_hwnd, CornerStyle);
var isDark = ApplyThemeCore(Theme);
NoiseOverlay.RenderTransformOrigin = new Windows.Foundation.Point(0, 0);
NoiseOverlay.RenderTransform = new ScaleTransform { ScaleX = 1.0 / _scale, ScaleY = 1.0 / _scale };
WindowEffects.ApplyAcrylicBackdrop(this, isDark, thin: false);
WindowEffects.RegenerateNoise(NoiseOverlay, widthPx, heightPx);
// Warm-up: one real Show/Activate cycle, far off-screen, before the
// panel is ever meant to be visible -- see the ClipboardTray-era
// comment this was ported from for why WinUI3's virtualizing
// ListView needs this.
var warmUpPos = new PointInt32(_appWindow.Position.X - 30000, _appWindow.Position.Y - 30000);
_appWindow.Move(warmUpPos);
_appWindow.Show();
this.Activate();
Container.UpdateLayout();
_appWindow.Hide();
SystemThemeService.Changed += OnSystemThemeChanged;
_saveDebounceTimer = new DispatcherTimer { Interval = SaveDebounceDelay };
_saveDebounceTimer.Tick += (_, _) =>
{
_saveDebounceTimer!.Stop();
SaveNotes();
};
// Fire-and-forget: repopulates Items from disk once loaded.
_ = LoadNotesAsync();
}
/// <summary>Restores persisted notes from NotesStore.</summary>
private Task LoadNotesAsync()
{
foreach (var record in _notesStore.Load())
{
Items.Add(new NoteItem
{
Id = record.Id,
Text = record.Text,
CreatedAt = record.CreatedAt,
ModifiedAt = record.ModifiedAt,
IsPinned = record.IsPinned,
PaperColorKey = record.PaperColorKey,
});
}
return Task.CompletedTask;
}
/// <summary>Snapshots the current Items into NotesStore's manifest
/// format and saves it. Called (debounced) on every edit, and
/// immediately after every add/remove/pin/clear-all.</summary>
private void SaveNotes()
{
var records = Items.Select(item => new NotesStore.Record
{
Id = item.Id,
Text = item.Text,
CreatedAt = item.CreatedAt,
ModifiedAt = item.ModifiedAt,
IsPinned = item.IsPinned,
PaperColorKey = item.PaperColorKey,
}).ToList();
_notesStore.Save(records);
}
/// <summary>Restarts the debounce timer -- called on every keystroke in
/// a note. A burst of keystrokes collapses into one save, ~600ms after
/// the user stops typing.</summary>
private void ScheduleSave()
{
if (_saveDebounceTimer == null) return;
_saveDebounceTimer.Stop();
_saveDebounceTimer.Start();
}
private void OnSystemThemeChanged()
{
if (Theme != ThemeMode.System) return;
DispatcherQueue.TryEnqueue(() =>
{
ApplyTheme(Theme);
NotifyEditorsOfTheme();
});
}
public void ApplyAndPersistTheme(ThemeMode mode)
{
ApplyTheme(mode);
_settingsStore.SaveThemeMode(mode);
NotifyEditorsOfTheme();
}
public void ApplyAndPersistCornerStyle(CornerStyle style)
{
CornerStyle = style;
WindowEffects.ApplyCornerStyle(_hwnd, style);
_settingsStore.SaveCornerStyle(style);
NotifyEditorsOfTheme();
}
/// <summary>Re-themes every currently-open note editor window to match
/// the panel's own theme/corner style -- called any time either changes
/// live (Settings, or Windows' own Light/Dark switch under "System"),
/// so an editor left open doesn't visually diverge from the app around
/// it.</summary>
private void NotifyEditorsOfTheme()
{
foreach (var editor in _openEditors.Values)
editor.ApplyTheme(Theme, CornerStyle);
foreach (var popout in _openPopouts.Values)
popout.ApplyTheme(Theme, CornerStyle);
}
public void ApplyTheme(ThemeMode mode)
{
Theme = mode;
var isDark = ApplyThemeCore(mode);
WindowEffects.ApplyAcrylicBackdrop(this, isDark, thin: false);
}
private bool ApplyThemeCore(ThemeMode mode)
{
var effectiveMode = SystemThemeService.Resolve(mode, taskbarSurface: true);
var isDark = effectiveMode == ThemeMode.Dark;
if (Content is FrameworkElement root)
root.RequestedTheme = isDark ? ElementTheme.Dark : ElementTheme.Light;
WindowEffects.SetDarkMode(_hwnd, isDark);
IsDarkMode = isDark;
EffectiveThemeChanged?.Invoke(isDark);
return isDark;
}
/// <summary>Panel bounds in physical screen pixels, for the mouse hook's
/// click-away hit test.</summary>
public PixelRect CurrentScreenRectPx()
{
var pos = _appWindow.Position;
var size = _appWindow.Size;
return new PixelRect(pos.X, pos.Y, size.Width, size.Height);
}
// --- note mutation ---------------------------------------------------
/// <summary>Adds a fresh blank note just below the pinned block (so a
/// new note never pushes a pin down) and focuses it for immediate
/// typing. Called from the header's "+" button.</summary>
private void OnAddNoteClicked(object sender, RoutedEventArgs e) => AddNoteAndFocus();
private void AddNoteAndFocus()
{
var insertAt = Items.TakeWhile(i => i.IsPinned).Count();
var note = new NoteItem();
Items.Insert(insertAt, note);
SaveNotes();
// If a search/filter is currently hiding new (empty, unpinned)
// notes, clear it so the note the user is about to type into is
// actually visible -- otherwise it would be created invisibly.
if (_contentFilter != ContentFilterMode.All)
{
_contentFilter = ContentFilterMode.All;
FilterGlyph.ClearValue(Microsoft.UI.Xaml.Controls.FontIcon.ForegroundProperty);
}
if (!string.IsNullOrEmpty(SearchBox.Text))
SearchBox.Text = string.Empty;
else
ApplyFilter();
// Container realization for a just-inserted item happens on the
// next layout pass, so focusing has to wait a beat -- mirrors the
// ScheduleWindowHeightUpdate pattern elsewhere in this file.
DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () =>
{
// A freshly-added note is always unpinned (see the insertAt
// computation above), so it always lands in HistoryList, never
// PinnedList.
HistoryList.UpdateLayout();
if (HistoryList.ContainerFromItem(note) is ListViewItem container)
{
var textBox = FindDescendant<TextBox>(container);
textBox?.Focus(FocusState.Programmatic);
}
});
}
/// <summary>Pushes a note's TextBox content back into the model as the
/// user types, bumps ModifiedAt, and schedules both a persisted save
/// and a fit-to-content height recalc (a growing/shrinking note changes
/// the panel's natural height same as adding/removing a whole note
/// does).</summary>
private void OnNoteTextChanged(object sender, TextChangedEventArgs e)
{
if (sender is not TextBox { Tag: NoteItem item } textBox) return;
// Runs even when the guard below bails out early, since that guard
// only covers user-edit side effects (save/resize) -- a recycled
// container re-firing TextChanged for a *different* note (whose
// overflow state has nothing to do with the previous occupant's)
// still needs its indicator re-checked.
UpdateMoreIndicator(textBox);
if (item.Text == textBox.Text) return; // recycled container re-firing with the same text
item.Text = textBox.Text;
item.ModifiedAt = DateTime.Now;
ScheduleSave();
ScheduleWindowHeightUpdate();
// A note's pinned/all-notes membership never changes just from
// editing its text, but a search query might now include/exclude
// it.
if (!string.IsNullOrEmpty(SearchBox.Text))
ApplyFilter();
}
/// <summary>Shows the small chevron under a note's TextBox once its
/// content actually overflows the 10-line preview cap (the TextBox's
/// MaxHeight in the item template), by checking the TextBox's own
/// internal ScrollViewer -- the same technique OnNotesListLoaded uses
/// to reach HistoryList's ScrollViewer. Deferred to a low-priority
/// dispatcher pass because the ScrollViewer's extent isn't updated
/// until the layout pass after Text changes lands, same reasoning as
/// the focus-after-insert dispatch in OnAddNoteClicked.</summary>
private void UpdateMoreIndicator(TextBox textBox)
{
DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () =>
{
if (VisualTreeHelper.GetParent(textBox) is not FrameworkElement wrapper) return;
if (FindDescendant<FontIcon>(wrapper, f => f.Name == "MoreIndicator") is not { } indicator) return;
var scrollViewer = FindDescendant<ScrollViewer>(textBox);
indicator.Visibility = scrollViewer is { ScrollableHeight: > 0.5 }
? Visibility.Visible
: Visibility.Collapsed;
});
}
private void OnCopyNoteClicked(object sender, RoutedEventArgs e)
{
if (sender is not FrameworkElement { Tag: NoteItem item }) return;
var package = new DataPackage();
package.SetText(item.Text ?? string.Empty);
Clipboard.SetContent(package);
}
/// <summary>Opens (or, if one's already open for this note, just
/// activates) a full editor window for the note -- the panel's row
/// stays live underneath since both views edit the same NoteItem
/// instance. See UI/NoteEditorWindow.xaml.cs.</summary>
private void OnOpenEditorClicked(object sender, RoutedEventArgs e)
{
if (sender is not FrameworkElement { Tag: NoteItem item }) return;
if (_openEditors.TryGetValue(item.Id, out var existing))
{
existing.Activate();
return;
}
var editor = new NoteEditorWindow(item, Theme, CornerStyle, PersistNow);
_openEditors[item.Id] = editor;
editor.Closed += (_, _) => _openEditors.Remove(item.Id);
editor.Activate();
}
/// <summary>Opens (or, if one's already open for this note, just
/// activates) a small movable, always-on-top "sticky note" style
/// window for the note -- unlike OnOpenEditorClicked's full editor,
/// this is meant to be left floating on top of other apps while you
/// work elsewhere. Both windows edit the very same NoteItem instance,
/// same as the panel row and the full editor do, so all three views
/// (row, editor, pop-out) stay in sync live. See
/// UI/StickyPopoutWindow.</summary>
private void OnPopOutClicked(object sender, RoutedEventArgs e)
{
if (sender is not FrameworkElement { Tag: NoteItem item }) return;
if (_openPopouts.TryGetValue(item.Id, out var existing))
{
existing.Activate();
return;
}
// Spawns a little down-and-right of the panel itself, cascading
// further with each additional pop-out (wrapping every 6 so a long
// run of clicks doesn't walk the window off-screen).
var stepPx = (int)Math.Round(28 * _scale);
var basePx = (int)Math.Round(24 * _scale);
var step = stepPx * (_popoutCascadeCount % 6);
_popoutCascadeCount++;
var anchor = new PointInt32(_appWindow.Position.X + basePx + step, _appWindow.Position.Y + basePx + step);
var popout = new UI.StickyPopoutWindow(item, Theme, CornerStyle, anchor, PersistNow);
_openPopouts[item.Id] = popout;
popout.Closed += (_, _) => _openPopouts.Remove(item.Id);
popout.Activate();
}
/// <summary>Persist-now callback handed to editor windows: writes the
/// full current Items snapshot the same way every other mutation here
/// does (SaveNotes has no notion of "just one note"), so an editor
/// window's Save button/autosave shares the exact same write path as
/// the panel's own inline editing.</summary>
private void PersistNow() => SaveNotes();
// --- fit-to-content height -------------------------------------------------
private void ScheduleWindowHeightUpdate()
{
if (_heightUpdateQueued) return;
_heightUpdateQueued = true;
DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () =>
{
_heightUpdateQueued = false;
UpdateWindowHeight();
});
}
private void UpdateWindowHeight()
{
if (_sizingInProgress) return;
_sizingInProgress = true;
try
{
Container.UpdateLayout();
var availableSize = new Windows.Foundation.Size(PanelWidthDip, double.PositiveInfinity);
Container.Measure(availableSize);
var naturalHeightDip = Container.DesiredSize.Height;
var wa = WorkAreaPx(_lastAnchor);
var maxHeightDip = (wa.Height * MaxPanelHeightFraction) / _scale;
// +ExtraFitHeightDip: a small cushion on top of the exact fit,
// since the exact-fit height sometimes clips the last visible
// pixels of a row right at the panel edge.
var targetHeightDip = Math.Clamp(naturalHeightDip, MinPanelHeightDip, Math.Max(MinPanelHeightDip, maxHeightDip)) + ExtraFitHeightDip;
var newHeightPx = (int)Math.Round(targetHeightDip * _scale);
if (newHeightPx == _appWindow.Size.Height) return;
WindowEffects.RegenerateNoise(NoiseOverlay, _appWindow.Size.Width, newHeightPx);
if (IsPanelVisible && !_slideInProgress)
{
AnimateHeightTo(newHeightPx);
return;
}
_appWindow.Resize(new SizeInt32(_appWindow.Size.Width, newHeightPx));
if (IsPanelVisible)
_appWindow.Move(TargetPosPx(_lastAnchor));
}
finally
{
_sizingInProgress = false;
}
}
private void AnimateHeightTo(int newHeightPx)
{
_resizeAnimCts?.Cancel();
_resizeAnimCts = new CancellationTokenSource();
var currentPos = _appWindow.Position;
var currentSize = _appWindow.Size;
var targetPos = TargetPosPxForSize(_lastAnchor, currentSize.Width, newHeightPx);
WindowAnimator.ResizeAndMove(
_hwnd,
new RectInt32(currentPos.X, currentPos.Y, currentSize.Width, currentSize.Height),
new RectInt32(targetPos.X, targetPos.Y, currentSize.Width, newHeightPx),
HeightResizeDurationMs,
WindowAnimator.ExponentialEaseOut,
DispatcherQueue,
cancellationToken: _resizeAnimCts.Token);
}
// --- positioning ---------------------------------------------------------
private RectInt32 WorkAreaPx(PointInt32 anchor)
{
var area = DisplayArea.GetFromPoint(anchor, DisplayAreaFallback.Nearest);
return area.WorkArea;
}
private static string ResolveEdge(PointInt32 anchor, RectInt32 wa)
{
var left = anchor.X - wa.X;
var right = (wa.X + wa.Width) - anchor.X;
var top = anchor.Y - wa.Y;
var bottom = (wa.Y + wa.Height) - anchor.Y;
var min = Math.Min(Math.Min(left, right), Math.Min(top, bottom));
if (min == left) return "left";
if (min == right) return "right";
if (min == top) return "top";
return "bottom";
}
private PointInt32 TargetPosPx(PointInt32 anchor) =>
TargetPosPxForSize(anchor, _appWindow.Size.Width, _appWindow.Size.Height);
private PointInt32 TargetPosPxForSize(PointInt32 anchor, int width, int height)
{
var wa = WorkAreaPx(anchor);
var edge = ResolveEdge(anchor, wa);
_lastEffectiveEdge = edge;
var edgeMargin = (int)Math.Round(EdgeMarginDip * _scale);
var contentWidth = width;
var contentHeight = height;
int x, y;
if (edge is "left" or "right")
{
y = anchor.Y - contentHeight / 2;
y = Math.Max(wa.Y + edgeMargin, Math.Min(y, wa.Y + wa.Height - contentHeight - edgeMargin));
x = edge == "left" ? wa.X + edgeMargin : wa.X + wa.Width - contentWidth - edgeMargin;
}
else
{
x = anchor.X - contentWidth / 2;
x = Math.Max(wa.X + edgeMargin, Math.Min(x, wa.X + wa.Width - contentWidth - edgeMargin));
y = edge == "top" ? wa.Y + edgeMargin : wa.Y + wa.Height - contentHeight - edgeMargin;
}
return new PointInt32(x, y);
}
private PointInt32 HiddenPosPx(PointInt32 target)
{
var contentWidth = _appWindow.Size.Width;
var contentHeight = _appWindow.Size.Height;
var offset = (int)Math.Round(30 * _scale);
return _lastEffectiveEdge switch
{
"left" => new PointInt32(target.X - contentWidth - offset, target.Y),
"right" => new PointInt32(target.X + contentWidth + offset, target.Y),
"top" => new PointInt32(target.X, target.Y - contentHeight - offset),
_ => new PointInt32(target.X, target.Y + contentHeight + offset), // "bottom"
};
}
// --- show/hide with slide --------------------------------------------------
public void ShowNearPoint(int x, int y) => SlideIn(new PointInt32(x, y));
/// <summary>Used when a second .exe launch wakes the already-running
/// instance: if the panel is hidden, slide it in like a normal open;
/// if it's already open, just re-foreground it instead of re-running
/// the slide-in animation from the hidden position.</summary>
public void ShowOrForegroundNearPoint(int x, int y)
{
if (IsPanelVisible)
{
WindowEffects.ApplyTopmostBelowTaskbar(_hwnd);
this.Activate();
NativeMethods.SetForegroundWindow(_hwnd);
}
else
{
SlideIn(new PointInt32(x, y));
}
}
public void SlideIn(PointInt32 anchor)
{
_lastAnchor = anchor;
UpdateWindowHeight();
var target = TargetPosPx(anchor);
var hidden = HiddenPosPx(target);
PrepareContentEntrance();
_appWindow.Move(hidden);
_appWindow.Show();
WindowEffects.ApplyTopmostBelowTaskbar(_hwnd);
this.Activate();
NativeMethods.SetForegroundWindow(_hwnd);
SearchBox.Focus(FocusState.Programmatic);
AnimateTo(target, isOpening: true, onNearComplete: TriggerContentAnimation);
IsPanelVisible = true;
}
public void HidePanel() => SlideOut();
public void SlideOut()
{
// Reset the search on close, same as Windows 11's own flyouts do.
SearchBox.Text = string.Empty;
// Flush any pending debounced edit immediately -- the panel is
// about to disappear, so there's no "later" to save on.
if (_saveDebounceTimer?.IsEnabled == true)
{
_saveDebounceTimer.Stop();
SaveNotes();
}
StopContentStoryboard();
var current = new PointInt32(_appWindow.Position.X, _appWindow.Position.Y);
var hidden = HiddenPosPx(current);
AnimateTo(hidden, isOpening: false, onFinished: () => _appWindow.Hide());
IsPanelVisible = false;
_lastCloseTimeUtc = DateTime.UtcNow;
}
public void Toggle(PointInt32 anchor)
{
if (!IsPanelVisible && (DateTime.UtcNow - _lastCloseTimeUtc).TotalSeconds < ReopenDebounceSeconds)
return;
if (IsPanelVisible) SlideOut();
else SlideIn(anchor);
}
private void PrepareContentEntrance()
{
StopContentStoryboard();
var offset = ContentSlideOffsetDip * _scale;
double x = 0, y = 0;
switch (_lastEffectiveEdge)
{
case "left": x = -offset; break;
case "right": x = offset; break;
case "top": y = -offset; break;
default: y = offset; break; // "bottom"
}
_contentTransform.X = x;
_contentTransform.Y = y;
Container.Opacity = 0;
}
private void TriggerContentAnimation()
{
var axis = _lastEffectiveEdge is "left" or "right" ? "X" : "Y";
var from = axis == "X" ? _contentTransform.X : _contentTransform.Y;
var sb = new Storyboard();
var slideAnim = new DoubleAnimation
{
From = from,
To = 0,
Duration = new Duration(TimeSpan.FromMilliseconds(ContentSlideDurationMs)),
EasingFunction = new CircleEase { EasingMode = EasingMode.EaseOut }
};
Storyboard.SetTarget(slideAnim, _contentTransform);
Storyboard.SetTargetProperty(slideAnim, axis);
var fadeAnim = new DoubleAnimation
{
From = 0,
To = 1,
Duration = new Duration(TimeSpan.FromMilliseconds(ContentFadeDurationMs))
};
Storyboard.SetTarget(fadeAnim, Container);
Storyboard.SetTargetProperty(fadeAnim, "Opacity");
sb.Children.Add(slideAnim);
sb.Children.Add(fadeAnim);
_contentStoryboard = sb;
sb.Begin();
}
private void StopContentStoryboard()
{
if (_contentStoryboard != null)
{
try { _contentStoryboard.Stop(); } catch { /* best effort */ }
_contentStoryboard = null;
}
Container.Opacity = 1;
_contentTransform.X = 0;
_contentTransform.Y = 0;
}
private void AnimateTo(PointInt32 target, bool isOpening, Action? onFinished = null, Action? onNearComplete = null)
{
_animCts?.Cancel();
_animCts = new CancellationTokenSource();
_resizeAnimCts?.Cancel();
_slideInProgress = true;
var start = _appWindow.Position;
var easing = isOpening
? (Func<double, double>)WindowAnimator.ExponentialEaseOut
: WindowAnimator.CircularEaseIn;
WindowAnimator.Slide(
_hwnd, start, target, SlideDurationMs, easing, DispatcherQueue,
nearCompleteFraction: isOpening ? 0.1 : 0.0,
onNearComplete: onNearComplete,
onComplete: () =>
{
_slideInProgress = false;
onFinished?.Invoke();
},
cancellationToken: _animCts.Token);
}
private void OnSearchTextChanged(object sender, TextChangedEventArgs e) => ApplyFilter();
private void OnFilterFlyoutOpening(object sender, object e)
{
SetFilterChecked(FilterAllItem, _contentFilter == ContentFilterMode.All);
SetFilterChecked(FilterPinnedItem, _contentFilter == ContentFilterMode.Pinned);
}
private static void SetFilterChecked(MenuFlyoutItem item, bool isChecked) =>
item.Icon = isChecked ? new FontIcon { Glyph = "\uE73E", FontSize = 12 } : null;
private void OnFilterModeClicked(object sender, RoutedEventArgs e)
{
if (sender is not MenuFlyoutItem { Tag: string tag }) return;
_contentFilter = tag switch
{
"Pinned" => ContentFilterMode.Pinned,
_ => ContentFilterMode.All
};
if (_contentFilter == ContentFilterMode.All)
FilterGlyph.ClearValue(FontIcon.ForegroundProperty);
else if (Application.Current.Resources.TryGetValue("AccentTextFillColorPrimaryBrush", out var accentBrush))
FilterGlyph.Foreground = (Microsoft.UI.Xaml.Media.Brush)accentBrush;
ApplyFilter();
}
/// <summary>Recomputes PinnedItems and UnpinnedItems from Items + the
/// search box's current text + FilterButton's current restriction.
/// Matches are split by IsPinned and each half is synced into its own
/// collection (see SyncCollection) -- diffing against each collection's
/// existing contents rather than clearing and rebuilding, so neither
/// ListView flickers, drops scroll position, or -- crucially for an
/// editable list -- steals focus out of whichever note the user is
/// actively typing into, and a pin/unpin toggle reads as the row
/// cleanly leaving one list and landing in the other instead of both
/// lists doing a full refresh.</summary>
private void ApplyFilter()
{
var query = SearchBox.Text?.Trim() ?? string.Empty;
IEnumerable<NoteItem> matches = Items;
if (_contentFilter == ContentFilterMode.Pinned)
matches = matches.Where(item => item.IsPinned);
if (query.Length > 0)
{
matches = matches.Where(item =>
item.Text != null && item.Text.Contains(query, StringComparison.OrdinalIgnoreCase));
}
var matchList = matches.ToList();
// Items already keeps pinned notes contiguous at the top (see
// IsPinned/TogglePin/AddNoteAndFocus), so both halves come out of
// this split still in their existing relative order.
var pinnedTarget = matchList.Where(item => item.IsPinned).ToList();
var unpinnedTarget = matchList.Where(item => !item.IsPinned).ToList();
SyncCollection(PinnedItems, pinnedTarget);
SyncCollection(UnpinnedItems, unpinnedTarget);
}
/// <summary>Diffs collection against target -- moving/inserting/
/// removing individual entries -- instead of clearing and rebuilding it
/// outright, so the ListView bound to it doesn't flicker, lose scroll
/// position, or steal focus out from under an actively-edited note, and
/// only the entries that actually changed play an add/remove/move
/// animation. Shared by both PinnedItems and UnpinnedItems in
/// ApplyFilter above.</summary>
private static void SyncCollection(ObservableCollection<NoteItem> collection, List<NoteItem> target)
{
for (var i = collection.Count - 1; i >= 0; i--)
{
if (!target.Contains(collection[i]))
collection.RemoveAt(i);
}
for (var i = 0; i < target.Count; i++)
{
if (i < collection.Count && collection[i] == target[i])
continue;
var existingIndex = collection.IndexOf(target[i]);
if (existingIndex >= 0)
collection.Move(existingIndex, i);
else
collection.Insert(i, target[i]);
}
}
private async void OnClearAllClicked(object sender, RoutedEventArgs e)
{
// Deleting every note is a lot more destructive than clearing a
// transient clipboard history -- always confirm, not just when
// pinned items are involved.
var unpinnedCount = Items.Count(i => !i.IsPinned);
if (unpinnedCount == 0) return;
var dialog = new ContentDialog
{
Title = "Delete all notes?",
Content = unpinnedCount == Items.Count
? $"This will permanently delete all {unpinnedCount} notes."
: $"This will permanently delete {unpinnedCount} unpinned notes. Pinned notes are kept.",
PrimaryButtonText = "Delete",
CloseButtonText = "Cancel",
DefaultButton = ContentDialogButton.Close,
XamlRoot = Content.XamlRoot,
};
var result = await dialog.ShowAsync();
if (result != ContentDialogResult.Primary) return;
for (var i = Items.Count - 1; i >= 0; i--)
{
if (!Items[i].IsPinned)
Items.RemoveAt(i);
}
SaveNotes();
}
private void OnPinPanelClicked(object sender, RoutedEventArgs e)
{
IsPanelPinned = !IsPanelPinned;
PinPanelButton.Content = IsPanelPinned ? "\uE77A" : "\uE718";
ToolTipService.SetToolTip(PinPanelButton, IsPanelPinned ? "Unpin panel" : "Keep panel open");
if (IsPanelPinned)
WindowEffects.ApplyTopmostBelowTaskbar(_hwnd);
}
private void OnPinItemClicked(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement { Tag: NoteItem item })
{
TogglePin(item);
}
}
/// <summary>Flips IsPinned and moves the note to preserve the list's
/// invariant that every pinned note sits contiguously above every
/// unpinned one: a newly pinned note jumps straight to index 0 (the
/// very top, above any other already-pinned notes); an unpinned note
/// drops back into the unpinned section in its existing relative order
/// rather than always landing at the very top of that section.</summary>
private void TogglePin(NoteItem item)
{
var currentIndex = Items.IndexOf(item);
if (currentIndex < 0) return;
item.IsPinned = !item.IsPinned;
var targetIndex = item.IsPinned
? 0
: Items.TakeWhile(i => i.IsPinned).Count();
if (targetIndex != currentIndex)
Items.Move(currentIndex, targetIndex);
// Move already triggers ApplyFilter via the CollectionChanged
// subscription in the constructor, but only when it actually
// fires -- pinning a note that's already at index 0 skips the Move