Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
780 lines (649 loc) · 28.1 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
780 lines (649 loc) · 28.1 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
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Win32;
using OneNoteExporter.Helpers;
using OneNoteExporter.Models;
using OneNoteExporter.Services;
namespace OneNoteExporter;
public partial class MainWindow : Window
{
// ── State ────────────────────────────────────────────────────────────────
private OneNoteComWorker? _service;
private CancellationTokenSource? _exportCts;
private bool _exportInProgress = false;
private bool _isLocalBackupMode = false;
private readonly ObservableCollection<NotebookViewModel> _notebooks = new();
// ── Startup / Shutdown ───────────────────────────────────────────────────
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
NotebookList.ItemsSource = _notebooks;
await InitOneNoteServiceAsync();
UpdateLocalBackupOption();
await LoadNotebooksAsync();
var defaultPath = FileHelper.GetDefaultDownloadsPath();
DestPathBox.Text = Path.Combine(defaultPath, "OneNote-Export");
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_exportCts?.Cancel();
_service?.Dispose();
}
// ── OneNote initialisation ───────────────────────────────────────────────
private async Task InitOneNoteServiceAsync()
{
SetVersionBadge("Checking OneNote installation...", StatusKind.Info);
try
{
_service = await OneNoteComWorker.CreateAsync();
var info = await _service.GetVersionInfoAsync();
if (info.OneNoteInstalled)
SetVersionBadge($"✓ {info.OneNoteVersion}", StatusKind.Success);
else
SetVersionBadge("⚠ OneNote Desktop not found", StatusKind.Warning);
}
catch (Exception ex)
{
_service = null;
SetVersionBadge(
$"⚠ {UserFacingError.Describe(ex, "OneNote Desktop connection failed.")}",
StatusKind.Error);
}
}
// ── Notebook loading ─────────────────────────────────────────────────────
private async Task LoadNotebooksAsync()
{
_notebooks.Clear();
ShowNotebookOverlay(OverlayKind.Loading);
try
{
if (_service == null)
throw new InvalidOperationException("OneNote Helper is not available.");
var list = await _service.GetNotebooksAsync();
ShowNotebookOverlay(OverlayKind.None);
if (list.Count == 0)
{
ShowNotebookOverlay(OverlayKind.Empty);
return;
}
foreach (var nb in list)
_notebooks.Add(new NotebookViewModel(nb));
// Re-apply localbackup UI state if that format is selected
if (GetSelectedFormat() == "localbackup")
ApplyLocalBackupMode(enable: true);
}
catch (Exception ex)
{
ShowNotebookOverlay(
OverlayKind.Error,
UserFacingError.Describe(
ex,
"Notebooks could not be loaded. Open OneNote Desktop and try again."));
}
UpdateExportButtonState();
}
// ── UI helpers ───────────────────────────────────────────────────────────
private string GetSelectedFormat()
{
if (FormatCombo.SelectedItem is ComboBoxItem item)
return item.Tag?.ToString() ?? "onepkg";
return "onepkg";
}
private static bool IsRenderedFormat(string format)
=> format.Equals("pdf", StringComparison.OrdinalIgnoreCase) ||
format.Equals("xps", StringComparison.OrdinalIgnoreCase);
private void UpdateRenderedFormatWarning(string format)
{
bool isRenderedFormat = IsRenderedFormat(format);
RenderedFormatWarning.Visibility = isRenderedFormat
? Visibility.Visible
: Visibility.Collapsed;
if (!isRenderedFormat) return;
string formatName = format.Equals("pdf", StringComparison.OrdinalIgnoreCase)
? "PDF"
: "XPS";
RenderedFormatWarningText.Text =
$"⚠ Whole-notebook {formatName} exports can fail in OneNote for large notebooks. " +
"Before export, the app will offer the safer section-by-section mode.";
}
private void UpdateExportButtonState()
{
if (GetSelectedFormat() == "localbackup") return; // handled by ApplyLocalBackupMode
// Notebooks selected for whole-notebook export
// (a notebook that has any section selected is handled at section level instead)
int notebookCount = _notebooks.Count(nb => nb.IsSelected && !nb.Sections.Any(s => s.IsSelected));
int sectionCount = _notebooks.Sum(nb => nb.Sections.Count(s => s.IsSelected));
bool hasAny = notebookCount > 0 || sectionCount > 0;
ExportButton.IsEnabled = hasAny && !_exportInProgress;
ExportButton.Content = (notebookCount, sectionCount) switch
{
(0, 0) => "Export Selected",
(> 0, 0) => $"Export {notebookCount} notebook(s)",
(0, > 0) => $"Export {sectionCount} section(s)",
_ => $"Export {notebookCount} notebook(s) + {sectionCount} section(s)"
};
}
private void UpdateLocalBackupOption()
{
var avail = FileHelper.CheckLocalBackupAvailable();
if (avail.Available)
{
LocalBackupItem.Content = $"Local Backup Copy ({avail.NotebookCount} notebooks) – Fast, direct file copy";
LocalBackupItem.IsEnabled = true;
}
else
{
LocalBackupItem.Content = $"Local Backup Copy – Not available ({avail.Message})";
LocalBackupItem.IsEnabled = false;
}
}
private void ApplyLocalBackupMode(bool enable)
{
if (enable)
{
_isLocalBackupMode = true;
BackupWarning.Visibility = Visibility.Visible;
foreach (var nb in _notebooks)
{
nb.IsSelected = true;
nb.IsEnabled = false;
nb.IsExpanded = false;
foreach (var s in nb.Sections) s.IsSelected = false;
}
var avail = FileHelper.CheckLocalBackupAvailable();
ExportButton.Content = avail.Available
? $"Export ALL Notebooks ({avail.NotebookCount} total)"
: "Export ALL Notebooks";
ExportButton.IsEnabled = avail.Available;
}
else
{
bool wasLocalBackupMode = _isLocalBackupMode;
_isLocalBackupMode = false;
BackupWarning.Visibility = Visibility.Collapsed;
if (wasLocalBackupMode)
{
foreach (var nb in _notebooks)
{
nb.IsSelected = false;
nb.IsEnabled = true;
}
}
UpdateExportButtonState();
}
}
private void SetButtonsEnabled(bool enabled)
{
ExportButton.IsEnabled = enabled;
RefreshButton.IsEnabled = enabled;
BrowseButton.IsEnabled = enabled;
}
// ── Status display ───────────────────────────────────────────────────────
private enum StatusKind { Info, Success, Warning, Error }
private enum OverlayKind { None, Loading, Empty, Error }
private void SetVersionBadge(string text, StatusKind kind)
{
VersionText.Text = text;
(VersionBadge.Background, VersionBadge.BorderBrush, VersionText.Foreground) = kind switch
{
StatusKind.Success => (Brush(StaticRes("SuccessBg")), Brush(StaticRes("SuccessBorder")), Brush(StaticRes("SuccessFg"))),
StatusKind.Warning => (Brush(StaticRes("WarningBg")), Brush(StaticRes("WarningBorder")), Brush(StaticRes("WarningFg"))),
StatusKind.Error => (Brush(StaticRes("ErrorBg")), Brush(StaticRes("ErrorBorder")), Brush(StaticRes("ErrorFg"))),
_ => (Brush(StaticRes("InfoBg")), Brush(StaticRes("InfoBorder")), Brush(StaticRes("InfoFg")))
};
}
private void ShowNotebookOverlay(OverlayKind kind, string? errorMsg = null)
{
LoadingText.Visibility = kind == OverlayKind.Loading ? Visibility.Visible : Visibility.Collapsed;
EmptyText.Visibility = kind == OverlayKind.Empty ? Visibility.Visible : Visibility.Collapsed;
ErrorText.Visibility = kind == OverlayKind.Error ? Visibility.Visible : Visibility.Collapsed;
if (kind == OverlayKind.Error && errorMsg != null)
ErrorText.Text = errorMsg;
}
private void ShowProgress(string text)
{
ExportProgressBar.Visibility = Visibility.Visible;
ProgressArea.Visibility = Visibility.Visible;
ProgressText.Text = text;
StatusBorder.Visibility = Visibility.Collapsed;
}
private void UpdateProgressText(string text) => ProgressText.Text = text;
private void HideProgress()
{
ExportProgressBar.Visibility = Visibility.Collapsed;
ProgressArea.Visibility = Visibility.Collapsed;
}
private void ShowStatus(string text, StatusKind kind)
{
StatusText.Text = text;
StatusBorder.Visibility = Visibility.Visible;
(StatusBorder.Background, StatusBorder.BorderBrush, StatusText.Foreground) = kind switch
{
StatusKind.Success => (Brush(StaticRes("SuccessBg")), Brush(StaticRes("SuccessBorder")), Brush(StaticRes("SuccessFg"))),
StatusKind.Warning => (Brush(StaticRes("WarningBg")), Brush(StaticRes("WarningBorder")), Brush(StaticRes("WarningFg"))),
StatusKind.Error => (Brush(StaticRes("ErrorBg")), Brush(StaticRes("ErrorBorder")), Brush(StaticRes("ErrorFg"))),
_ => (Brush(StaticRes("InfoBg")), Brush(StaticRes("InfoBorder")), Brush(StaticRes("InfoFg")))
};
}
private void ClearStatus()
{
StatusBorder.Visibility = Visibility.Collapsed;
StatusText.Text = "";
}
// Resource helpers
private object StaticRes(string key) => FindResource(key);
private static SolidColorBrush Brush(object res) => (SolidColorBrush)res;
// ── Event handlers ───────────────────────────────────────────────────────
private async void RefreshButton_Click(object sender, RoutedEventArgs e)
{
foreach (var nb in _notebooks) nb.IsSelected = false;
await LoadNotebooksAsync();
}
private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// OpenFolderDialog is available in WPF on .NET 8+ (Windows)
var dialog = new OpenFolderDialog
{
Title = "Select Destination Folder",
InitialDirectory = FileHelper.GetDefaultDownloadsPath()
};
if (dialog.ShowDialog(this) == true)
{
DestPathBox.Text = dialog.FolderName;
ShowStatus($"Path selected: {dialog.FolderName}", StatusKind.Info);
}
}
private void FormatCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Guard: may fire before UI is fully initialised
if (BackupWarning == null) return;
string format = GetSelectedFormat();
bool isLocalBackup = format == "localbackup";
ApplyLocalBackupMode(isLocalBackup);
UpdateRenderedFormatWarning(format);
}
private void Notebook_SelectionChanged(object sender, RoutedEventArgs e)
=> UpdateExportButtonState();
private void Section_SelectionChanged(object sender, RoutedEventArgs e)
=> UpdateExportButtonState();
private void AboutButton_Click(object sender, RoutedEventArgs e)
{
var aboutWindow = new AboutWindow { Owner = this };
aboutWindow.ShowDialog();
}
private async void ExpandSections_Click(object sender, RoutedEventArgs e)
{
if (sender is not Button btn || btn.DataContext is not NotebookViewModel nb) return;
nb.IsExpanded = !nb.IsExpanded;
if (nb.IsExpanded && !nb.HasSectionsLoaded)
await LoadSectionsAsync(nb);
}
private async Task<bool> LoadSectionsAsync(
NotebookViewModel nb,
CancellationToken ct = default)
{
if (_service == null) return false;
nb.IsLoadingSections = true;
try
{
var sections = await _service.GetSectionsAsync(nb.Id, ct);
ct.ThrowIfCancellationRequested();
nb.Sections.Clear();
foreach (var s in sections)
nb.Sections.Add(new SectionViewModel(s));
nb.HasSectionsLoaded = true;
return true;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
ShowStatus(
UserFacingError.Describe(
ex,
$"Sections for '{nb.Name}' could not be loaded."),
StatusKind.Error);
return false;
}
finally
{
nb.IsLoadingSections = false; // fires SectionsEmpty + IsSectionsContentVisible
}
}
private async Task<bool> ConvertNotebookJobsToSectionsAsync(
List<NotebookViewModel> notebookJobs,
List<(NotebookViewModel Notebook, SectionViewModel Section)> sectionJobs,
string format,
CancellationToken ct)
{
int notebookIndex = 0;
foreach (var notebook in notebookJobs)
{
ct.ThrowIfCancellationRequested();
notebookIndex++;
ShowProgress(
$"Preparing safer {format.ToUpperInvariant()} export...\n" +
$"Loading sections for notebook {notebookIndex}/{notebookJobs.Count}: " +
notebook.Name);
if (!notebook.HasSectionsLoaded && !await LoadSectionsAsync(notebook, ct))
{
HideProgress();
return false;
}
if (notebook.Sections.Count == 0)
{
HideProgress();
ShowStatus(
$"No exportable sections were found in '{notebook.Name}'. " +
"Use a OneNote package for a complete backup.",
StatusKind.Warning);
return false;
}
ct.ThrowIfCancellationRequested();
foreach (var section in notebook.Sections)
{
bool alreadyQueued = sectionJobs.Any(job => job.Section.Id == section.Id);
if (!alreadyQueued)
sectionJobs.Add((notebook, section));
}
}
notebookJobs.Clear();
return true;
}
private async Task<(bool Continue, string Format)> ApplyRenderedExportGuardAsync(
List<NotebookViewModel> notebookJobs,
List<(NotebookViewModel Notebook, SectionViewModel Section)> sectionJobs,
string format,
CancellationToken ct)
{
if (!IsRenderedFormat(format) || notebookJobs.Count == 0)
return (true, format);
var warningWindow = new RenderedExportWarningWindow(
format,
sectionJobs.Count > 0)
{
Owner = this
};
warningWindow.ShowDialog();
switch (warningWindow.Choice)
{
case RenderedExportChoice.IndividualSections:
bool converted = await ConvertNotebookJobsToSectionsAsync(
notebookJobs, sectionJobs, format, ct);
return (converted, format);
case RenderedExportChoice.OneNotePackage:
SelectFormat("onepkg");
return (true, "onepkg");
case RenderedExportChoice.WholeNotebook:
return (true, format);
default:
return (false, format);
}
}
private void SelectFormat(string format)
{
var item = FormatCombo.Items
.OfType<ComboBoxItem>()
.FirstOrDefault(candidate => string.Equals(
candidate.Tag?.ToString(), format, StringComparison.OrdinalIgnoreCase));
if (item != null)
FormatCombo.SelectedItem = item;
}
private async void ExportButton_Click(object sender, RoutedEventArgs e)
{
if (_exportInProgress)
{
ShowStatus("⚠ An export is already running! Please wait until it is completed.", StatusKind.Warning);
return;
}
var destPath = DestPathBox.Text.Trim();
if (string.IsNullOrEmpty(destPath))
{
ShowStatus("Please specify a destination folder.", StatusKind.Error);
return;
}
var format = GetSelectedFormat();
// For COM export: build separate job lists for notebooks and sections.
// Rule: if a notebook has any selected sections, export those sections individually
// (the notebook-level checkbox is ignored for that notebook).
List<NotebookViewModel>? notebookJobs = null;
List<(NotebookViewModel Notebook, SectionViewModel Section)>? sectionJobs = null;
if (format != "localbackup")
{
notebookJobs = _notebooks
.Where(nb => nb.IsSelected && !nb.Sections.Any(s => s.IsSelected))
.ToList();
sectionJobs = _notebooks
.SelectMany(nb => nb.Sections
.Where(s => s.IsSelected)
.Select(s => (Notebook: nb, Section: s)))
.ToList();
if (notebookJobs.Count == 0 && sectionJobs.Count == 0)
{
ShowStatus("Please select at least one notebook or section.", StatusKind.Error);
return;
}
}
// Lock UI
_exportInProgress = true;
_exportCts = new CancellationTokenSource();
CancelButton.Visibility = Visibility.Visible;
SetButtonsEnabled(false);
ClearStatus();
try
{
if (format == "localbackup")
await RunLocalBackupAsync(destPath, _exportCts.Token);
else
{
var prepared = await ApplyRenderedExportGuardAsync(
notebookJobs!, sectionJobs!, format, _exportCts.Token);
if (!prepared.Continue)
return;
_exportCts.Token.ThrowIfCancellationRequested();
await RunComExportAsync(
notebookJobs!, sectionJobs!, destPath, prepared.Format, _exportCts.Token);
}
}
catch (OperationCanceledException)
{
HideProgress();
ShowStatus("Export cancelled.", StatusKind.Warning);
}
finally
{
_exportInProgress = false;
CancelButton.Visibility = Visibility.Collapsed;
SetButtonsEnabled(true);
UpdateExportButtonState();
}
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
if (!_exportInProgress) return;
string cancellationDetails = _isLocalBackupMode
? "The export will stop safely after the current file copy finishes."
: "The export will stop safely without closing OneNote. If OneNote is currently " +
"rendering, cancellation completes as soon as OneNote returns control.";
var confirm = MessageBox.Show(
$"Do you really want to cancel the export?\n\n{cancellationDetails}",
"Cancel Export",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (confirm != MessageBoxResult.Yes) return;
ShowStatus("Cancelling export...", StatusKind.Warning);
_exportCts?.Cancel();
}
// ── Export implementations ───────────────────────────────────────────────
private async Task RunLocalBackupAsync(string destPath, CancellationToken ct)
{
ShowProgress("Copying local backup files...");
try
{
var result = await Task.Run(() => FileHelper.CopyLocalBackup(destPath, ct), ct);
HideProgress();
if (result.Success)
{
ShowStatus($"✓ Local backup successfully copied!\n\nExported to: {destPath}", StatusKind.Success);
FileHelper.OpenFolder(destPath);
}
else
{
ShowStatus($"❌ Export failed: {result.Message}", StatusKind.Error);
}
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
HideProgress();
ShowStatus(
$"❌ {UserFacingError.Describe(ex, "The local backup export could not be completed.")}",
StatusKind.Error);
}
}
private async Task RunComExportAsync(
List<NotebookViewModel> notebookJobs,
List<(NotebookViewModel Notebook, SectionViewModel Section)> sectionJobs,
string destPath,
string format,
CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (_service == null)
{
ShowStatus("OneNote Helper is not available. Please ensure OneNote Desktop is installed.", StatusKind.Error);
return;
}
// Auto-dismiss the OneNote sync-warning dialog ("Ja" / "Nein") if it appears
StartDialogWatcher(ct);
int successCount = 0, failCount = 0;
var messages = new List<string>();
int totalJobs = notebookJobs.Count + sectionJobs.Count;
int jobIndex = 0;
// ── Notebook-level exports ────────────────────────────────────────────
foreach (var nb in notebookJobs)
{
ct.ThrowIfCancellationRequested();
jobIndex++;
var label = $"Notebook {jobIndex}/{totalJobs}: {nb.Name}";
var progress = new Progress<string>(msg =>
UpdateProgressText($"{label}\n{msg}\nPlease be patient, this may take several minutes..."));
ShowProgress($"{label}\nStarting export...\nPlease be patient, this may take several minutes...");
try
{
var result = await _service.ExportNotebookAsync(
nb.Id, destPath, format, progress, ct);
if (result.Success)
{
successCount++;
string retryNote = result.RecoveredAfterRetry
? " (recovered after COM retry)"
: "";
messages.Add($"✓ {nb.Name}{retryNote}");
}
else { failCount++; messages.Add($"✗ {nb.Name}: {result.Message}"); }
}
catch (OperationCanceledException)
{
HideProgress();
ShowStatus("Export cancelled.", StatusKind.Warning);
return;
}
catch (Exception ex)
{
failCount++;
messages.Add(
$"✗ {nb.Name}: " +
UserFacingError.Describe(ex, "The export could not be completed."));
}
await Task.Delay(300, CancellationToken.None);
}
// ── Section-level exports ─────────────────────────────────────────────
foreach (var (nb, sec) in sectionJobs)
{
ct.ThrowIfCancellationRequested();
jobIndex++;
var label = $"Section {jobIndex}/{totalJobs}: {sec.Name} ({nb.Name})";
var progress = new Progress<string>(msg =>
UpdateProgressText($"{label}\n{msg}\nPlease be patient, this may take several minutes..."));
ShowProgress($"{label}\nStarting export...\nPlease be patient, this may take several minutes...");
try
{
var result = await _service.ExportSectionAsync(
sec.Info, destPath, format, progress, ct);
if (result.Success)
{
successCount++;
string retryNote = result.RecoveredAfterRetry
? " (recovered after COM retry)"
: "";
messages.Add($"✓ {nb.Name} / {sec.Name}{retryNote}");
}
else { failCount++; messages.Add($"✗ {nb.Name} / {sec.Name}: {result.Message}"); }
}
catch (OperationCanceledException)
{
HideProgress();
ShowStatus("Export cancelled.", StatusKind.Warning);
return;
}
catch (Exception ex)
{
failCount++;
messages.Add(
$"✗ {nb.Name} / {sec.Name}: " +
UserFacingError.Describe(ex, "The export could not be completed."));
}
await Task.Delay(300, CancellationToken.None);
}
HideProgress();
var finalMsg = $"Export completed: {successCount} successful, {failCount} failed\n\n" +
string.Join("\n", messages);
ShowStatus(finalMsg, failCount == 0 ? StatusKind.Success : StatusKind.Warning);
if (successCount > 0)
FileHelper.OpenFolder(destPath);
}
// ── Utilities ────────────────────────────────────────────────────────────
private void StartDialogWatcher(CancellationToken ct)
{
_ = Task.Run(() =>
{
while (!ct.IsCancellationRequested && _exportInProgress)
{
try
{
var allWindows = AutomationElement.RootElement.FindAll(
TreeScope.Children,
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window));
foreach (AutomationElement window in allWindows)
{
if (!window.Current.Name.Contains("OneNote", StringComparison.OrdinalIgnoreCase))
continue;
var jaButton = window.FindFirst(
TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button),
new PropertyCondition(AutomationElement.NameProperty, "Ja")));
if (jaButton != null &&
jaButton.TryGetCurrentPattern(InvokePattern.Pattern, out var pattern))
{
((InvokePattern)pattern).Invoke();
Debug.WriteLine("OneNote sync-warning dialog auto-dismissed.");
}
}
}
catch { /* dialog may have closed between find and invoke */ }
ct.WaitHandle.WaitOne(300);
}
});
}
}