-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
937 lines (792 loc) · 35 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
937 lines (792 loc) · 35 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Caelum.Models;
using Caelum.Pages;
using Caelum.Services;
namespace Caelum
{
public partial class MainWindow : Window
{
private const int WM_GETMINMAXINFO = 0x0024;
private const uint MONITOR_DEFAULTTONEAREST = 0x00000002;
private const string TabDragDataFormat = "Caelum.AppTab";
private readonly List<AppTab> _tabs = new List<AppTab>();
private AppTab _activeTab;
private Point _tabDragStartPoint;
private AppTab _tabDragCandidate;
private bool _isTabDragInProgress;
public MainWindow()
{
InitializeComponent();
LoadAppIcon();
SourceInitialized += MainWindow_SourceInitialized;
StateChanged += MainWindow_StateChanged;
KeyDown += MainWindow_KeyDown;
TitleBarBorder.MouseLeftButtonDown += (sender, args) => DragMove();
ApplyLocalization();
// Create the first Home tab
AddNewHomeTab(activate: true);
}
private void LoadAppIcon()
{
try
{
var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets", "app-icon.ico");
if (!File.Exists(iconPath)) return;
using var fs = new FileStream(iconPath, FileMode.Open, FileAccess.Read);
var decoder = new IconBitmapDecoder(fs, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
// Pick the largest frame 鈥?preserves 32-bit ARGB transparency
var best = decoder.Frames.OrderByDescending(f => f.PixelWidth).First();
Icon = best;
}
catch
{
// Fall back silently 鈥?window will use default icon
}
}
// 鈹€鈹€鈹€ Drag & Drop 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
private static readonly string[] SupportedDropExtensions = { ".pdf" };
private bool HasSupportedFiles(DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return false;
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
return files != null && files.Any(f =>
SupportedDropExtensions.Contains(Path.GetExtension(f).ToLowerInvariant()));
}
private bool ShouldDeferWindowFileDrop(DragEventArgs e)
{
return ActiveFrame?.Content is HomePage home &&
home.ShouldDeferWindowFileDrop(e.OriginalSource as DependencyObject, e.Data);
}
private void Window_DragEnter(object sender, DragEventArgs e)
{
if (ShouldDeferWindowFileDrop(e))
return;
e.Effects = HasSupportedFiles(e) ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
private void Window_DragOver(object sender, DragEventArgs e)
{
if (ShouldDeferWindowFileDrop(e))
return;
e.Effects = HasSupportedFiles(e) ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
private void Window_Drop(object sender, DragEventArgs e)
{
if (ShouldDeferWindowFileDrop(e))
return;
if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files == null) return;
var pdfFiles = files.Where(f =>
SupportedDropExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())).ToList();
if (pdfFiles.Count == 0) return;
// If the active tab is on the Home page, open the first file in-place
bool isHomePage = ActiveFrame?.Content is HomePage;
bool first = true;
foreach (var file in pdfFiles)
{
if (first && isHomePage)
{
// Open directly in the current Home tab
NavigateActiveTabToFile(file);
first = false;
}
else
{
OpenFileInNewTab(file);
first = false;
}
}
e.Handled = true;
}
// 鈹€鈹€鈹€ Tab Management 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
private Frame ActiveFrame => _activeTab?.Frame;
internal bool IsActiveContent(object content) => ReferenceEquals(ActiveFrame?.Content, content);
public void AddNewHomeTab(bool activate = true)
{
var tab = new AppTab { Title = GetHomeTabTitle(), Icon = "\uE80F" };
var frame = new Frame
{
NavigationUIVisibility = NavigationUIVisibility.Hidden,
AllowDrop = true,
Background = Brushes.Transparent
};
frame.Navigated += Frame_Navigated;
tab.Frame = frame;
TabContentArea.Children.Add(frame);
_tabs.Add(tab);
RebuildTabBar();
frame.Navigate(new HomePage());
if (activate)
ActivateTab(tab);
}
public void OpenFileInNewTab(string filePath, bool promptSaveAsAfterLoad = false, string pendingLibraryFolderId = null, bool isNotebookDraft = false)
{
RecentFilesService.AddOrPromote(filePath);
// Check if this file is already open
var existing = _tabs.FirstOrDefault(t =>
!string.IsNullOrEmpty(t.FilePath) &&
string.Equals(t.FilePath, filePath, StringComparison.OrdinalIgnoreCase));
if (existing != null)
{
ActivateTab(existing);
return;
}
var name = Path.GetFileNameWithoutExtension(filePath);
var ext = Path.GetExtension(filePath).ToLowerInvariant();
string icon = ext == ".pdf" ? "\uEA90" : "\uE7C3"; // PDF icon or generic document
var tab = new AppTab { Title = name, Icon = icon, FilePath = filePath };
var frame = new Frame
{
NavigationUIVisibility = NavigationUIVisibility.Hidden,
AllowDrop = true,
Background = Brushes.Transparent
};
frame.Navigated += Frame_Navigated;
tab.Frame = frame;
TabContentArea.Children.Add(frame);
_tabs.Add(tab);
RebuildTabBar();
frame.Navigate(new EditorPage(filePath, promptSaveAsAfterLoad, pendingLibraryFolderId, isNotebookDraft));
ActivateTab(tab);
}
private void ActivateTab(AppTab tab)
{
if (_activeTab == tab) return;
foreach (var t in _tabs)
{
t.IsActive = false;
if (t.Frame != null)
t.Frame.Visibility = Visibility.Collapsed;
}
tab.IsActive = true;
tab.Frame.Visibility = Visibility.Visible;
_activeTab = tab;
UpdateNavButtons();
RebuildTabBar();
RefreshSelectButtonVisualState();
}
private async void CloseTab(AppTab tab)
{
// Auto-save if editor
if (tab.Frame?.Content is EditorPage editor)
{
var saved = await editor.AutoSaveAsync();
if (saved) ShowToast(LocalizationService.Get("Main.FileAutoSaved"));
}
tab.Frame.Navigated -= Frame_Navigated;
TabContentArea.Children.Remove(tab.Frame);
_tabs.Remove(tab);
if (_tabs.Count == 0)
{
// Always keep at least one tab
AddNewHomeTab(activate: true);
}
else if (tab == _activeTab)
{
ActivateTab(_tabs.Last());
}
RebuildTabBar();
}
private void RebuildTabBar()
{
TabBar.Children.Clear();
foreach (var tab in _tabs)
{
var tabButton = CreateTabButton(tab);
TabBar.Children.Add(tabButton);
}
}
private Border CreateTabButton(AppTab tab)
{
bool isActive = tab == _activeTab;
var activeForeground = new SolidColorBrush(Color.FromRgb(31, 41, 55));
var inactiveForeground = new SolidColorBrush(Color.FromRgb(107, 114, 128));
var activeCloseForeground = new SolidColorBrush(Color.FromRgb(75, 85, 99));
var inactiveCloseForeground = new SolidColorBrush(Color.FromRgb(156, 163, 175));
var activeBackground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
var hoverBackground = new SolidColorBrush(Color.FromArgb(18, 17, 24, 39));
var transparentBackground = Brushes.Transparent;
var activeBorderBrush = new SolidColorBrush(Color.FromArgb(18, 17, 24, 39));
// Tab content: icon + title + close button
var icon = new TextBlock
{
Text = tab.Icon,
FontFamily = new FontFamily("Segoe MDL2 Assets"),
FontSize = 13,
Foreground = isActive ? activeForeground : inactiveForeground,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0)
};
var title = new TextBlock
{
Text = tab.Title.Length > 20 ? tab.Title.Substring(0, 17) + "..." : tab.Title,
FontSize = 13,
Foreground = isActive ? activeForeground : inactiveForeground,
VerticalAlignment = VerticalAlignment.Center,
MaxWidth = 132,
TextTrimming = TextTrimming.CharacterEllipsis,
FontWeight = isActive ? FontWeights.Medium : FontWeights.Normal
};
var closeBtn = new Button
{
Content = new TextBlock
{
Text = "\uE8BB",
FontFamily = new FontFamily("Segoe MDL2 Assets"),
FontSize = 10,
Foreground = isActive ? activeCloseForeground : inactiveCloseForeground
},
Width = 20,
Height = 20,
Background = transparentBackground,
BorderThickness = new Thickness(0),
Cursor = Cursors.Hand,
Margin = new Thickness(6, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
Visibility = _tabs.Count > 1 ? Visibility.Visible : Visibility.Collapsed,
Opacity = isActive ? 1 : 0.72,
ToolTip = LocalizationService.Get("Main.CloseTabTooltip")
};
// Close button template with hover
var closeBtnTemplate = new ControlTemplate(typeof(Button));
var closeBorder = new FrameworkElementFactory(typeof(Border));
closeBorder.SetValue(Border.BackgroundProperty, transparentBackground);
closeBorder.SetValue(Border.CornerRadiusProperty, new CornerRadius(5));
closeBorder.Name = "CloseBg";
var closeContent = new FrameworkElementFactory(typeof(ContentPresenter));
closeContent.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
closeContent.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
closeBorder.AppendChild(closeContent);
closeBtnTemplate.VisualTree = closeBorder;
var hoverTrigger = new Trigger { Property = UIElement.IsMouseOverProperty, Value = true };
hoverTrigger.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Color.FromArgb(18, 17, 24, 39)), "CloseBg"));
closeBtnTemplate.Triggers.Add(hoverTrigger);
closeBtn.Template = closeBtnTemplate;
var capturedTab = tab;
closeBtn.Click += (s, e) => { e.Handled = true; CloseTab(capturedTab); };
var panel = new StackPanel();
panel.Orientation = Orientation.Horizontal;
panel.Margin = new Thickness(10, 0, 8, 0);
panel.VerticalAlignment = VerticalAlignment.Center;
panel.Children.Add(icon);
panel.Children.Add(title);
panel.Children.Add(closeBtn);
var border = new Border
{
Child = panel,
Background = isActive ? activeBackground : transparentBackground,
BorderBrush = isActive ? activeBorderBrush : transparentBackground,
BorderThickness = isActive ? new Thickness(1) : new Thickness(0),
CornerRadius = new CornerRadius(10),
Margin = new Thickness(0, 0, 4, 0),
Height = 32,
MinWidth = 72,
AllowDrop = true,
Cursor = Cursors.Hand,
SnapsToDevicePixels = true
};
border.MouseEnter += (s, e) =>
{
if (capturedTab != _activeTab)
{
border.Background = hoverBackground;
}
closeBtn.Opacity = 1;
};
border.MouseLeave += (s, e) =>
{
if (capturedTab != _activeTab)
{
border.Background = transparentBackground;
}
closeBtn.Opacity = capturedTab == _activeTab ? 1 : 0.72;
};
border.PreviewMouseLeftButtonDown += (s, e) =>
{
if (e.OriginalSource is DependencyObject source && IsDescendantOf(source, closeBtn))
return;
ActivateTab(capturedTab);
_tabDragCandidate = capturedTab;
_tabDragStartPoint = e.GetPosition(TabBar);
};
border.PreviewMouseMove += (s, e) =>
{
if (_isTabDragInProgress ||
_tabDragCandidate != capturedTab ||
e.LeftButton != MouseButtonState.Pressed)
{
return;
}
var currentPosition = e.GetPosition(TabBar);
if (!HasExceededDragThreshold(_tabDragStartPoint, currentPosition))
return;
_isTabDragInProgress = true;
try
{
DragDrop.DoDragDrop(border, new DataObject(TabDragDataFormat, capturedTab.Id), DragDropEffects.Move);
}
finally
{
_isTabDragInProgress = false;
if (_tabDragCandidate == capturedTab)
_tabDragCandidate = null;
}
e.Handled = true;
};
border.PreviewMouseLeftButtonUp += (s, e) =>
{
if (_tabDragCandidate == capturedTab)
_tabDragCandidate = null;
};
// Middle-click to close
border.MouseDown += (s, e) =>
{
if (e.ChangedButton == MouseButton.Middle && _tabs.Count > 1)
{
e.Handled = true;
CloseTab(capturedTab);
}
};
border.DragOver += (s, e) =>
{
if (TryGetDraggedTab(e.Data, out var draggedTab) && draggedTab != capturedTab)
{
e.Effects = DragDropEffects.Move;
e.Handled = true;
return;
}
e.Effects = DragDropEffects.None;
e.Handled = true;
};
border.Drop += (s, e) =>
{
if (!TryGetDraggedTab(e.Data, out var draggedTab) || draggedTab == capturedTab)
return;
bool insertAfter = e.GetPosition(border).X >= border.ActualWidth / 2;
MoveTab(draggedTab, capturedTab, insertAfter);
e.Handled = true;
};
return border;
}
private bool TryGetDraggedTab(IDataObject data, out AppTab tab)
{
tab = null;
if (data == null || !data.GetDataPresent(TabDragDataFormat))
return false;
var tabId = data.GetData(TabDragDataFormat) as string;
if (string.IsNullOrWhiteSpace(tabId))
return false;
tab = _tabs.FirstOrDefault(candidate => string.Equals(candidate.Id, tabId, StringComparison.Ordinal));
return tab != null;
}
private void MoveTab(AppTab draggedTab, AppTab targetTab, bool insertAfter)
{
if (draggedTab == null || targetTab == null || draggedTab == targetTab)
return;
int sourceIndex = _tabs.IndexOf(draggedTab);
int targetIndex = _tabs.IndexOf(targetTab);
if (sourceIndex < 0 || targetIndex < 0)
return;
_tabs.RemoveAt(sourceIndex);
if (sourceIndex < targetIndex)
targetIndex--;
int insertIndex = insertAfter ? targetIndex + 1 : targetIndex;
insertIndex = Math.Max(0, Math.Min(insertIndex, _tabs.Count));
_tabs.Insert(insertIndex, draggedTab);
RebuildTabBar();
}
private static bool HasExceededDragThreshold(Point startPoint, Point currentPoint)
{
return Math.Abs(currentPoint.X - startPoint.X) >= SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(currentPoint.Y - startPoint.Y) >= SystemParameters.MinimumVerticalDragDistance;
}
private static bool IsDescendantOf(DependencyObject descendant, DependencyObject ancestor)
{
var current = descendant;
while (current != null)
{
if (current == ancestor)
return true;
current = VisualTreeHelper.GetParent(current) ?? LogicalTreeHelper.GetParent(current);
}
return false;
}
// 鈹€鈹€鈹€ Navigation (operates on active tab's frame) 鈹€鈹€
private void Frame_Navigated(object sender, NavigationEventArgs e)
{
if (sender == _activeTab?.Frame)
{
UpdateNavButtons();
UpdateActiveTabInfo();
RefreshSelectButtonVisualState();
}
}
private void UpdateNavButtons()
{
var frame = ActiveFrame;
NavBackButton.IsEnabled = frame?.CanGoBack == true;
NavForwardButton.IsEnabled = frame?.CanGoForward == true;
}
private async void NavBack_Click(object sender, RoutedEventArgs e)
{
if (ActiveFrame?.Content is EditorPage editor)
{
var saved = await editor.AutoSaveAsync();
if (saved) ShowToast(LocalizationService.Get("Main.FileAutoSaved"));
}
if (ActiveFrame?.CanGoBack == true)
{
ActiveFrame.GoBack();
}
}
private void NavForward_Click(object sender, RoutedEventArgs e)
{
if (ActiveFrame?.CanGoForward == true)
{
ActiveFrame.GoForward();
}
}
private async void NavHome_Click(object sender, RoutedEventArgs e)
{
if (ActiveFrame == null) return;
if (ActiveFrame.Content is EditorPage editor)
{
var saved = await editor.AutoSaveAsync();
if (saved) ShowToast(LocalizationService.Get("Main.FileAutoSaved"));
}
ActiveFrame.Navigate(new HomePage());
}
private void NewTab_Click(object sender, RoutedEventArgs e)
{
AddNewHomeTab(activate: true);
}
private void UpdateActiveTabInfo()
{
if (_activeTab == null) return;
if (ActiveFrame?.Content is HomePage)
{
_activeTab.Title = GetHomeTabTitle();
_activeTab.Icon = "\uE80F";
_activeTab.FilePath = null;
}
else if (ActiveFrame?.Content is EditorPage ep && !string.IsNullOrEmpty(ep.CurrentPdfPath))
{
_activeTab.Title = Path.GetFileNameWithoutExtension(ep.CurrentPdfPath);
_activeTab.FilePath = ep.CurrentPdfPath;
_activeTab.Icon = Path.GetExtension(ep.CurrentPdfPath).ToLowerInvariant() == ".pdf" ? "\uEA90" : "\uE7C3";
}
RebuildTabBar();
}
public void RefreshActiveTabInfo()
{
UpdateActiveTabInfo();
}
// Called by HomePage/EditorPage to navigate the current tab to a file
public void NavigateActiveTabToFile(string filePath, bool promptSaveAsAfterLoad = false, string pendingLibraryFolderId = null, bool isNotebookDraft = false)
{
if (_activeTab == null) return;
RecentFilesService.AddOrPromote(filePath);
// Check if already open in another tab
var existing = _tabs.FirstOrDefault(t =>
t != _activeTab &&
!string.IsNullOrEmpty(t.FilePath) &&
string.Equals(t.FilePath, filePath, StringComparison.OrdinalIgnoreCase));
if (existing != null)
{
ActivateTab(existing);
return;
}
var name = Path.GetFileNameWithoutExtension(filePath);
_activeTab.Title = name;
_activeTab.FilePath = filePath;
_activeTab.Icon = Path.GetExtension(filePath).ToLowerInvariant() == ".pdf" ? "\uEA90" : "\uE7C3";
ActiveFrame?.Navigate(new EditorPage(filePath, promptSaveAsAfterLoad, pendingLibraryFolderId, isNotebookDraft));
RebuildTabBar();
}
public void HandleFilePathChanged(string oldPath, string newPath)
{
if (string.IsNullOrWhiteSpace(oldPath) || string.IsNullOrWhiteSpace(newPath))
return;
foreach (var tab in _tabs.Where(tab =>
!string.IsNullOrWhiteSpace(tab.FilePath) &&
string.Equals(tab.FilePath, oldPath, StringComparison.OrdinalIgnoreCase)))
{
tab.FilePath = newPath;
tab.Title = Path.GetFileNameWithoutExtension(newPath);
tab.Icon = Path.GetExtension(newPath).ToLowerInvariant() == ".pdf" ? "\uEA90" : "\uE7C3";
if (tab.Frame?.Content is EditorPage editor)
editor.UpdateCurrentPdfPath(newPath);
}
if (_activeTab != null &&
!string.IsNullOrWhiteSpace(_activeTab.FilePath) &&
string.Equals(_activeTab.FilePath, newPath, StringComparison.OrdinalIgnoreCase))
{
UpdateActiveTabInfo();
}
else
{
RebuildTabBar();
}
}
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control)
{
if (e.Key == Key.T)
{
AddNewHomeTab(activate: true);
e.Handled = true;
}
else if (e.Key == Key.W && _tabs.Count > 0)
{
CloseTab(_activeTab);
e.Handled = true;
}
}
}
// 鈹€鈹€鈹€ Window State 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
private void MainWindow_StateChanged(object sender, EventArgs e)
{
MaximizeIcon.Text = WindowState == WindowState.Maximized ? "\uE923" : "\uE922";
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e) => WindowState = WindowState.Minimized;
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
=> WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
private void CloseButton_Click(object sender, RoutedEventArgs e) => Close();
protected override async void OnClosing(System.ComponentModel.CancelEventArgs e)
{
// Auto-save all open editor tabs
foreach (var tab in _tabs)
{
if (tab.Frame?.Content is EditorPage editor)
{
await editor.AutoSaveAsync();
}
}
base.OnClosing(e);
}
private void MainWindow_SourceInitialized(object sender, EventArgs e)
{
var handle = new WindowInteropHelper(this).Handle;
HwndSource.FromHwnd(handle)?.AddHook(WndProc);
// Enforce transparent icon at Win32 level
try
{
var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets", "app-icon.ico");
if (File.Exists(iconPath))
{
const int IMAGE_ICON = 1;
const int LR_LOADFROMFILE = 0x00000010;
const int LR_SHARED = 0x00008000;
const int WM_SETICON = 0x0080;
const int ICON_SMALL = 0;
const int ICON_BIG = 1;
// Fetch the absolute maximum icons internally to force extreme clarity and size
IntPtr hIconSmall = LoadImage(IntPtr.Zero, iconPath, IMAGE_ICON, 64, 64, LR_LOADFROMFILE | LR_SHARED);
IntPtr hIconBig = LoadImage(IntPtr.Zero, iconPath, IMAGE_ICON, 256, 256, LR_LOADFROMFILE | LR_SHARED);
if (hIconSmall != IntPtr.Zero) SendMessage(handle, WM_SETICON, (IntPtr)ICON_SMALL, hIconSmall);
if (hIconBig != IntPtr.Zero) SendMessage(handle, WM_SETICON, (IntPtr)ICON_BIG, hIconBig);
}
}
catch { }
EnableAcrylicBlur(handle);
// Allow drag-drop messages through UIPI (fixes blocked drops when running elevated)
ChangeWindowMessageFilterEx(handle, 0x0233, 1, IntPtr.Zero); // WM_DROPFILES
ChangeWindowMessageFilterEx(handle, 0x004A, 1, IntPtr.Zero); // WM_COPYDATA
ChangeWindowMessageFilterEx(handle, 0x0049, 1, IntPtr.Zero); // WM_COPYGLOBALDATA
DragDrop.AddPreviewDropHandler(this, Window_Drop);
DragDrop.AddPreviewDragOverHandler(this, Window_DragOver);
DragDrop.AddPreviewDragEnterHandler(this, Window_DragEnter);
}
// 鈹€鈹€鈹€ Header Toolbar Buttons 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_GETMINMAXINFO)
{
UpdateMaximizedBounds(hwnd, lParam);
handled = true;
}
return IntPtr.Zero;
}
private static void UpdateMaximizedBounds(IntPtr hwnd, IntPtr lParam)
{
var monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor == IntPtr.Zero)
return;
var monitorInfo = new MONITORINFO
{
cbSize = Marshal.SizeOf<MONITORINFO>()
};
if (!GetMonitorInfo(monitor, ref monitorInfo))
return;
var minMaxInfo = Marshal.PtrToStructure<MINMAXINFO>(lParam);
var workArea = monitorInfo.rcWork;
var monitorArea = monitorInfo.rcMonitor;
minMaxInfo.ptMaxPosition.x = workArea.left - monitorArea.left;
minMaxInfo.ptMaxPosition.y = workArea.top - monitorArea.top;
minMaxInfo.ptMaxSize.x = workArea.right - workArea.left;
minMaxInfo.ptMaxSize.y = workArea.bottom - workArea.top;
minMaxInfo.ptMaxTrackSize.x = minMaxInfo.ptMaxSize.x;
minMaxInfo.ptMaxTrackSize.y = minMaxInfo.ptMaxSize.y;
Marshal.StructureToPtr(minMaxInfo, lParam, false);
}
private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (ActiveFrame?.Content is HomePage home)
{
home.Filter(SearchBox.Text);
}
}
private void SelectButton_Click(object sender, RoutedEventArgs e)
{
if (ActiveFrame?.Content is HomePage home)
{
home.ToggleSelectionMode();
RefreshSelectButtonVisualState();
ShowToast(home.IsSelectionMode ? LocalizationService.Get("Main.SelectionEnabled") : LocalizationService.Get("Main.SelectionDisabled"), "\uE762");
return;
}
if (ActiveFrame?.Content is EditorPage editor)
{
editor.ToggleSelectionMode();
RefreshSelectButtonVisualState();
ShowToast(editor.IsSelectionMode ? LocalizationService.Get("Main.SelectionEnabled") : LocalizationService.Get("Main.SelectionDisabled"), "\uE762");
}
}
private void SortButton_Click(object sender, RoutedEventArgs e)
{
if (sender is Button btn && btn.ContextMenu != null)
{
btn.ContextMenu.IsOpen = true;
}
}
private void MoreButton_Click(object sender, RoutedEventArgs e)
{
if (sender is Button btn && btn.ContextMenu != null)
{
btn.ContextMenu.IsOpen = true;
}
}
private void SortByName_Click(object sender, RoutedEventArgs e)
{
if (ActiveFrame?.Content is HomePage home)
{
home.SortByName();
}
}
private void SortByDate_Click(object sender, RoutedEventArgs e)
{
if (ActiveFrame?.Content is HomePage home)
{
home.SortByDate();
}
}
private void Settings_Click(object sender, RoutedEventArgs e)
{
OpenSettingsDialog();
}
private async void About_Click(object sender, RoutedEventArgs e)
{
await DialogService.ShowInfoAsync(this, LocalizationService.Get("Main.AboutTitle"), LocalizationService.Get("Main.AboutMessage"));
}
// 鈹€鈹€鈹€ Toast 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
public async void ShowToast(string message, string icon = "\uE73E", int durationMs = 2500)
{
ToastIcon.Text = icon;
ToastText.Text = message;
ToastBorder.Visibility = Visibility.Visible;
var fadeIn = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(220));
fadeIn.EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut };
ToastBorder.BeginAnimation(OpacityProperty, fadeIn);
await Task.Delay(durationMs);
var fadeOut = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(350));
fadeOut.EasingFunction = new CubicEase { EasingMode = EasingMode.EaseIn };
fadeOut.Completed += (s, ev) => ToastBorder.Visibility = Visibility.Collapsed;
ToastBorder.BeginAnimation(OpacityProperty, fadeOut);
}
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr LoadImage(IntPtr hInst, string lpszName, int uType, int cxDesired, int cyDesired, int fuLoad);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
private static extern bool ChangeWindowMessageFilterEx(IntPtr hwnd, uint message, uint action, IntPtr pChangeFilterStruct);
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);
// 鈹€鈹€鈹€ Acrylic Blur (Glassmorphism) 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
[DllImport("user32.dll")]
private static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct MONITORINFO
{
public int cbSize;
public RECT rcMonitor;
public RECT rcWork;
public int dwFlags;
}
[StructLayout(LayoutKind.Sequential)]
private struct WindowCompositionAttributeData
{
public int Attribute;
public IntPtr Data;
public int SizeOfData;
}
[StructLayout(LayoutKind.Sequential)]
private struct AccentPolicy
{
public int AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
private void EnableAcrylicBlur(IntPtr handle)
{
// Solid white background — no acrylic/DWM backdrop needed
int backdropType = 1; // DWMWCP_DEFAULT
DwmSetWindowAttribute(handle, 38, ref backdropType, Marshal.SizeOf(typeof(int)));
}
}
}