Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
609 lines (501 loc) · 22.3 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
609 lines (501 loc) · 22.3 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
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 OneNoteService? _service;
private CancellationTokenSource? _exportCts;
private bool _exportInProgress = 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 Task.Run(() => new OneNoteService());
var info = await Task.Run(() => _service.GetVersionInfo());
if (info.OneNoteInstalled)
SetVersionBadge($"✓ {info.OneNoteVersion}", StatusKind.Success);
else
SetVersionBadge("⚠ OneNote Desktop not found", StatusKind.Warning);
}
catch (Exception ex)
{
_service = null;
SetVersionBadge($"⚠ {ex.Message}", 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 Task.Run(() => _service.GetNotebooks());
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, $"Error loading notebooks: {ex.Message}");
}
UpdateExportButtonState();
}
// ── UI helpers ───────────────────────────────────────────────────────────
private string GetSelectedFormat()
{
if (FormatCombo.SelectedItem is ComboBoxItem item)
return item.Tag?.ToString() ?? "onepkg";
return "onepkg";
}
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;
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.Reason})";
LocalBackupItem.IsEnabled = false;
}
}
private void ApplyLocalBackupMode(bool enable)
{
if (enable)
{
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
{
BackupWarning.Visibility = Visibility.Collapsed;
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;
bool isLocalBackup = GetSelectedFormat() == "localbackup";
ApplyLocalBackupMode(isLocalBackup);
}
private void Notebook_SelectionChanged(object sender, RoutedEventArgs e)
=> UpdateExportButtonState();
private void Section_SelectionChanged(object sender, RoutedEventArgs e)
=> UpdateExportButtonState();
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 LoadSectionsAsync(NotebookViewModel nb)
{
if (_service == null) return;
nb.IsLoadingSections = true;
try
{
var sections = await Task.Run(() => _service.GetSections(nb.Id));
nb.Sections.Clear();
foreach (var s in sections)
nb.Sections.Add(new SectionViewModel(s));
nb.HasSectionsLoaded = true;
}
catch (Exception ex)
{
ShowStatus($"Could not load sections for '{nb.Name}': {ex.Message}", StatusKind.Error);
}
finally
{
nb.IsLoadingSections = false; // fires SectionsEmpty + IsSectionsContentVisible
}
}
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);
else
await RunComExportAsync(notebookJobs!, sectionJobs!, destPath, format, _exportCts.Token);
}
finally
{
_exportInProgress = false;
CancelButton.Visibility = Visibility.Collapsed;
SetButtonsEnabled(true);
UpdateExportButtonState();
}
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
if (!_exportInProgress) return;
var confirm = MessageBox.Show(
"Do you really want to cancel the export?\n\nWarning: This will terminate OneNote and OneNoteHelper processes!",
"Cancel Export",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (confirm != MessageBoxResult.Yes) return;
ShowStatus("Cancelling export...", StatusKind.Warning);
// Cancel via token
_exportCts?.Cancel();
// Fallback: force-kill processes (mirrors Go CancelExport behaviour)
KillProcess("ONENOTE.EXE");
}
// ── Export implementations ───────────────────────────────────────────────
private async Task RunLocalBackupAsync(string destPath)
{
ShowProgress("Copying local backup files...");
try
{
var result = await Task.Run(() => FileHelper.CopyLocalBackup(destPath));
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 (Exception ex)
{
HideProgress();
ShowStatus($"❌ Error during export: {ex.Message}", StatusKind.Error);
}
}
private async Task RunComExportAsync(
List<NotebookViewModel> notebookJobs,
List<(NotebookViewModel Notebook, SectionViewModel Section)> sectionJobs,
string destPath,
string format,
CancellationToken ct)
{
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)
{
if (ct.IsCancellationRequested) break;
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 Task.Run(
() => _service.ExportNotebook(nb.Id, destPath, format, progress, ct), ct);
if (result.Success) { successCount++; messages.Add($"✓ {nb.Name}"); }
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}: {ex.Message}");
}
await Task.Delay(300, CancellationToken.None);
}
// ── Section-level exports ─────────────────────────────────────────────
foreach (var (nb, sec) in sectionJobs)
{
if (ct.IsCancellationRequested) break;
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 Task.Run(
() => _service.ExportSection(sec.Info, destPath, format, progress, ct), ct);
if (result.Success) { successCount++; messages.Add($"✓ {nb.Name} / {sec.Name}"); }
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}: {ex.Message}");
}
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 static void StartDialogWatcher(CancellationToken ct)
{
_ = Task.Run(() =>
{
while (!ct.IsCancellationRequested)
{
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);
}
});
}
private static void KillProcess(string processName)
{
try
{
var psi = new ProcessStartInfo
{
FileName = "taskkill",
Arguments = $"/F /IM {processName}",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
using var p = Process.Start(psi);
p?.WaitForExit(5000);
}
catch (Exception ex)
{
Debug.WriteLine($"KillProcess({processName}): {ex.Message}");
}
}
}