DialogsPage.xaml.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 class DialogsPage : UserControl
  23. {
  24. public DialogsPage()
  25. {
  26. this.InitializeComponent();
  27. IStorageFolder? lastSelectedDirectory = null;
  28. IStorageItem? lastSelectedItem = null;
  29. bool ignoreTextChanged = false;
  30. var results = this.Get<ItemsControl>("PickerLastResults");
  31. var resultsVisible = this.Get<TextBlock>("PickerLastResultsVisible");
  32. var bookmarkContainer = this.Get<TextBox>("BookmarkContainer");
  33. var openedFileContent = this.Get<TextBox>("OpenedFileContent");
  34. var openMultiple = this.Get<CheckBox>("OpenMultiple");
  35. var currentFolderBox = this.Get<AutoCompleteBox>("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 = (this.Get<ComboBox>("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. this.Get<Button>("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. this.Get<Button>("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. this.Get<Button>("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. this.Get<Button>("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. this.Get<Button>("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. this.Get<Button>("DecoratedWindow").Click += delegate
  179. {
  180. new DecoratedWindow().Show();
  181. };
  182. this.Get<Button>("DecoratedWindowDialog").Click += delegate
  183. {
  184. _ = new DecoratedWindow().ShowDialog(GetWindow());
  185. };
  186. this.Get<Button>("Dialog").Click += delegate
  187. {
  188. var window = CreateSampleWindow();
  189. window.Height = 200;
  190. _ = window.ShowDialog(GetWindow());
  191. };
  192. this.Get<Button>("DialogNoTaskbar").Click += delegate
  193. {
  194. var window = CreateSampleWindow();
  195. window.Height = 200;
  196. window.ShowInTaskbar = false;
  197. _ = window.ShowDialog(GetWindow());
  198. };
  199. this.Get<Button>("OwnedWindow").Click += delegate
  200. {
  201. var window = CreateSampleWindow();
  202. window.Show(GetWindow());
  203. };
  204. this.Get<Button>("OwnedWindowNoTaskbar").Click += delegate
  205. {
  206. var window = CreateSampleWindow();
  207. window.ShowInTaskbar = false;
  208. window.Show(GetWindow());
  209. };
  210. this.Get<Button>("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. this.Get<Button>("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. // Sync disposal of StreamWriter is not supported on WASM
  236. #if NET6_0_OR_GREATER
  237. await using var stream = await file.OpenWriteAsync();
  238. await using var writer = new System.IO.StreamWriter(stream);
  239. #else
  240. using var stream = await file.OpenWriteAsync();
  241. using var writer = new System.IO.StreamWriter(stream);
  242. #endif
  243. await writer.WriteLineAsync(openedFileContent.Text);
  244. SetFolder(await file.GetParentAsync());
  245. }
  246. await SetPickerResult(file is null ? null : new[] { file });
  247. };
  248. this.Get<Button>("OpenFolderPicker").Click += async delegate
  249. {
  250. var folders = await GetStorageProvider().OpenFolderPickerAsync(new FolderPickerOpenOptions()
  251. {
  252. Title = "Folder file",
  253. SuggestedStartLocation = lastSelectedDirectory,
  254. SuggestedFileName = "FileName",
  255. AllowMultiple = openMultiple.IsChecked == true
  256. });
  257. await SetPickerResult(folders);
  258. SetFolder(folders.FirstOrDefault());
  259. };
  260. this.Get<Button>("OpenFileFromBookmark").Click += async delegate
  261. {
  262. var file = bookmarkContainer.Text is not null
  263. ? await GetStorageProvider().OpenFileBookmarkAsync(bookmarkContainer.Text)
  264. : null;
  265. await SetPickerResult(file is null ? null : new[] { file });
  266. };
  267. this.Get<Button>("OpenFolderFromBookmark").Click += async delegate
  268. {
  269. var folder = bookmarkContainer.Text is not null
  270. ? await GetStorageProvider().OpenFolderBookmarkAsync(bookmarkContainer.Text)
  271. : null;
  272. await SetPickerResult(folder is null ? null : new[] { folder });
  273. SetFolder(folder);
  274. };
  275. this.Get<Button>("LaunchUri").Click += async delegate
  276. {
  277. var statusBlock = this.Get<TextBlock>("LaunchStatus");
  278. if (Uri.TryCreate(this.Get<TextBox>("UriToLaunch").Text, UriKind.Absolute, out var uri))
  279. {
  280. var result = await TopLevel.GetTopLevel(this)!.Launcher.LaunchUriAsync(uri);
  281. statusBlock.Text = "LaunchUriAsync returned " + result;
  282. }
  283. else
  284. {
  285. statusBlock.Text = "Can't parse the Uri";
  286. }
  287. };
  288. this.Get<Button>("LaunchFile").Click += async delegate
  289. {
  290. var statusBlock = this.Get<TextBlock>("LaunchStatus");
  291. if (lastSelectedItem is not null)
  292. {
  293. var result = await TopLevel.GetTopLevel(this)!.Launcher.LaunchFileAsync(lastSelectedItem);
  294. statusBlock.Text = "LaunchFileAsync returned " + result;
  295. }
  296. else
  297. {
  298. statusBlock.Text = "Please select any file or folder first";
  299. }
  300. };
  301. void SetFolder(IStorageFolder? folder)
  302. {
  303. ignoreTextChanged = true;
  304. lastSelectedDirectory = folder;
  305. lastSelectedItem = folder;
  306. currentFolderBox.Text = folder?.Path is { IsAbsoluteUri: true } abs ? abs.LocalPath : folder?.Path?.ToString();
  307. ignoreTextChanged = false;
  308. }
  309. async Task SetPickerResult(IReadOnlyCollection<IStorageItem>? items)
  310. {
  311. items ??= Array.Empty<IStorageItem>();
  312. bookmarkContainer.Text = items.FirstOrDefault(f => f.CanBookmark) is { } f ? await f.SaveBookmarkAsync() : "Can't bookmark";
  313. var mappedResults = new List<string>();
  314. if (items.FirstOrDefault() is IStorageItem item)
  315. {
  316. var resultText = item is IStorageFile ? "File:" : "Folder:";
  317. resultText += Environment.NewLine;
  318. var props = await item.GetBasicPropertiesAsync();
  319. resultText += @$"Size: {props.Size}
  320. DateCreated: {props.DateCreated}
  321. DateModified: {props.DateModified}
  322. CanBookmark: {item.CanBookmark}
  323. ";
  324. if (item is IStorageFile file)
  325. {
  326. resultText += @$"
  327. Content:
  328. ";
  329. resultText += await ReadTextFromFile(file, 500);
  330. }
  331. openedFileContent.Text = resultText;
  332. var parent = await item.GetParentAsync();
  333. SetFolder(parent);
  334. if (parent is not null)
  335. {
  336. mappedResults.Add(FullPathOrName(parent));
  337. }
  338. foreach (var selectedItem in items)
  339. {
  340. mappedResults.Add("+> " + FullPathOrName(selectedItem));
  341. if (selectedItem is IStorageFolder folder)
  342. {
  343. await foreach (var innerItem in folder.GetItemsAsync())
  344. {
  345. mappedResults.Add("++> " + FullPathOrName(innerItem));
  346. }
  347. }
  348. }
  349. lastSelectedItem = item;
  350. }
  351. results.ItemsSource = mappedResults;
  352. resultsVisible.IsVisible = mappedResults.Any();
  353. }
  354. }
  355. public static async Task<string> ReadTextFromFile(IStorageFile file, int length)
  356. {
  357. #if NET6_0_OR_GREATER
  358. await using var stream = await file.OpenReadAsync();
  359. #else
  360. using var stream = await file.OpenReadAsync();
  361. #endif
  362. using var reader = new System.IO.StreamReader(stream);
  363. // 4GB file test, shouldn't load more than 10000 chars into a memory.
  364. var buffer = ArrayPool<char>.Shared.Rent(length);
  365. try
  366. {
  367. var charsRead = await reader.ReadAsync(buffer, 0, length);
  368. return new string(buffer, 0, charsRead);
  369. }
  370. finally
  371. {
  372. ArrayPool<char>.Shared.Return(buffer);
  373. }
  374. }
  375. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  376. {
  377. base.OnAttachedToVisualTree(e);
  378. var openedFileContent = this.Get<TextBox>("OpenedFileContent");
  379. try
  380. {
  381. var storageProvider = GetStorageProvider();
  382. openedFileContent.Text = $@"CanOpen: {storageProvider.CanOpen}
  383. CanSave: {storageProvider.CanSave}
  384. CanPickFolder: {storageProvider.CanPickFolder}";
  385. }
  386. catch (Exception ex)
  387. {
  388. openedFileContent.Text = "Storage provider is not available: " + ex.Message;
  389. }
  390. }
  391. private Window CreateSampleWindow()
  392. {
  393. Button button;
  394. Button dialogButton;
  395. var window = new Window
  396. {
  397. Height = 200,
  398. Width = 200,
  399. Content = new StackPanel
  400. {
  401. Spacing = 4,
  402. Children =
  403. {
  404. new TextBlock { Text = "Hello world!" },
  405. (button = new Button
  406. {
  407. HorizontalAlignment = HorizontalAlignment.Center,
  408. Content = "Click to close",
  409. IsDefault = true
  410. }),
  411. (dialogButton = new Button
  412. {
  413. HorizontalAlignment = HorizontalAlignment.Center,
  414. Content = "Dialog",
  415. IsDefault = false
  416. })
  417. }
  418. },
  419. WindowStartupLocation = WindowStartupLocation.CenterOwner
  420. };
  421. button.Click += (_, __) => window.Close();
  422. dialogButton.Click += (_, __) =>
  423. {
  424. var dialog = CreateSampleWindow();
  425. dialog.Height = 200;
  426. dialog.ShowDialog(window);
  427. };
  428. return window;
  429. }
  430. private IStorageProvider GetStorageProvider()
  431. {
  432. var forceManaged = this.Get<CheckBox>("ForceManaged").IsChecked ?? false;
  433. return forceManaged
  434. ? new ManagedStorageProvider(GetWindow()) // NOTE: In your production App use 'AppBuilder.UseManagedSystemDialogs()'
  435. : GetTopLevel().StorageProvider;
  436. }
  437. private static string FullPathOrName(IStorageItem? item)
  438. {
  439. if (item is null) return "(null)";
  440. return item.Path is { IsAbsoluteUri: true } path ? path.ToString() : item.Name;
  441. }
  442. Window GetWindow() => TopLevel.GetTopLevel(this) as Window ?? throw new NullReferenceException("Invalid Owner");
  443. TopLevel GetTopLevel() => TopLevel.GetTopLevel(this) ?? throw new NullReferenceException("Invalid Owner");
  444. private void InitializeComponent()
  445. {
  446. AvaloniaXamlLoader.Load(this);
  447. }
  448. }
  449. }
  450. #pragma warning restore CS0618 // Type or member is obsolete