|
1 | 1 | using System; |
2 | 2 | using System.IO; |
| 3 | +using System.Linq; |
3 | 4 | using Avalonia; |
4 | 5 | using Avalonia.Controls; |
5 | 6 | using Avalonia.Controls.ApplicationLifetimes; |
| 7 | +using Avalonia.Input; |
6 | 8 | using Avalonia.Input.Platform; // ClipboardExtensions.SetTextAsync |
| 9 | +using Avalonia.Platform.Storage; |
7 | 10 | using Avalonia.Threading; |
8 | 11 | using Markdig; |
9 | 12 | using MarkdownPointer.Services; // HtmlGenerator (shared rendering core) |
@@ -46,6 +49,52 @@ public MainWindow() |
46 | 49 |
|
47 | 50 | Loaded += (_, _) => { Render(); SetupWatcher(); }; |
48 | 51 | Closed += (_, _) => { _watcher?.Dispose(); _reloadDebounce?.Stop(); }; |
| 52 | + |
| 53 | + // Ctrl+O to open a file; drag-and-drop a file onto the window to open it. |
| 54 | + KeyDown += OnKeyDown; |
| 55 | + DragDrop.SetAllowDrop(this, true); |
| 56 | + AddHandler(DragDrop.DragOverEvent, OnDragOver); |
| 57 | + AddHandler(DragDrop.DropEvent, OnDrop); |
| 58 | + } |
| 59 | + |
| 60 | + private void OnKeyDown(object? sender, KeyEventArgs e) |
| 61 | + { |
| 62 | + if (e.Key == Key.O && e.KeyModifiers == KeyModifiers.Control) |
| 63 | + { |
| 64 | + OpenFileDialog(); |
| 65 | + e.Handled = true; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + private async void OpenFileDialog() |
| 70 | + { |
| 71 | + var top = TopLevel.GetTopLevel(this); |
| 72 | + if (top is null) return; |
| 73 | + |
| 74 | + var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions |
| 75 | + { |
| 76 | + Title = "Open Markdown", |
| 77 | + AllowMultiple = false, |
| 78 | + FileTypeFilter = new[] |
| 79 | + { |
| 80 | + new FilePickerFileType("Markdown") { Patterns = new[] { "*.md", "*.markdown", "*.txt" } }, |
| 81 | + FilePickerFileTypes.All, |
| 82 | + }, |
| 83 | + }); |
| 84 | + |
| 85 | + var path = files.Count > 0 ? files[0].TryGetLocalPath() : null; |
| 86 | + if (path is not null) LoadFile(path); |
| 87 | + } |
| 88 | + |
| 89 | + private void OnDragOver(object? sender, DragEventArgs e) |
| 90 | + { |
| 91 | + e.DragEffects = e.DataTransfer.Contains(DataFormat.File) ? DragDropEffects.Copy : DragDropEffects.None; |
| 92 | + } |
| 93 | + |
| 94 | + private void OnDrop(object? sender, DragEventArgs e) |
| 95 | + { |
| 96 | + var path = e.DataTransfer.TryGetFile()?.TryGetLocalPath(); |
| 97 | + if (path is not null && File.Exists(path)) LoadFile(path); |
49 | 98 | } |
50 | 99 |
|
51 | 100 | private void SetFile(string? path) |
|
0 commit comments