DialogsPage.xaml.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Security;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Avalonia;
  11. using Avalonia.Controls;
  12. using Avalonia.Controls.Presenters;
  13. using Avalonia.Dialogs;
  14. using Avalonia.Layout;
  15. using Avalonia.Markup.Xaml;
  16. using Avalonia.Platform.Storage;
  17. using Avalonia.Platform.Storage.FileIO;
  18. #pragma warning disable CS0618 // Type or member is obsolete
  19. #nullable enable
  20. namespace ControlCatalog.Pages
  21. {
  22. public partial class DialogsPage : UserControl
  23. {
  24. public DialogsPage()
  25. {
  26. InitializeComponent();
  27. IStorageFolder? lastSelectedDirectory = null;
  28. IStorageItem? lastSelectedItem = null;
  29. bool ignoreTextChanged = false;
  30. var results = PickerLastResults;
  31. var resultsVisible = PickerLastResultsVisible;
  32. var bookmarkContainer = BookmarkContainer;
  33. var openedFileContent = OpenedFileContent;
  34. var openMultiple = OpenMultiple;
  35. var currentFolderBox = CurrentFolderBox;
  36. currentFolderBox.TextChanged += async (sender, args) =>
  37. {
  38. if (ignoreTextChanged) return;
  39. if (Enum.TryParse<WellKnownFolder>(currentFolderBox.Text, true, out var folderEnum))
  40. {
  41. lastSelectedDirectory = await GetStorageProvider().TryGetWellKnownFolderAsync(folderEnum);
  42. }
  43. else if (!string.IsNullOrWhiteSpace(currentFolderBox.Text))
  44. {
  45. if (!Uri.TryCreate(currentFolderBox.Text, UriKind.Absolute, out var folderLink))
  46. {
  47. Uri.TryCreate("file://" + currentFolderBox.Text, UriKind.Absolute, out folderLink);
  48. }
  49. if (folderLink is not null)
  50. {
  51. try
  52. {
  53. lastSelectedDirectory = await GetStorageProvider().TryGetFolderFromPathAsync(folderLink);
  54. }
  55. catch (SecurityException)
  56. {
  57. }
  58. }
  59. }
  60. };
  61. List<FileDialogFilter> GetFilters()
  62. {
  63. return GetFileTypes()?.Select(f => new FileDialogFilter
  64. {
  65. Name = f.Name, Extensions = f.Patterns!.ToList()
  66. }).ToList() ?? new List<FileDialogFilter>();
  67. }
  68. List<FilePickerFileType>? GetFileTypes()
  69. {
  70. var selectedItem = (FilterSelector.SelectedItem as ComboBoxItem)?.Content
  71. ?? "None";
  72. var binLogType = new FilePickerFileType("Binary Log")
  73. {
  74. Patterns = new[] { "*.binlog", "*.buildlog" },
  75. MimeTypes = new[] { "application/binlog", "application/buildlog" },
  76. AppleUniformTypeIdentifiers = new[] { "public.data" }
  77. };
  78. return selectedItem switch
  79. {
  80. "All + TXT + BinLog" => new List<FilePickerFileType>
  81. {
  82. FilePickerFileTypes.All, FilePickerFileTypes.TextPlain, binLogType
  83. },
  84. "Binlog" => new List<FilePickerFileType> { binLogType },
  85. "TXT extension only" => new List<FilePickerFileType>
  86. {
  87. new("TXT") { Patterns = FilePickerFileTypes.TextPlain.Patterns }
  88. },
  89. "TXT mime only" => new List<FilePickerFileType>
  90. {
  91. new("TXT") { MimeTypes = FilePickerFileTypes.TextPlain.MimeTypes }
  92. },
  93. "TXT apple type id only" => new List<FilePickerFileType>
  94. {
  95. new("TXT")
  96. {
  97. AppleUniformTypeIdentifiers =
  98. FilePickerFileTypes.TextPlain.AppleUniformTypeIdentifiers
  99. }
  100. },
  101. _ => null
  102. };
  103. }
  104. OpenFile.Click += async delegate
  105. {
  106. // Almost guaranteed to exist
  107. var uri = Assembly.GetEntryAssembly()?.GetModules().FirstOrDefault()?.FullyQualifiedName;
  108. var initialFileName = uri == null ? null : System.IO.Path.GetFileName(uri);
  109. var initialDirectory = uri == null ? null : System.IO.Path.GetDirectoryName(uri);
  110. var result = await new OpenFileDialog()
  111. {
  112. Title = "Open file",
  113. Filters = GetFilters(),
  114. Directory = initialDirectory,
  115. InitialFileName = initialFileName
  116. }.ShowAsync(GetWindow());
  117. results.ItemsSource = result;
  118. resultsVisible.IsVisible = result?.Any() == true;
  119. };
  120. OpenMultipleFiles.Click += async delegate
  121. {
  122. var result = await new OpenFileDialog()
  123. {
  124. Title = "Open multiple files",
  125. Filters = GetFilters(),
  126. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  127. AllowMultiple = true
  128. }.ShowAsync(GetWindow());
  129. results.ItemsSource = result;
  130. resultsVisible.IsVisible = result?.Any() == true;
  131. };
  132. SaveFile.Click += async delegate
  133. {
  134. var filters = GetFilters();
  135. var result = await new SaveFileDialog()
  136. {
  137. Title = "Save file",
  138. Filters = filters,
  139. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  140. DefaultExtension = filters?.Any() == true ? "txt" : null,
  141. InitialFileName = "test.txt"
  142. }.ShowAsync(GetWindow());
  143. results.ItemsSource = new[] { result };
  144. resultsVisible.IsVisible = result != null;
  145. };
  146. SelectFolder.Click += async delegate
  147. {
  148. var result = await new OpenFolderDialog()
  149. {
  150. Title = "Select folder",
  151. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  152. }.ShowAsync(GetWindow());
  153. if (string.IsNullOrEmpty(result))
  154. {
  155. resultsVisible.IsVisible = false;
  156. }
  157. else
  158. {
  159. SetFolder(await GetStorageProvider().TryGetFolderFromPathAsync(result!));
  160. results.ItemsSource = new[] { result };
  161. resultsVisible.IsVisible = true;
  162. }
  163. };
  164. OpenBoth.Click += async delegate
  165. {
  166. var result = await new OpenFileDialog()
  167. {
  168. Title = "Select both",
  169. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  170. AllowMultiple = true
  171. }.ShowManagedAsync(GetWindow(), new ManagedFileDialogOptions
  172. {
  173. AllowDirectorySelection = true
  174. });
  175. results.ItemsSource = result;
  176. resultsVisible.IsVisible = result?.Any() == true;
  177. };
  178. DecoratedWindow.Click += delegate
  179. {
  180. new DecoratedWindow().Show();
  181. };
  182. DecoratedWindowDialog.Click += delegate
  183. {
  184. _ = new DecoratedWindow().ShowDialog(GetWindow());
  185. };
  186. Dialog.Click += delegate
  187. {
  188. var window = CreateSampleWindow();
  189. window.Height = 200;
  190. _ = window.ShowDialog(GetWindow());
  191. };
  192. DialogNoTaskbar.Click += delegate
  193. {
  194. var window = CreateSampleWindow();
  195. window.Height = 200;
  196. window.ShowInTaskbar = false;
  197. _ = window.ShowDialog(GetWindow());
  198. };
  199. OwnedWindow.Click += delegate
  200. {
  201. var window = CreateSampleWindow();
  202. window.Show(GetWindow());
  203. };
  204. OwnedWindowNoTaskbar.Click += delegate
  205. {
  206. var window = CreateSampleWindow();
  207. window.ShowInTaskbar = false;
  208. window.Show(GetWindow());
  209. };
  210. OpenFilePicker.Click += async delegate
  211. {
  212. var result = await GetStorageProvider().OpenFilePickerAsync(new FilePickerOpenOptions()
  213. {
  214. Title = "Open file",
  215. FileTypeFilter = GetFileTypes(),
  216. SuggestedFileName = "FileName",
  217. SuggestedStartLocation = lastSelectedDirectory,
  218. AllowMultiple = openMultiple.IsChecked == true
  219. });
  220. await SetPickerResult(result);
  221. };
  222. SaveFilePicker.Click += async delegate
  223. {
  224. var fileTypes = GetFileTypes();
  225. var file = await GetStorageProvider().SaveFilePickerAsync(new FilePickerSaveOptions()
  226. {
  227. Title = "Save file",
  228. FileTypeChoices = fileTypes,
  229. SuggestedStartLocation = lastSelectedDirectory,
  230. SuggestedFileName = "FileName",
  231. ShowOverwritePrompt = true
  232. });
  233. if (file is not null)
  234. {
  235. try
  236. {
  237. // Sync disposal of StreamWriter is not supported on WASM
  238. #if NET6_0_OR_GREATER
  239. await using var stream = await file.OpenWriteAsync();
  240. await using var writer = new System.IO.StreamWriter(stream);
  241. #else
  242. using var stream = await file.OpenWriteAsync();
  243. using var writer = new System.IO.StreamWriter(stream);
  244. #endif
  245. await writer.WriteLineAsync(openedFileContent.Text);
  246. SetFolder(await file.GetParentAsync());
  247. }
  248. catch (Exception ex)
  249. {
  250. openedFileContent.Text = ex.ToString();
  251. }
  252. }
  253. await SetPickerResult(file is null ? null : new[] { file });
  254. };
  255. SaveFilePickerWithResult.Click += async delegate
  256. {
  257. var result = await GetStorageProvider().SaveFilePickerWithResultAsync(new FilePickerSaveOptions()
  258. {
  259. Title = "Save file",
  260. FileTypeChoices = [FilePickerFileTypes.Json, FilePickerFileTypes.Xml],
  261. SuggestedStartLocation = lastSelectedDirectory,
  262. SuggestedFileName = "FileName",
  263. ShowOverwritePrompt = true
  264. });
  265. try
  266. {
  267. if (result.File is { } file)
  268. {
  269. // Sync disposal of StreamWriter is not supported on WASM
  270. #if NET6_0_OR_GREATER
  271. await using var stream = await file.OpenWriteAsync();
  272. await using var writer = new System.IO.StreamWriter(stream);
  273. #else
  274. using var stream = await file.OpenWriteAsync();
  275. using var writer = new System.IO.StreamWriter(stream);
  276. #endif
  277. if (result.SelectedFileType == FilePickerFileTypes.Xml)
  278. {
  279. await writer.WriteLineAsync("<sample>Test</sample>");
  280. }
  281. else
  282. {
  283. await writer.WriteLineAsync("""{ "sample": "Test" }""");
  284. }
  285. SetFolder(await result.File.GetParentAsync());
  286. }
  287. }
  288. catch (Exception ex)
  289. {
  290. openedFileContent.Text = ex.ToString();
  291. }
  292. await SetPickerResult(result.File is null ? null : new[] { result.File }, result.SelectedFileType);
  293. };
  294. OpenFolderPicker.Click += async delegate
  295. {
  296. var folders = await GetStorageProvider().OpenFolderPickerAsync(new FolderPickerOpenOptions()
  297. {
  298. Title = "Folder file",
  299. SuggestedStartLocation = lastSelectedDirectory,
  300. SuggestedFileName = "FileName",
  301. AllowMultiple = openMultiple.IsChecked == true
  302. });
  303. await SetPickerResult(folders);
  304. };
  305. OpenFileFromBookmark.Click += async delegate
  306. {
  307. var file = bookmarkContainer.Text is not null
  308. ? await GetStorageProvider().OpenFileBookmarkAsync(bookmarkContainer.Text)
  309. : null;
  310. await SetPickerResult(file is null ? null : new[] { file });
  311. };
  312. OpenFolderFromBookmark.Click += async delegate
  313. {
  314. var folder = bookmarkContainer.Text is not null
  315. ? await GetStorageProvider().OpenFolderBookmarkAsync(bookmarkContainer.Text)
  316. : null;
  317. await SetPickerResult(folder is null ? null : new[] { folder });
  318. };
  319. LaunchUri.Click += async delegate
  320. {
  321. var statusBlock = LaunchStatus;
  322. if (Uri.TryCreate(UriToLaunch.Text, UriKind.Absolute, out var uri))
  323. {
  324. var result = await TopLevel.GetTopLevel(this)!.Launcher.LaunchUriAsync(uri);
  325. statusBlock.Text = "LaunchUriAsync returned " + result;
  326. }
  327. else
  328. {
  329. statusBlock.Text = "Can't parse the Uri";
  330. }
  331. };
  332. LaunchFile.Click += async delegate
  333. {
  334. var statusBlock = LaunchStatus;
  335. if (lastSelectedItem is not null)
  336. {
  337. var result = await TopLevel.GetTopLevel(this)!.Launcher.LaunchFileAsync(lastSelectedItem);
  338. statusBlock.Text = "LaunchFileAsync returned " + result;
  339. }
  340. else
  341. {
  342. statusBlock.Text = "Please select any file or folder first";
  343. }
  344. };
  345. void SetFolder(IStorageFolder? folder)
  346. {
  347. ignoreTextChanged = true;
  348. lastSelectedDirectory = folder;
  349. lastSelectedItem = folder;
  350. currentFolderBox.Text = folder?.Path is { IsAbsoluteUri: true } abs ? abs.LocalPath : folder?.Path?.ToString();
  351. ignoreTextChanged = false;
  352. }
  353. async Task SetPickerResult(IReadOnlyCollection<IStorageItem>? items, FilePickerFileType? selectedType = null)
  354. {
  355. items ??= Array.Empty<IStorageItem>();
  356. bookmarkContainer.Text = items.FirstOrDefault(f => f.CanBookmark) is { } f ? await f.SaveBookmarkAsync() : "Can't bookmark";
  357. var mappedResults = new List<string>();
  358. string resultText = "";
  359. if (items.FirstOrDefault() is IStorageItem item)
  360. {
  361. resultText += item is IStorageFile ? "File:" : "Folder:";
  362. resultText += Environment.NewLine;
  363. var props = await item.GetBasicPropertiesAsync();
  364. resultText += @$"Size: {props.Size}
  365. DateCreated: {props.DateCreated}
  366. DateModified: {props.DateModified}
  367. CanBookmark: {item.CanBookmark}
  368. ";
  369. if (item is IStorageFile file)
  370. {
  371. resultText += @$"
  372. Content:
  373. ";
  374. try
  375. {
  376. resultText += await ReadTextFromFile(file, 500);
  377. }
  378. catch (Exception ex)
  379. {
  380. resultText += ex.ToString();
  381. }
  382. }
  383. if (item is IStorageFolder storageFolder)
  384. {
  385. SetFolder(storageFolder);
  386. }
  387. else
  388. {
  389. var parent = await item.GetParentAsync();
  390. SetFolder(parent);
  391. if (parent is not null)
  392. {
  393. mappedResults.Add(FullPathOrName(parent));
  394. }
  395. }
  396. foreach (var selectedItem in items)
  397. {
  398. mappedResults.Add("+> " + FullPathOrName(selectedItem));
  399. if (selectedItem is IStorageFolder folder)
  400. {
  401. await foreach (var innerItem in folder.GetItemsAsync())
  402. {
  403. mappedResults.Add("++> " + FullPathOrName(innerItem));
  404. }
  405. }
  406. }
  407. lastSelectedItem = item;
  408. }
  409. if (selectedType is not null)
  410. {
  411. resultText += Environment.NewLine + "Selected type: " + selectedType.Name;
  412. }
  413. openedFileContent.Text = resultText;
  414. results.ItemsSource = mappedResults;
  415. resultsVisible.IsVisible = mappedResults.Any();
  416. }
  417. }
  418. internal static async Task<string> ReadTextFromFile(IStorageFile file, int length)
  419. {
  420. #if NET6_0_OR_GREATER
  421. await using var stream = await file.OpenReadAsync();
  422. #else
  423. using var stream = await file.OpenReadAsync();
  424. #endif
  425. using var reader = new System.IO.StreamReader(stream);
  426. // 4GB file test, shouldn't load more than 10000 chars into a memory.
  427. var buffer = ArrayPool<char>.Shared.Rent(length);
  428. try
  429. {
  430. var charsRead = await reader.ReadAsync(buffer, 0, length);
  431. return new string(buffer, 0, charsRead);
  432. }
  433. finally
  434. {
  435. ArrayPool<char>.Shared.Return(buffer);
  436. }
  437. }
  438. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  439. {
  440. base.OnAttachedToVisualTree(e);
  441. var openedFileContent = OpenedFileContent;
  442. try
  443. {
  444. var storageProvider = GetStorageProvider();
  445. openedFileContent.Text = $@"CanOpen: {storageProvider.CanOpen}
  446. CanSave: {storageProvider.CanSave}
  447. CanPickFolder: {storageProvider.CanPickFolder}";
  448. }
  449. catch (Exception ex)
  450. {
  451. openedFileContent.Text = "Storage provider is not available: " + ex.Message;
  452. }
  453. }
  454. private Window CreateSampleWindow()
  455. {
  456. Button button;
  457. Button dialogButton;
  458. var window = new Window
  459. {
  460. Height = 200,
  461. Width = 200,
  462. Content = new StackPanel
  463. {
  464. Spacing = 4,
  465. Children =
  466. {
  467. new TextBlock { Text = "Hello world!" },
  468. (button = new Button
  469. {
  470. HorizontalAlignment = HorizontalAlignment.Center,
  471. Content = "Click to close",
  472. IsDefault = true
  473. }),
  474. (dialogButton = new Button
  475. {
  476. HorizontalAlignment = HorizontalAlignment.Center,
  477. Content = "Dialog",
  478. IsDefault = false
  479. })
  480. }
  481. },
  482. WindowStartupLocation = WindowStartupLocation.CenterOwner
  483. };
  484. button.Click += (_, __) => window.Close();
  485. dialogButton.Click += (_, __) =>
  486. {
  487. var dialog = CreateSampleWindow();
  488. dialog.Height = 200;
  489. dialog.ShowDialog(window);
  490. };
  491. return window;
  492. }
  493. private IStorageProvider GetStorageProvider()
  494. {
  495. var forceManaged = ForceManaged.IsChecked ?? false;
  496. return forceManaged
  497. ? new ManagedStorageProvider(GetWindow()) // NOTE: In your production App use 'AppBuilder.UseManagedSystemDialogs()'
  498. : GetTopLevel().StorageProvider;
  499. }
  500. private static string FullPathOrName(IStorageItem? item)
  501. {
  502. if (item is null) return "(null)";
  503. return item.Path is { IsAbsoluteUri: true } path ? path.ToString() : item.Name;
  504. }
  505. Window GetWindow() => TopLevel.GetTopLevel(this) as Window ?? throw new NullReferenceException("Invalid Owner");
  506. TopLevel GetTopLevel() => TopLevel.GetTopLevel(this) ?? throw new NullReferenceException("Invalid Owner");
  507. }
  508. #pragma warning restore CS0618 // Type or member is obsolete
  509. }