-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
2094 lines (1837 loc) · 80.9 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
2094 lines (1837 loc) · 80.9 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
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.Controls;
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;
private bool _windowCloseWorkflowActive;
private bool _allowWindowClose;
private bool _navigationWorkflowActive;
private readonly HashSet<AppTab> _tabCloseWorkflows = new HashSet<AppTab>();
// A Frame navigation journal can keep an EditorPage behind a HomePage.
// Track every editor seen by that frame so tab/window close releases
// hidden native documents as well as the currently visible content.
private readonly Dictionary<Frame, HashSet<EditorPage>> _frameEditors =
new Dictionary<Frame, HashSet<EditorPage>>();
private CancellationTokenSource _windowCloseCts;
private CancellationTokenSource _toastCts;
private CancellationTokenSource _updateCheckCts;
private readonly UpdateCheckService _updateCheckService = new UpdateCheckService();
private bool _isUpdateCheckInProgress;
private static readonly TimeSpan CloseWorkflowTimeout = TimeSpan.FromSeconds(30);
public MainWindow()
: this(createHomeTab: true)
{
}
internal MainWindow(bool createHomeTab)
{
InitializeComponent();
LoadAppIcon();
TabDragCoordinator.Register(this);
SourceInitialized += MainWindow_SourceInitialized;
StateChanged += MainWindow_StateChanged;
Deactivated += MainWindow_Deactivated;
KeyDown += MainWindow_KeyDown;
TitleBarBorder.MouseLeftButtonDown += (sender, args) => DragMove();
LocalizationService.LanguageChanged += LocalizationService_LanguageChanged;
Closed += (_, __) =>
{
_updateCheckCts?.Cancel();
Deactivated -= MainWindow_Deactivated;
LocalizationService.LanguageChanged -= LocalizationService_LanguageChanged;
TabDragCoordinator.Unregister(this);
TabBar.DragOver -= TabBar_DragOver;
TabBar.Drop -= TabBar_Drop;
PopupZOrderHelper.UnfixContextMenuTopmost(SortContextMenu);
PopupZOrderHelper.UnfixContextMenuTopmost(MoreContextMenu);
};
var startupSettings = AppSettingsService.Load();
ThemeService.Apply(startupSettings.Theme, workspaceBackdrop: startupSettings.WorkspaceBackdrop);
ApplyLocalization();
// Popups must not float above other applications after Alt-Tab (Task 10)
PopupZOrderHelper.FixContextMenuTopmost(SortContextMenu);
PopupZOrderHelper.FixContextMenuTopmost(MoreContextMenu);
TabBar.AllowDrop = true;
TabBar.DragOver += TabBar_DragOver;
TabBar.Drop += TabBar_Drop;
Stylus.SetIsPressAndHoldEnabled(CloseButton, false);
Stylus.SetIsFlicksEnabled(CloseButton, false);
// The normal application window starts with Home. Detached
// windows receive an existing AppTab after construction so the
// original Frame/editor state is preserved.
if (createHomeTab)
AddNewHomeTab(activate: true);
}
private void LocalizationService_LanguageChanged(object sender, EventArgs e)
{
ApplyLocalization();
}
private void MainWindow_Deactivated(object sender, EventArgs e)
{
SortContextMenu.IsOpen = false;
MoreContextMenu.IsOpen = false;
// Popup HWNDs are detached from the Frame visual tree. Sweep every
// retained editor (including journal entries hidden behind Home)
// so an OpenNotes popup can never remain above another app.
var editors = _frameEditors.Values
.SelectMany(editorsForFrame => editorsForFrame)
.Concat(_tabs.SelectMany(tab => GetFrameEditors(tab.Frame)))
.Distinct()
.ToList();
foreach (var editor in editors)
{
editor.CancelInteraction("window deactivated");
editor.CloseTransientUi("window deactivated");
}
}
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", ".doc", ".docx", ".docm" };
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(WordDocumentImport.IsImportablePath);
}
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 (IsTabDragOverTabStrip(e))
return;
if (TabDragCoordinator.TryGetPayload(e.Data, out _))
{
e.Effects = DragDropEffects.Move;
e.Handled = true;
return;
}
if (ShouldDeferWindowFileDrop(e))
return;
e.Effects = HasSupportedFiles(e) ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
private void Window_DragOver(object sender, DragEventArgs e)
{
if (IsTabDragOverTabStrip(e))
return;
if (TabDragCoordinator.TryGetPayload(e.Data, out _))
{
e.Effects = DragDropEffects.Move;
e.Handled = true;
return;
}
if (ShouldDeferWindowFileDrop(e))
return;
e.Effects = HasSupportedFiles(e) ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
private async void Window_Drop(object sender, DragEventArgs e)
{
if (IsTabDragOverTabStrip(e) || TabDragCoordinator.TryGetPayload(e.Data, out _))
return;
if (ShouldDeferWindowFileDrop(e))
return;
if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files == null) return;
var importableFiles = files.Where(WordDocumentImport.IsImportablePath).ToList();
if (importableFiles.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 importableFiles)
{
var pdfPath = await TryImportDroppedDocumentAsync(file);
if (string.IsNullOrWhiteSpace(pdfPath))
continue;
if (first && isHomePage)
{
// Open directly in the current Home tab
NavigateActiveTabToFile(pdfPath);
first = false;
}
else
{
OpenFileInNewTab(pdfPath);
first = false;
}
}
e.Handled = true;
}
private async Task<string> TryImportDroppedDocumentAsync(string path)
{
if (WordDocumentImport.IsPdfPath(path))
return path;
if (!WordDocumentImport.IsWordPath(path))
return null;
ShowToast(LocalizationService.Get("Home.ConvertingWord"), "\uE8B7");
var previousCursor = Mouse.OverrideCursor;
Mouse.OverrideCursor = Cursors.Wait;
try
{
return await WordToPdfConverter.Default.ImportAsync(path);
}
catch (WordConverterNotFoundException)
{
await DialogService.ShowErrorAsync(
this,
LocalizationService.Get("Common.Error"),
LocalizationService.Get("Home.WordConverterMissing"));
return null;
}
catch (Exception ex)
{
await DialogService.ShowErrorAsync(
this,
LocalizationService.Get("Common.Error"),
LocalizationService.Format("Home.WordConvertFailed", Path.GetFileName(path), ex.Message));
return null;
}
finally
{
Mouse.OverrideCursor = previousCursor;
}
}
private bool IsTabDragOverTabStrip(DragEventArgs e)
{
return TabDragCoordinator.TryGetPayload(e.Data, out _) &&
IsDescendantOf(e.OriginalSource as DependencyObject, TabBar);
}
// 鈹€鈹€鈹€ Tab Management 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
private Frame ActiveFrame => _activeTab?.Frame;
internal bool IsActiveContent(object content) => ReferenceEquals(ActiveFrame?.Content, content);
private IReadOnlyList<EditorPage> GetFrameEditors(Frame frame)
{
return frame != null && _frameEditors.TryGetValue(frame, out var editors)
? editors.ToList()
: Array.Empty<EditorPage>();
}
public void AddNewHomeTab(bool activate = true)
{
var tab = new AppTab { Title = GetHomeTabTitle(), Icon = "Home" };
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);
}
private sealed class TabTransferState
{
public AppTab Tab { get; set; }
public Frame Frame { get; set; }
public HashSet<EditorPage> Editors { get; set; }
public int SourceIndex { get; set; }
public bool WasActive { get; set; }
}
/// <summary>
/// Removes a tab from this window without closing or recreating its
/// Frame. The editor map and Navigated subscription travel with the
/// same transfer transaction and are each moved exactly once.
/// </summary>
private bool TransferTabTo(
MainWindow destination,
AppTab tab,
AppTab targetTab,
bool insertAfter,
TabDragPayload payload)
{
if (destination == null || destination == this || tab == null ||
!_tabs.Contains(tab) || tab.Frame == null ||
_windowCloseWorkflowActive || _navigationWorkflowActive ||
_tabCloseWorkflows.Count > 0 ||
destination._windowCloseWorkflowActive || destination._navigationWorkflowActive ||
destination._tabCloseWorkflows.Count > 0)
{
return false;
}
if (payload != null && !ReferenceEquals(payload.Tab, tab))
return false;
if (ReferenceEquals(tab, _activeTab) && tab.Frame.Content is EditorPage activeEditor)
{
activeEditor.CancelInteraction("tab transfer");
activeEditor.CloseTransientUi("tab transfer");
activeEditor.SetHostActive(false);
}
var state = RemoveTabForTransfer(tab);
if (state == null)
return false;
try
{
if (!destination.AttachTransferredTab(state, targetTab, insertAfter))
{
RestoreTabAfterTransferFailure(state);
return false;
}
CompleteSourceTransfer(state);
if (payload != null)
TabDragCoordinator.AcceptDrop(payload);
return true;
}
catch
{
RestoreTabAfterTransferFailure(state);
return false;
}
}
private TabTransferState RemoveTabForTransfer(AppTab tab)
{
int sourceIndex = _tabs.IndexOf(tab);
if (sourceIndex < 0 || tab.Frame == null)
return null;
var frame = tab.Frame;
var editors = _frameEditors.TryGetValue(frame, out var knownEditors)
? knownEditors
: new HashSet<EditorPage>();
_frameEditors.Remove(frame);
frame.Navigated -= Frame_Navigated;
TabContentArea.Children.Remove(frame);
bool wasActive = ReferenceEquals(tab, _activeTab);
_tabs.RemoveAt(sourceIndex);
tab.IsActive = false;
frame.Visibility = Visibility.Collapsed;
if (wasActive)
_activeTab = null;
RebuildTabBar();
return new TabTransferState
{
Tab = tab,
Frame = frame,
Editors = editors,
SourceIndex = sourceIndex,
WasActive = wasActive
};
}
private bool AttachTransferredTab(TabTransferState state, AppTab targetTab, bool insertAfter)
{
if (state?.Tab == null || state.Frame == null || _tabs.Contains(state.Tab) ||
_windowCloseWorkflowActive || _navigationWorkflowActive || _tabCloseWorkflows.Count > 0)
{
return false;
}
int insertIndex = _tabs.Count;
if (targetTab != null)
{
int targetIndex = _tabs.IndexOf(targetTab);
if (targetIndex < 0)
return false;
insertIndex = targetIndex + (insertAfter ? 1 : 0);
}
state.Frame.Navigated += Frame_Navigated;
try
{
TabContentArea.Children.Add(state.Frame);
// This assignment is the destination half of the one-time
// map move performed by RemoveTabForTransfer.
_frameEditors[state.Frame] = state.Editors ?? new HashSet<EditorPage>();
_tabs.Insert(Math.Min(insertIndex, _tabs.Count), state.Tab);
state.Tab.IsActive = false;
state.Frame.Visibility = Visibility.Collapsed;
RebuildTabBar();
ActivateTab(state.Tab);
return true;
}
catch
{
state.Frame.Navigated -= Frame_Navigated;
_frameEditors.Remove(state.Frame);
TabContentArea.Children.Remove(state.Frame);
_tabs.Remove(state.Tab);
return false;
}
}
private void CompleteSourceTransfer(TabTransferState state)
{
if (_tabs.Count == 0)
{
// A source window remains usable after its last tab moves.
AddNewHomeTab(activate: true);
}
else if (state.WasActive)
{
int nextIndex = Math.Min(state.SourceIndex, _tabs.Count - 1);
ActivateTab(_tabs[nextIndex]);
}
else
{
RebuildTabBar();
UpdateNavButtons();
}
}
private void RestoreTabAfterTransferFailure(TabTransferState state)
{
if (state?.Tab == null || state.Frame == null || _tabs.Contains(state.Tab))
return;
state.Frame.Navigated += Frame_Navigated;
TabContentArea.Children.Add(state.Frame);
_frameEditors[state.Frame] = state.Editors ?? new HashSet<EditorPage>();
int insertIndex = Math.Max(0, Math.Min(state.SourceIndex, _tabs.Count));
_tabs.Insert(insertIndex, state.Tab);
state.Frame.Visibility = Visibility.Collapsed;
state.Tab.IsActive = false;
RebuildTabBar();
if (state.WasActive)
{
_activeTab = null;
ActivateTab(state.Tab);
}
else
{
UpdateNavButtons();
}
}
private void DetachTabToNewWindow(AppTab tab)
{
if (tab == null || !_tabs.Contains(tab))
return;
var detached = new MainWindow(createHomeTab: false)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Width = Width,
Height = Height,
Left = Left + 32,
Top = Top + 32
};
detached.Show();
if (!TransferTabTo(detached, tab, targetTab: null, insertAfter: true, payload: null))
{
detached._allowWindowClose = true;
detached.Close();
return;
}
detached.Activate();
}
public void OpenFileInNewTab(string filePath, bool promptSaveAsAfterLoad = false, string pendingLibraryFolderId = null, bool isNotebookDraft = false)
{
if (_windowCloseWorkflowActive || _navigationWorkflowActive || _tabCloseWorkflows.Count > 0)
return;
RecentFilesService.AddOrPromote(filePath);
var name = Path.GetFileNameWithoutExtension(filePath);
string icon = "FileText";
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 (_windowCloseWorkflowActive || _navigationWorkflowActive || _tabCloseWorkflows.Count > 0)
return;
if (_activeTab == tab) return;
if (_activeTab?.Frame?.Content is EditorPage previousEditor)
{
previousEditor.CloseTransientUi("tab switch");
previousEditor.SetHostActive(false);
}
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;
if (tab.Frame.Content is EditorPage activeEditor)
{
activeEditor.SetHostActive(WindowState != WindowState.Minimized);
if (WindowState != WindowState.Minimized)
activeEditor.ResumeDocumentInteraction();
}
UpdateNavButtons();
RefreshTabBarChrome();
RefreshSelectButtonVisualState();
}
private void ReleasePointerCapturesForChrome()
{
Mouse.Capture(null);
Stylus.Capture(null);
if (ActiveFrame?.Content is EditorPage editor)
editor.CancelInteraction("chrome pointer");
}
private void ChromeButton_PreviewStylusDown(object sender, StylusDownEventArgs e)
{
ReleasePointerCapturesForChrome();
if (sender is not Button button)
return;
e.Handled = true;
button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
private async void CloseTab(AppTab tab)
{
if (tab == null || !_tabs.Contains(tab))
return;
if (_windowCloseWorkflowActive || _navigationWorkflowActive || !_tabCloseWorkflows.Add(tab))
return;
ReleasePointerCapturesForChrome();
// A tab is not removed until the editor has persisted its newest
// generation and released native resources. A failed save keeps
// the tab/document alive for recovery.
EditorPage activeEditor = null;
var preparedEditors = new List<EditorPage>();
bool releaseStarted = false;
bool releaseHandoff = false;
try
{
using var timeout = new CancellationTokenSource(CloseWorkflowTimeout);
var editors = GetFrameEditors(tab.Frame).ToList();
if (tab.Frame?.Content is EditorPage currentEditor && !editors.Contains(currentEditor))
editors.Add(currentEditor);
foreach (var editor in editors)
{
activeEditor = editor;
bool wasDirty = editor.IsDirty;
if (!await editor.PrepareForCloseAsync(timeout.Token).WaitAsync(timeout.Token))
{
foreach (var prepared in preparedEditors)
prepared.CancelClosePreparation();
return;
}
if (wasDirty)
ShowToast(LocalizationService.Get("Main.FileAutoSaved"));
preparedEditors.Add(editor);
}
for (int releaseIndex = 0; releaseIndex < preparedEditors.Count; releaseIndex++)
{
var editor = preparedEditors[releaseIndex];
activeEditor = editor;
releaseStarted = true;
Task<bool> releaseTask = editor.ReleaseResourcesAsync();
bool releaseCompleted;
try
{
releaseCompleted = await releaseTask.WaitAsync(timeout.Token);
}
catch (OperationCanceledException) when (!releaseTask.IsCompleted)
{
// The underlying release is deliberately not aborted
// mid-disposal. Leave the editor admitted as busy so
// a later close attempt can join and finish it.
releaseHandoff = true;
_ = ContinueTimedOutTabCloseAsync(
tab,
preparedEditors.ToList(),
releaseIndex,
releaseTask);
ShowToast(LocalizationService.Get("Editor.SaveFailed"), "\uE783", 3500);
return;
}
if (!releaseCompleted)
{
editor.CancelClosePreparation();
return;
}
}
RemoveTabAfterResourcesReleased(tab);
}
catch (Exception ex)
{
if (!releaseStarted)
{
foreach (var prepared in preparedEditors)
prepared.CancelClosePreparation();
activeEditor?.CancelClosePreparation();
}
ShowToast(LocalizationService.Format("Editor.SaveFailed", ex.Message), "\uE783", 3500);
}
finally
{
if (!releaseHandoff)
_tabCloseWorkflows.Remove(tab);
}
}
/// <summary>
/// Completes a tab close after the UI timeout stopped waiting. The
/// workflow marker remains installed until every native release task
/// has actually settled, so ActivateTab/re-close cannot re-enter a
/// partially disposed editor.
/// </summary>
private async Task ContinueTimedOutTabCloseAsync(
AppTab tab,
IReadOnlyList<EditorPage> preparedEditors,
int releaseIndex,
Task<bool> releaseTask)
{
try
{
if (!await releaseTask.ConfigureAwait(false))
throw new InvalidOperationException("The document release did not complete.");
for (int i = releaseIndex + 1; i < preparedEditors.Count; i++)
{
if (!await preparedEditors[i].ReleaseResourcesAsync().ConfigureAwait(false))
throw new InvalidOperationException("The document release did not complete.");
}
await Dispatcher.InvokeAsync(
() => RemoveTabAfterResourcesReleased(tab),
System.Windows.Threading.DispatcherPriority.ApplicationIdle);
}
catch (Exception ex)
{
await Dispatcher.InvokeAsync(
() =>
{
ShowToast(LocalizationService.Format("Editor.SaveFailed", ex.Message), "\uE783", 3500);
// Editors after the failed release were only prepared,
// never admitted to native cleanup. Re-open their
// input/autosave admission, while the failed/current
// release remains blocked for an explicit retry.
for (int i = releaseIndex + 1; i < preparedEditors.Count; i++)
preparedEditors[i].CancelClosePreparation();
},
System.Windows.Threading.DispatcherPriority.ApplicationIdle);
// ReleaseResourcesAsync retains the editor's blocked/failed
// state. Removing only the workflow marker permits an
// explicit retry without enabling the editor implicitly.
await Dispatcher.InvokeAsync(
() => _tabCloseWorkflows.Remove(tab),
System.Windows.Threading.DispatcherPriority.ApplicationIdle);
}
}
private void RemoveTabAfterResourcesReleased(AppTab tab)
{
if (tab?.Frame == null || !_tabs.Contains(tab))
return;
tab.Frame.Navigated -= Frame_Navigated;
TabContentArea.Children.Remove(tab.Frame);
_tabs.Remove(tab);
_frameEditors.Remove(tab.Frame);
_tabCloseWorkflows.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 void RefreshTabBarChrome()
{
if (TabBar.Children.Count != _tabs.Count)
{
RebuildTabBar();
return;
}
for (int i = 0; i < _tabs.Count; i++)
{
if (TabBar.Children[i] is not Border border || !ReferenceEquals(border.Tag, _tabs[i]))
{
RebuildTabBar();
return;
}
ApplyTabChrome(border, _tabs[i]);
}
}
private void ApplyTabChrome(Border border, AppTab tab)
{
bool isActive = tab == _activeTab;
var transparentBackground = Brushes.Transparent;
if (border.Child is not StackPanel panel)
return;
LucideIcon icon = null;
TextBlock title = null;
Button closeBtn = null;
foreach (var child in panel.Children)
{
if (child is LucideIcon lucide)
icon = lucide;
else if (child is TextBlock text)
title = text;
else if (child is Button button)
closeBtn = button;
}
if (isActive)
{
UseThemeBrush(border, Border.BackgroundProperty, "ThemeSurfaceAltBrush");
UseThemeBrush(border, Border.BorderBrushProperty, "ThemeBorderBrush");
border.BorderThickness = new Thickness(1);
}
else
{
border.Background = transparentBackground;
border.BorderBrush = transparentBackground;
border.BorderThickness = new Thickness(0);
}
if (icon != null)
UseThemeBrush(icon, System.Windows.Shapes.Shape.StrokeProperty, isActive ? "ThemeForegroundBrush" : "ThemeSubtleForegroundBrush");
if (title != null)
{
title.Text = tab.Title.Length > 20 ? tab.Title.Substring(0, 17) + "..." : tab.Title;
title.FontWeight = isActive ? FontWeights.Medium : FontWeights.Normal;
UseThemeBrush(title, TextBlock.ForegroundProperty, isActive ? "ThemeForegroundBrush" : "ThemeSubtleForegroundBrush");
}
if (closeBtn != null)
{
closeBtn.Visibility = _tabs.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
closeBtn.Opacity = isActive ? 1 : 0.72;
}
border.ToolTip = tab.Title;
}
private static Brush GetThemeBrush(string key, Brush fallback)
{
return Application.Current?.TryFindResource(key) as Brush ?? fallback;
}
private static void UseThemeBrush(FrameworkElement element, DependencyProperty property, string key)
{
if (element == null || Application.Current?.TryFindResource(key) == null)
return;
// Keep a DynamicResource expression so an in-place settings preview
// updates existing tab chrome when ThemeService swaps the palette.
element.SetResourceReference(property, key);
}
private Border CreateTabButton(AppTab tab)
{
bool isActive = tab == _activeTab;
var activeForeground = GetThemeBrush("ThemeForegroundBrush", SystemColors.ControlTextBrush);
var inactiveForeground = GetThemeBrush("ThemeSubtleForegroundBrush", SystemColors.GrayTextBrush);
var activeBackground = GetThemeBrush("ThemeSurfaceAltBrush", SystemColors.WindowBrush);
var activeBorderBrush = GetThemeBrush("ThemeBorderBrush", SystemColors.ActiveBorderBrush);
var transparentBackground = Brushes.Transparent;
// Tab content: icon + title + close button
var icon = new LucideIcon
{
Kind = tab.Icon,
Width = 14,
Height = 14,
Stroke = isActive ? activeForeground : inactiveForeground,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0)
};
UseThemeBrush(icon, System.Windows.Shapes.Shape.StrokeProperty, isActive ? "ThemeForegroundBrush" : "ThemeSubtleForegroundBrush");
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
};
UseThemeBrush(title, TextBlock.ForegroundProperty, isActive ? "ThemeForegroundBrush" : "ThemeSubtleForegroundBrush");
var closeIcon = new LucideIcon
{
Kind = "X",
Width = 12,
Height = 12,
Stroke = inactiveForeground
};
UseThemeBrush(closeIcon, System.Windows.Shapes.Shape.StrokeProperty, "ThemeSubtleForegroundBrush");
var closeBtn = new Button
{
Content = closeIcon,
Width = 32,
Height = 32,
Background = transparentBackground,
BorderThickness = new Thickness(0),
Cursor = Cursors.Hand,
Margin = new Thickness(2, 0, -4, 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 DynamicResourceExtension("ThemeControlHoverBrush"),
"CloseBg"));
closeBtnTemplate.Triggers.Add(hoverTrigger);
closeBtn.Template = closeBtnTemplate;
var capturedTab = tab;
Stylus.SetIsPressAndHoldEnabled(closeBtn, false);
Stylus.SetIsFlicksEnabled(closeBtn, false);
closeBtn.PreviewMouseLeftButtonDown += (s, e) =>
{
e.Handled = true;
CloseTab(capturedTab);
};
closeBtn.PreviewStylusDown += (s, e) =>
{
e.Handled = true;
CloseTab(capturedTab);
};
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,
Tag = tab,
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,
Focusable = true,
ToolTip = tab.Title,
Cursor = Cursors.Hand,
SnapsToDevicePixels = true
};
KeyboardNavigation.SetIsTabStop(border, true);
if (isActive)
{
UseThemeBrush(border, Border.BackgroundProperty, "ThemeSurfaceAltBrush");
UseThemeBrush(border, Border.BorderBrushProperty, "ThemeBorderBrush");
}
border.MouseEnter += (s, e) =>
{
if (capturedTab != _activeTab)
{
UseThemeBrush(border, Border.BackgroundProperty, "ThemeControlHoverBrush");
}
closeBtn.Opacity = 1;
};
border.MouseLeave += (s, e) =>
{
if (capturedTab != _activeTab)
{