-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
3127 lines (2780 loc) · 111 KB
/
MainWindow.xaml.cs
File metadata and controls
3127 lines (2780 loc) · 111 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 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.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
namespace NoteUI;
public sealed partial class MainWindow : Window
{
private readonly NotesManager _notes = new();
private readonly List<NoteWindow> _openNoteWindows = [];
private ReminderService? _reminderService;
private IDisposable? _acrylicController;
private SystemBackdropConfiguration? _configSource;
private TrayIcon? _trayIcon;
private ClipboardMonitor? _clipboardMonitor;
private bool _isExiting;
private AcrylicSettingsWindow? _acrylicSettingsWindow;
private VoiceNoteWindow? _voiceNoteWindow;
private NotepadWindow? _notepadWindow;
private readonly SnippetManager _snippetManager = new();
private TextExpansionService? _textExpansion;
private AiManager? _aiManager;
private HotkeyService? _hotkeyService;
private WindowAttachmentService? _attachmentService;
private readonly Dictionary<string, NoteWindow> _attachedNoteWindows = new();
private readonly Dictionary<string, IntPtr> _attachedTargetHwnds = new();
private enum ViewMode { Notes, Favorites, Tags, TagFilter, Folders, FolderFilter, Archive }
private ViewMode _currentView = ViewMode.Notes;
private string? _currentTagFilter;
private string? _currentFolderFilter;
private bool _isPinned;
private bool _isCompact;
private const int DefaultFullHeight = 650;
private const int CompactHeight = 40;
private Microsoft.UI.Xaml.DispatcherTimer? _animTimer;
private int _preCompactWidth = 380;
private int _preCompactHeight = DefaultFullHeight;
private int _targetHeight;
private int _currentAnimHeight;
// Inline note expansion
private string? _expandedNoteId;
private int _expandedCardIndex = -1;
private RichEditBox? _expandedEditor;
private bool _suppressInlineTextChanged;
private bool _inlineEditorDirty;
private bool _inlineEditorLoaded;
private bool _isDragging;
private POINT _dragStartCursor;
private Windows.Graphics.PointInt32 _dragStartPos;
public MainWindow()
{
this.InitializeComponent();
ExtendsContentIntoTitleBar = true;
var presenter = WindowHelper.GetOverlappedPresenter(this);
presenter.SetBorderAndTitleBar(false, false);
presenter.IsResizable = true;
WindowHelper.RemoveWindowBorderKeepResize(this);
var savedMainPos = AppSettings.LoadMainWindowPosition();
if (savedMainPos is { } pos)
{
AppWindow.Resize(new Windows.Graphics.SizeInt32(pos.W, pos.H));
_preCompactWidth = pos.W;
_preCompactHeight = pos.H;
WindowHelper.MoveToVisibleArea(this, pos.X, pos.Y);
}
else
{
AppWindow.Resize(new Windows.Graphics.SizeInt32(380, 650));
WindowHelper.MoveToBottomRight(this);
}
WindowShadow.Apply(this);
WindowHelper.AddResizeGrips(this);
// Set window icon (for taskbar / Alt+Tab)
var iconPath = Path.Combine(AppContext.BaseDirectory, "app.ico");
if (File.Exists(iconPath))
AppWindow.SetIcon(iconPath);
// Apply saved settings
var backdrop = AppSettings.LoadSettings();
var theme = AppSettings.LoadThemeSetting();
AppSettings.ApplyToWindow(this, backdrop, ref _acrylicController, ref _configSource);
AppSettings.ApplyThemeToWindow(this, theme, _configSource);
if (Content is FrameworkElement rootFe)
{
ThemeHelper.Initialize(rootFe);
rootFe.ActualThemeChanged += (_, _) => RefreshCurrentView();
}
// System tray icon
_trayIcon = new TrayIcon(this, "Notes");
_trayIcon.ShowRequested += () =>
{
AppWindow.Show(true);
};
_trayIcon.ExitRequested += ExitApplication;
// Clipboard source tracking
_clipboardMonitor = new ClipboardMonitor(this);
// Global hotkeys
RegisterGlobalHotkeys();
// Collapse expanded note when window loses focus
this.Activated += (_, args) =>
{
if (args.WindowActivationState == WindowActivationState.Deactivated)
CollapseExpandedNote();
};
// Hide to tray instead of closing
AppWindow.Closing += (_, args) =>
{
SaveMainWindowPosition();
SaveNotePositions();
if (!_isExiting)
{
SaveOpenedSecondaryWindows();
args.Cancel = true;
AppWindow.Hide();
}
};
this.Closed += (_, _) =>
{
SaveMainWindowPosition();
StopFirebaseListener();
_attachmentService?.Dispose();
foreach (var w in _attachedNoteWindows.Values.ToList())
{
try { w.Close(); } catch { }
}
_attachedNoteWindows.Clear();
_attachedTargetHwnds.Clear();
_textExpansion?.Stop();
_reminderService?.Dispose();
ReminderService.Shutdown();
_hotkeyService?.Dispose();
_acrylicController?.Dispose();
_clipboardMonitor?.Dispose();
_trayIcon?.Dispose();
Environment.Exit(0);
};
_notes.Load();
_snippetManager.Load();
_textExpansion = new TextExpansionService(_snippetManager);
_textExpansion.Start();
ApplyLocalization();
RefreshNotesList();
SetCompactState(AppSettings.LoadMainWindowCompact(), animate: false);
RestorePersistedWindows();
_attachmentService = new WindowAttachmentService(_notes);
_attachmentService.ShowRequested += OnAttachedNoteShow;
_attachmentService.HideRequested += OnAttachedNoteHide;
_attachmentService.Start();
_reminderService = new ReminderService(_notes);
_reminderService.ReminderFired += () => DispatcherQueue.TryEnqueue(() => RefreshCurrentView());
// Auto-connect cloud sync if previously configured
_ = InitCloudSync();
// Check for updates in background
_ = CheckForUpdateOnStartupAsync();
}
private void ApplyLocalization()
{
ToolTipService.SetToolTip(AddButton, Lang.T("tip_new"));
ToolTipService.SetToolTip(CompactButton, Lang.T("tip_compact"));
ToolTipService.SetToolTip(PinButton, Lang.T("tip_pin"));
ToolTipService.SetToolTip(SettingsButton, Lang.T("tip_settings"));
ToolTipService.SetToolTip(SyncButton, Lang.T("tip_sync"));
ToolTipService.SetToolTip(CloseButton, Lang.T("tip_close"));
ToolTipService.SetToolTip(QuickAccessButton, Lang.T("tip_quick_access"));
SearchBox.PlaceholderText = Lang.T("search");
TitleLabel.Text = Lang.T("notes");
}
private async Task InitCloudSync()
{
await _notes.InitFirebaseFromSettings();
await _notes.InitWebDavFromSettings();
UpdateSyncButtonVisibility();
RefreshCurrentView();
StartFirebaseListener();
}
// ── Auto-update ────────────────────────────────────────────
private UpdateService.UpdateInfo? _pendingUpdate;
private async Task CheckForUpdateOnStartupAsync()
{
await Task.Delay(3000); // Let the app settle first
var update = await UpdateService.CheckForUpdateAsync();
if (update == null) return;
_pendingUpdate = update;
DispatcherQueue.TryEnqueue(() =>
{
UpdateBannerText.Text = Lang.T("update_new_version", update.Version);
UpdateBanner.Visibility = Microsoft.UI.Xaml.Visibility.Visible;
});
}
private async void UpdateBanner_Click(object sender, RoutedEventArgs e)
{
if (_pendingUpdate == null) return;
if (string.IsNullOrEmpty(_pendingUpdate.DownloadUrl))
{
_ = Windows.System.Launcher.LaunchUriAsync(new Uri(_pendingUpdate.ReleaseUrl));
return;
}
UpdateBanner.IsEnabled = false;
UpdateBannerText.Text = Lang.T("update_downloading", 0);
var progress = new Progress<double>(p =>
DispatcherQueue.TryEnqueue(() =>
UpdateBannerText.Text = Lang.T("update_downloading", (int)(p * 100))));
var path = await UpdateService.DownloadInstallerAsync(_pendingUpdate.DownloadUrl, progress);
if (path != null)
{
UpdateBannerText.Text = Lang.T("update_install");
UpdateBanner.IsEnabled = true;
UpdateBanner.Click -= UpdateBanner_Click;
UpdateBanner.Click += (_, _) => UpdateService.LaunchInstallerAndExit(path);
}
else
{
UpdateBannerText.Text = Lang.T("update_error");
UpdateBanner.IsEnabled = true;
}
}
/// <summary>Real-time SSE listener on RTDB notes, replaces periodic polling.</summary>
private void StartFirebaseListener()
{
StopFirebaseListener();
if (_notes.Firebase is not { IsConnected: true } fb) return;
fb.StartListening(() =>
{
DispatcherQueue.TryEnqueue(() => _ = PullFirebaseInBackgroundAsync());
});
}
private void StopFirebaseListener()
{
_notes.Firebase?.StopListening();
}
private async Task PullFirebaseInBackgroundAsync()
{
if (_notes.IsSyncing) return;
if (_notes.Firebase is not { IsConnected: true }) return;
await _notes.SyncFromFirebase();
RefreshOpenNoteWindows();
RefreshCurrentView();
}
private void RefreshOpenNoteWindows()
{
foreach (var w in _openNoteWindows)
{
var updated = _notes.Notes.FirstOrDefault(n => n.Id == w.NoteId);
if (updated != null)
w.ReloadAfterSync(updated);
}
foreach (var (id, w) in _attachedNoteWindows)
{
var updated = _notes.Notes.FirstOrDefault(n => n.Id == id);
if (updated != null)
w.ReloadAfterSync(updated);
}
}
private void UpdateSyncButtonVisibility()
{
SyncButton.Visibility = _notes.Firebase is { IsConnected: true }
? Visibility.Visible
: Visibility.Collapsed;
}
private async void SyncButton_Click(object sender, RoutedEventArgs e)
{
SyncButton.IsEnabled = false;
try
{
await _notes.SyncSettingsFromFirebase();
await _notes.SyncFromFirebase();
RefreshOpenNoteWindows();
RefreshCurrentView();
}
finally
{
SyncButton.IsEnabled = true;
}
}
private void ExitApplication()
{
_isExiting = true;
SaveMainWindowPosition();
SaveNotePositions();
SaveOpenedSecondaryWindows();
foreach (var w in _openNoteWindows.ToList())
{
try { w.Close(); } catch { }
}
this.Close();
}
private void SaveNotePositions()
{
foreach (var w in _openNoteWindows)
{
try
{
var pos = w.AppWindow.Position;
var sz = w.AppWindow.Size;
var note = _notes.Notes.FirstOrDefault(n => n.Id == w.NoteId);
if (note != null)
{
note.PosX = pos.X;
note.PosY = pos.Y;
note.Width = w.IsCompact ? w.PreCompactWidth : sz.Width;
note.Height = w.IsCompact ? w.PreCompactHeight : sz.Height;
note.IsCompact = w.IsCompact;
}
}
catch { }
}
_notes.Save();
}
private void RefreshNotesList(string? search = null)
{
ResetExpandedState();
NotesList.Children.Clear();
var notes = _notes.GetSorted(AppSettings.LoadSortPreference()).Where(n => !n.IsArchived).ToList();
if (!string.IsNullOrEmpty(search))
{
notes = notes.Where(n =>
n.Title.Contains(search, StringComparison.OrdinalIgnoreCase) ||
n.Preview.Contains(search, StringComparison.OrdinalIgnoreCase)
).ToList();
}
var index = 0;
foreach (var note in notes)
{
var card = CreateNoteCard(note);
NotesList.Children.Add(card);
AnimationHelper.FadeSlideIn(card, delayMs: index * 30, durationMs: 250);
index++;
}
}
private void SaveMainWindowPosition()
{
AppSettings.SaveMainWindowPosition(AppWindow.Position, AppWindow.Size);
AppSettings.SaveMainWindowCompact(_isCompact);
}
private void SaveOpenedSecondaryWindows()
{
var windows = new List<PersistedWindowState>();
foreach (var noteWindow in _openNoteWindows.ToList())
{
var pos = noteWindow.AppWindow.Position;
windows.Add(new PersistedWindowState("note", noteWindow.NoteId, pos.X, pos.Y, noteWindow.IsCompact));
}
if (_notepadWindow != null)
{
var pos = _notepadWindow.AppWindow.Position;
windows.Add(new PersistedWindowState("notepad", "", pos.X, pos.Y));
}
AppSettings.SaveOpenWindows(windows);
}
private void RestorePersistedWindows()
{
var windows = AppSettings.LoadOpenWindows();
if (windows.Count == 0)
return;
var notepadRestored = false;
foreach (var window in windows)
{
if (window.Type == "note" && !string.IsNullOrWhiteSpace(window.NoteId))
{
var noteForRestore = _notes.Notes.FirstOrDefault(n => n.Id == window.NoteId);
if (noteForRestore?.IsLocked == true)
continue;
OpenNote(window.NoteId);
var opened = _openNoteWindows.FirstOrDefault(w => w.NoteId == window.NoteId);
if (opened != null)
{
opened.SetCompactState(window.IsCompact, animate: false);
WindowHelper.MoveToVisibleArea(opened, window.X, window.Y);
}
continue;
}
if (window.Type == "notepad" && !notepadRestored)
{
OpenNotepad();
if (_notepadWindow != null)
WindowHelper.MoveToVisibleArea(_notepadWindow, window.X, window.Y);
notepadRestored = true;
}
}
}
private UIElement CreateNoteCard(NoteEntry note)
{
if (AppSettings.LoadCompactCards())
return CreateCompactNoteCard(note);
var color = NoteColors.Get(note.Color);
var hasColor = !NoteColors.IsNone(note.Color);
var isFull = hasColor && AppSettings.LoadNoteStyle() == "full";
var cardColor = isFull
? color
: hasColor
? ThemeHelper.CardBackgroundWithColor(color)
: ThemeHelper.CardBackground;
var cardBg = new SolidColorBrush(cardColor);
var outer = new Button
{
Background = cardBg,
CornerRadius = new CornerRadius(8),
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
BorderThickness = new Thickness(0),
Padding = new Thickness(0),
};
if (isFull)
{
var blackBrush = new SolidColorBrush(Microsoft.UI.Colors.Black);
var hoverBg = new SolidColorBrush(NoteColors.GetDarker(note.Color, 0.93));
var pressedBg = new SolidColorBrush(NoteColors.GetDarker(note.Color, 0.88));
outer.Foreground = blackBrush;
outer.Resources["ButtonForeground"] = blackBrush;
outer.Resources["ButtonForegroundPointerOver"] = blackBrush;
outer.Resources["ButtonForegroundPressed"] = blackBrush;
outer.Resources["ButtonBackground"] = cardBg;
outer.Resources["ButtonBackgroundPointerOver"] = hoverBg;
outer.Resources["ButtonBackgroundPressed"] = pressedBg;
}
var stack = new StackPanel();
// Thin color bar at top (skip in full color mode — entire card is colored)
if (hasColor && !isFull)
{
stack.Children.Add(new Border
{
Height = 4,
Background = new SolidColorBrush(color),
CornerRadius = new CornerRadius(8, 8, 0, 0),
});
}
var content = new StackPanel { Padding = new Thickness(14, 10, 14, 14) };
// Source row (clipboard origin)
if (!string.IsNullOrEmpty(note.SourceExePath))
{
var sourcePanel = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 5,
Margin = new Thickness(0, 0, 0, 4)
};
var sourceIcon = new Image
{
Width = 14,
Height = 14,
VerticalAlignment = VerticalAlignment.Center
};
_ = IconHelper.LoadIconAsync(sourceIcon, note.SourceExePath);
sourcePanel.Children.Add(sourceIcon);
var sourceLabel = !string.IsNullOrEmpty(note.SourceTitle)
? note.SourceTitle
: Path.GetFileNameWithoutExtension(note.SourceExePath);
sourcePanel.Children.Add(new TextBlock
{
Text = sourceLabel,
FontSize = 11,
Opacity = 0.5,
TextTrimming = TextTrimming.CharacterEllipsis,
MaxLines = 1,
VerticalAlignment = VerticalAlignment.Center
});
content.Children.Add(sourcePanel);
}
// Title row: bold title left, meta right
var titleRow = new Grid();
titleRow.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
titleRow.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
var titleText = new TextBlock
{
Text = note.Title,
FontSize = 14,
FontWeight = Microsoft.UI.Text.FontWeights.SemiBold,
TextTrimming = TextTrimming.CharacterEllipsis,
VerticalAlignment = VerticalAlignment.Center,
};
Grid.SetColumn(titleText, 0);
titleRow.Children.Add(titleText);
var metaPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
if (note.IsPinned)
{
metaPanel.Children.Add(new FontIcon
{
Glyph = "\uE718",
FontSize = 10,
Opacity = 0.45,
VerticalAlignment = VerticalAlignment.Center
});
}
if (note.IsLocked)
{
metaPanel.Children.Add(new FontIcon
{
Glyph = "\uE72E",
FontSize = 10,
Opacity = 0.45,
VerticalAlignment = VerticalAlignment.Center
});
}
if (!string.IsNullOrEmpty(note.Folder))
{
var folderIcon = new FontIcon
{
Glyph = "\uE8B7",
FontSize = 10,
Opacity = 0.45,
VerticalAlignment = VerticalAlignment.Center
};
ToolTipService.SetToolTip(folderIcon, note.Folder);
metaPanel.Children.Add(folderIcon);
}
if (!string.IsNullOrEmpty(note.AttachMode))
{
var attachIcon = new FontIcon
{
Glyph = "\uE723",
FontSize = 10,
Opacity = 0.45,
VerticalAlignment = VerticalAlignment.Center
};
ToolTipService.SetToolTip(attachIcon,
$"{Lang.T("attached_to")} {GetAttachTargetLabel(note)}");
metaPanel.Children.Add(attachIcon);
}
if (!string.IsNullOrEmpty(note.TaskProgress))
{
metaPanel.Children.Add(new TextBlock
{
Text = note.TaskProgress,
FontSize = 11,
Opacity = 0.45,
VerticalAlignment = VerticalAlignment.Center
});
}
metaPanel.Children.Add(new TextBlock
{
Text = note.DateDisplay,
FontSize = 12,
Opacity = 0.45,
});
Grid.SetColumn(metaPanel, 1);
titleRow.Children.Add(metaPanel);
content.Children.Add(titleRow);
// Preview text
if (note.IsLocked)
{
content.Children.Add(new TextBlock
{
Text = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",
FontSize = 12,
Margin = new Thickness(0, 2, 0, 0),
Opacity = 0.35,
});
}
else
{
var preview = note.Preview;
if (!string.IsNullOrEmpty(preview))
{
content.Children.Add(new TextBlock
{
Text = preview,
TextWrapping = TextWrapping.Wrap,
MaxLines = 3,
TextTrimming = TextTrimming.CharacterEllipsis,
FontSize = 12,
Margin = new Thickness(0, 2, 0, 0),
Opacity = 0.65,
});
}
// Image thumbnail (first embedded screenshot)
var imageBytes = note.ExtractFirstImageBytes();
if (imageBytes != null)
{
var img = new Image
{
MaxHeight = 60,
Stretch = Stretch.Uniform,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0, 6, 0, 0),
};
content.Children.Add(img);
_ = LoadThumbnailAsync(img, imageBytes);
}
}
stack.Children.Add(content);
outer.Content = stack;
var noteId = note.Id;
outer.Tag = noteId;
DispatcherTimer? clickTimer = null;
bool doubleClicked = false;
outer.Click += (_, _) =>
{
if (doubleClicked) { doubleClicked = false; return; }
if (clickTimer != null) return;
clickTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
clickTimer.Tick += (_, _) =>
{
clickTimer.Stop();
clickTimer = null;
if (!doubleClicked) ToggleNoteExpansion(noteId);
};
clickTimer.Start();
};
outer.DoubleTapped += (_, e) =>
{
e.Handled = true;
doubleClicked = true;
if (clickTimer != null) { clickTimer.Stop(); clickTimer = null; }
OpenNote(noteId);
};
outer.RightTapped += (s, e) =>
{
e.Handled = true;
ShowNoteContextMenu(noteId, (FrameworkElement)s);
};
return outer;
}
private static async Task LoadThumbnailAsync(Image img, byte[] data)
{
try
{
var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(data.AsBuffer());
stream.Seek(0);
var bitmap = new BitmapImage { DecodePixelHeight = 60 };
await bitmap.SetSourceAsync(stream);
img.Source = bitmap;
}
catch { }
}
private static string GetAttachTargetLabel(NoteEntry note)
{
if (string.IsNullOrWhiteSpace(note.AttachTarget))
return "";
return note.AttachMode switch
{
"process" => note.AttachTarget!,
"folder" => Path.GetFileName(note.AttachTarget!),
"title" => note.AttachTarget!,
_ => note.AttachTarget!
};
}
private void ShowNoteContextMenu(string noteId, FrameworkElement target)
{
var note = _notes.Notes.FirstOrDefault(n => n.Id == noteId);
var pinLabel = note?.IsPinned == true ? Lang.T("unpin") : Lang.T("pin");
var pinGlyph = note?.IsPinned == true ? "\uE77A" : "\uE718";
var actions = new List<ActionPanel.ActionItem>
{
new(pinGlyph, pinLabel, [], () =>
{
_notes.TogglePin(noteId);
RefreshCurrentView();
}),
new("\uE70F", Lang.T("edit"), [], () => OpenNote(noteId)),
new("\uE8C8", Lang.T("duplicate"), [], () =>
{
var copy = _notes.DuplicateNote(noteId);
if (copy != null)
{
RefreshCurrentView();
OpenNote(copy.Id);
}
}),
new("\uE943", Lang.T("snippet"), [], () =>
{
ActionPanel.ShowSnippetFlyout(target, noteId, _snippetManager, note?.Content ?? "");
}),
new(note?.IsLocked == true ? "\uE785" : "\uE72E",
note?.IsLocked == true ? Lang.T("unlock") : Lang.T("lock"), [], () =>
{
HandleLockToggle(noteId, target);
}),
new("\uE723",
note != null && !string.IsNullOrEmpty(note.AttachMode)
? $"{Lang.T("attached_to")} {GetAttachTargetLabel(note)}"
: Lang.T("attach_to_window"), [], () =>
{
if (note != null)
ShowAttachMenuFromList(note, target);
}),
new("\uE7B8", note?.IsArchived == true ? Lang.T("unarchive") : Lang.T("archive"), [], () =>
{
_notes.ToggleArchive(noteId);
RefreshCurrentView();
}),
new("\uE74D", Lang.T("delete"), [], () =>
{
void DoDelete()
{
var existing = _openNoteWindows.FirstOrDefault(w => w.NoteId == noteId);
if (existing != null)
{
try { existing.Close(); } catch { }
}
_notes.DeleteNote(noteId);
RefreshCurrentView();
}
if (note?.IsLocked == true)
{
var storedHash = AppSettings.LoadMasterPasswordHash();
if (string.IsNullOrEmpty(storedHash)) return;
ActionPanel.ShowEnterPasswordFlyout(target, storedHash, DoDelete);
}
else
{
DoDelete();
}
}, IsDestructive: true),
};
var flyout = ActionPanel.Create(Lang.T("actions"), actions);
flyout.ShowAt(target);
}
private void ShowAttachMenuFromList(NoteEntry note, FrameworkElement target)
{
var actions = new List<ActionPanel.ActionItem>
{
new("\uE737", Lang.T("attach_to_program"), [], () =>
{
ShowRunningProgramsPicker(note, target);
}),
new("\uE774", Lang.T("attach_to_website"), [], () =>
{
ShowWebTabsPicker(note, target);
}),
new("\uE8B7", Lang.T("attach_to_folder"), [], async () =>
{
await PickAttachFolder(note);
}),
};
if (!string.IsNullOrEmpty(note.AttachMode))
{
actions.Add(new("\uE711", Lang.T("detach"), [], () =>
{
note.AttachTarget = null;
note.AttachMode = null;
note.AttachOffsetX = 0;
note.AttachOffsetY = 0;
_notes.Save();
_attachmentService?.Refresh();
RefreshCurrentView();
}, IsDestructive: true));
}
var flyout = ActionPanel.Create(Lang.T("attach_to_window"), actions);
flyout.ShowAt(target);
}
private void ShowRunningProgramsPicker(NoteEntry note, FrameworkElement target)
{
var programs = WindowAttachmentHelper.GetVisibleWindows();
if (programs.Count == 0)
{
var empty = ActionPanel.Create(Lang.T("select_program"),
[new(null, Lang.T("no_windows_found"), [], () => { })]);
empty.ShowAt(target);
return;
}
var actions = programs.Select(p =>
new ActionPanel.ActionItem(null, $"{p.ProcessName} — {p.Title}", [], () =>
{
note.AttachTarget = p.ProcessName;
note.AttachMode = "process";
note.AttachOffsetX = 0;
note.AttachOffsetY = 0;
_notes.Save();
_attachmentService?.Refresh();
RefreshCurrentView();
})
).ToList();
var flyout = ActionPanel.Create(Lang.T("select_program"), actions);
flyout.ShowAt(target);
}
private void ShowWebTabsPicker(NoteEntry note, FrameworkElement target)
{
var tabs = WindowAttachmentHelper.GetVisibleWebTabs();
if (tabs.Count == 0)
{
var empty = ActionPanel.Create(Lang.T("select_website"),
[new(null, Lang.T("no_web_tabs_found"), [], () => { })]);
empty.ShowAt(target);
return;
}
var actions = tabs.Select(tab =>
new ActionPanel.ActionItem(null, $"{tab.ProcessName} — {tab.Title}", [], () =>
{
note.AttachTarget = tab.Title;
note.AttachMode = "title";
note.AttachOffsetX = 0;
note.AttachOffsetY = 0;
_notes.Save();
_attachmentService?.Refresh();
RefreshCurrentView();
})
).ToList();
var flyout = ActionPanel.Create(Lang.T("select_website"), actions);
flyout.ShowAt(target);
}
private async Task PickAttachFolder(NoteEntry note)
{
var picker = new Windows.Storage.Pickers.FolderPicker();
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
picker.FileTypeFilter.Add("*");
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);
var folder = await picker.PickSingleFolderAsync();
if (folder == null) return;
note.AttachTarget = folder.Path;
note.AttachMode = "folder";
note.AttachOffsetX = 0;
note.AttachOffsetY = 0;
_notes.Save();
_attachmentService?.Refresh();
RefreshCurrentView();
}
private void HandleLockToggle(string noteId, FrameworkElement target)
{
var note = _notes.Notes.FirstOrDefault(n => n.Id == noteId);
if (note == null) return;
if (note.IsLocked)
{
var storedHash = AppSettings.LoadMasterPasswordHash();
if (string.IsNullOrEmpty(storedHash)) return;
ActionPanel.ShowEnterPasswordFlyout(target, storedHash, () =>
{
_notes.ToggleLock(noteId);
RefreshCurrentView();
});
return;
}
if (!AppSettings.HasMasterPassword())
{
ActionPanel.ShowCreatePasswordFlyout(target, password =>
{
var hash = AppSettings.HashPassword(password);
AppSettings.SaveMasterPasswordHash(hash);
_notes.ToggleLock(noteId);
RefreshCurrentView();
_ = _notes.SyncSettingsToFirebase();
});
}
else
{
_notes.ToggleLock(noteId);
RefreshCurrentView();
}
}
private void OpenNote(string noteId)
{
var existing = _openNoteWindows.FirstOrDefault(w => w.NoteId == noteId);
if (existing != null)
{
existing.Activate();
return;
}
var note = _notes.Notes.FirstOrDefault(n => n.Id == noteId);
if (note == null) return;
if (note.IsLocked)
{
var storedHash = AppSettings.LoadMasterPasswordHash();
if (string.IsNullOrEmpty(storedHash)) return;
ActionPanel.ShowEnterPasswordFlyout(NotesList, storedHash, () =>
{
OpenNoteUnlocked(noteId);
});
return;
}
OpenNoteUnlocked(noteId);
}
private void OpenNoteUnlocked(string noteId)
{
var existing = _openNoteWindows.FirstOrDefault(w => w.NoteId == noteId);
if (existing != null)
{
existing.Activate();
return;
}
var note = _notes.Notes.FirstOrDefault(n => n.Id == noteId);
if (note == null) return;
var pos = AppWindow.Position;
var sz = AppWindow.Size;
var parentRect = new NoteWindow.ParentRect(pos.X, pos.Y, sz.Width, sz.Height);
var window = new NoteWindow(_notes, note, parentRect);
window.SetSnippetManager(_snippetManager);
window.RefreshAiUi();
_openNoteWindows.Add(window);
window.NoteChanged += () =>
{
// Keep snippet content in sync (no main window refresh — deferred to close)
var n = _notes.Notes.FirstOrDefault(n => n.Id == window.NoteId);
if (n != null) _snippetManager.UpdateContent(n.Id, n.Content);
};
window.OpenInNotepadRequested += () =>
{
var note = _notes.Notes.FirstOrDefault(n => n.Id == window.NoteId);