DialogsPage.xaml.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using Avalonia;
  8. using Avalonia.Controls;
  9. using Avalonia.Controls.Presenters;
  10. using Avalonia.Dialogs;
  11. using Avalonia.Layout;
  12. using Avalonia.Markup.Xaml;
  13. using Avalonia.Platform.Storage;
  14. using Avalonia.Platform.Storage.FileIO;
  15. #pragma warning disable CS0618 // Type or member is obsolete
  16. #nullable enable
  17. namespace ControlCatalog.Pages
  18. {
  19. public class DialogsPage : UserControl
  20. {
  21. public DialogsPage()
  22. {
  23. this.InitializeComponent();
  24. IStorageFolder? lastSelectedDirectory = null;
  25. bool ignoreTextChanged = false;
  26. var results = this.Get<ItemsControl>("PickerLastResults");
  27. var resultsVisible = this.Get<TextBlock>("PickerLastResultsVisible");
  28. var bookmarkContainer = this.Get<TextBox>("BookmarkContainer");
  29. var openedFileContent = this.Get<TextBox>("OpenedFileContent");
  30. var openMultiple = this.Get<CheckBox>("OpenMultiple");
  31. var currentFolderBox = this.Get<AutoCompleteBox>("CurrentFolderBox");
  32. currentFolderBox.TextChanged += async (sender, args) =>
  33. {
  34. if (ignoreTextChanged) return;
  35. if (Enum.TryParse<WellKnownFolder>(currentFolderBox.Text, true, out var folderEnum))
  36. {
  37. lastSelectedDirectory = await GetStorageProvider().TryGetWellKnownFolder(folderEnum);
  38. }
  39. else
  40. {
  41. if (!Uri.TryCreate(currentFolderBox.Text, UriKind.Absolute, out var folderLink))
  42. {
  43. Uri.TryCreate("file://" + currentFolderBox.Text, UriKind.Absolute, out folderLink);
  44. }
  45. if (folderLink is not null)
  46. {
  47. lastSelectedDirectory = await GetStorageProvider().TryGetFolderFromPath(folderLink);
  48. }
  49. }
  50. };
  51. List<FileDialogFilter> GetFilters()
  52. {
  53. if (this.Get<CheckBox>("UseFilters").IsChecked != true)
  54. return new List<FileDialogFilter>();
  55. return new List<FileDialogFilter>
  56. {
  57. new FileDialogFilter
  58. {
  59. Name = "Text files (.txt)", Extensions = new List<string> {"txt"}
  60. },
  61. new FileDialogFilter
  62. {
  63. Name = "All files",
  64. Extensions = new List<string> {"*"}
  65. }
  66. };
  67. }
  68. List<FilePickerFileType>? GetFileTypes()
  69. {
  70. if (this.Get<CheckBox>("UseFilters").IsChecked != true)
  71. return null;
  72. return new List<FilePickerFileType>
  73. {
  74. FilePickerFileTypes.All,
  75. FilePickerFileTypes.TextPlain
  76. };
  77. }
  78. this.Get<Button>("OpenFile").Click += async delegate
  79. {
  80. // Almost guaranteed to exist
  81. var uri = Assembly.GetEntryAssembly()?.GetModules().FirstOrDefault()?.FullyQualifiedName;
  82. var initialFileName = uri == null ? null : System.IO.Path.GetFileName(uri);
  83. var initialDirectory = uri == null ? null : System.IO.Path.GetDirectoryName(uri);
  84. var result = await new OpenFileDialog()
  85. {
  86. Title = "Open file",
  87. Filters = GetFilters(),
  88. Directory = initialDirectory,
  89. InitialFileName = initialFileName
  90. }.ShowAsync(GetWindow());
  91. results.Items = result;
  92. resultsVisible.IsVisible = result?.Any() == true;
  93. };
  94. this.Get<Button>("OpenMultipleFiles").Click += async delegate
  95. {
  96. var result = await new OpenFileDialog()
  97. {
  98. Title = "Open multiple files",
  99. Filters = GetFilters(),
  100. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  101. AllowMultiple = true
  102. }.ShowAsync(GetWindow());
  103. results.Items = result;
  104. resultsVisible.IsVisible = result?.Any() == true;
  105. };
  106. this.Get<Button>("SaveFile").Click += async delegate
  107. {
  108. var filters = GetFilters();
  109. var result = await new SaveFileDialog()
  110. {
  111. Title = "Save file",
  112. Filters = filters,
  113. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  114. DefaultExtension = filters?.Any() == true ? "txt" : null,
  115. InitialFileName = "test.txt"
  116. }.ShowAsync(GetWindow());
  117. results.Items = new[] { result };
  118. resultsVisible.IsVisible = result != null;
  119. };
  120. this.Get<Button>("SelectFolder").Click += async delegate
  121. {
  122. var result = await new OpenFolderDialog()
  123. {
  124. Title = "Select folder",
  125. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  126. }.ShowAsync(GetWindow());
  127. if (string.IsNullOrEmpty(result))
  128. {
  129. resultsVisible.IsVisible = false;
  130. }
  131. else
  132. {
  133. SetFolder(await GetStorageProvider().TryGetFolderFromPath(result));
  134. results.Items = new[] { result };
  135. resultsVisible.IsVisible = true;
  136. }
  137. };
  138. this.Get<Button>("OpenBoth").Click += async delegate
  139. {
  140. var result = await new OpenFileDialog()
  141. {
  142. Title = "Select both",
  143. Directory = lastSelectedDirectory?.Path is {IsAbsoluteUri:true} path ? path.LocalPath : null,
  144. AllowMultiple = true
  145. }.ShowManagedAsync(GetWindow(), new ManagedFileDialogOptions
  146. {
  147. AllowDirectorySelection = true
  148. });
  149. results.Items = result;
  150. resultsVisible.IsVisible = result?.Any() == true;
  151. };
  152. this.Get<Button>("DecoratedWindow").Click += delegate
  153. {
  154. new DecoratedWindow().Show();
  155. };
  156. this.Get<Button>("DecoratedWindowDialog").Click += delegate
  157. {
  158. _ = new DecoratedWindow().ShowDialog(GetWindow());
  159. };
  160. this.Get<Button>("Dialog").Click += delegate
  161. {
  162. var window = CreateSampleWindow();
  163. window.Height = 200;
  164. _ = window.ShowDialog(GetWindow());
  165. };
  166. this.Get<Button>("DialogNoTaskbar").Click += delegate
  167. {
  168. var window = CreateSampleWindow();
  169. window.Height = 200;
  170. window.ShowInTaskbar = false;
  171. _ = window.ShowDialog(GetWindow());
  172. };
  173. this.Get<Button>("OwnedWindow").Click += delegate
  174. {
  175. var window = CreateSampleWindow();
  176. window.Show(GetWindow());
  177. };
  178. this.Get<Button>("OwnedWindowNoTaskbar").Click += delegate
  179. {
  180. var window = CreateSampleWindow();
  181. window.ShowInTaskbar = false;
  182. window.Show(GetWindow());
  183. };
  184. this.Get<Button>("OpenFilePicker").Click += async delegate
  185. {
  186. var result = await GetStorageProvider().OpenFilePickerAsync(new FilePickerOpenOptions()
  187. {
  188. Title = "Open file",
  189. FileTypeFilter = GetFileTypes(),
  190. SuggestedStartLocation = lastSelectedDirectory,
  191. AllowMultiple = openMultiple.IsChecked == true
  192. });
  193. await SetPickerResult(result);
  194. };
  195. this.Get<Button>("SaveFilePicker").Click += async delegate
  196. {
  197. var fileTypes = GetFileTypes();
  198. var file = await GetStorageProvider().SaveFilePickerAsync(new FilePickerSaveOptions()
  199. {
  200. Title = "Save file",
  201. FileTypeChoices = fileTypes,
  202. SuggestedStartLocation = lastSelectedDirectory,
  203. SuggestedFileName = "FileName",
  204. DefaultExtension = fileTypes?.Any() == true ? "txt" : null,
  205. ShowOverwritePrompt = false
  206. });
  207. if (file is not null)
  208. {
  209. // Sync disposal of StreamWriter is not supported on WASM
  210. #if NET6_0_OR_GREATER
  211. await using var stream = await file.OpenWriteAsync();
  212. await using var reader = new System.IO.StreamWriter(stream);
  213. #else
  214. using var stream = await file.OpenWriteAsync();
  215. using var reader = new System.IO.StreamWriter(stream);
  216. #endif
  217. await reader.WriteLineAsync(openedFileContent.Text);
  218. SetFolder(await file.GetParentAsync());
  219. }
  220. await SetPickerResult(file is null ? null : new[] { file });
  221. };
  222. this.Get<Button>("OpenFolderPicker").Click += async delegate
  223. {
  224. var folders = await GetStorageProvider().OpenFolderPickerAsync(new FolderPickerOpenOptions()
  225. {
  226. Title = "Folder file",
  227. SuggestedStartLocation = lastSelectedDirectory,
  228. AllowMultiple = openMultiple.IsChecked == true
  229. });
  230. await SetPickerResult(folders);
  231. SetFolder(folders.FirstOrDefault());
  232. };
  233. this.Get<Button>("OpenFileFromBookmark").Click += async delegate
  234. {
  235. var file = bookmarkContainer.Text is not null
  236. ? await GetStorageProvider().OpenFileBookmarkAsync(bookmarkContainer.Text)
  237. : null;
  238. await SetPickerResult(file is null ? null : new[] { file });
  239. };
  240. this.Get<Button>("OpenFolderFromBookmark").Click += async delegate
  241. {
  242. var folder = bookmarkContainer.Text is not null
  243. ? await GetStorageProvider().OpenFolderBookmarkAsync(bookmarkContainer.Text)
  244. : null;
  245. await SetPickerResult(folder is null ? null : new[] { folder });
  246. SetFolder(folder);
  247. };
  248. void SetFolder(IStorageFolder? folder)
  249. {
  250. ignoreTextChanged = true;
  251. lastSelectedDirectory = folder;
  252. currentFolderBox.Text = folder?.Path.LocalPath;
  253. ignoreTextChanged = false;
  254. }
  255. async Task SetPickerResult(IReadOnlyCollection<IStorageItem>? items)
  256. {
  257. items ??= Array.Empty<IStorageItem>();
  258. bookmarkContainer.Text = items.FirstOrDefault(f => f.CanBookmark) is { } f ? await f.SaveBookmarkAsync() : "Can't bookmark";
  259. var mappedResults = new List<string>();
  260. if (items.FirstOrDefault() is IStorageItem item)
  261. {
  262. var resultText = item is IStorageFile ? "File:" : "Folder:";
  263. resultText += Environment.NewLine;
  264. var props = await item.GetBasicPropertiesAsync();
  265. resultText += @$"Size: {props.Size}
  266. DateCreated: {props.DateCreated}
  267. DateModified: {props.DateModified}
  268. CanBookmark: {item.CanBookmark}
  269. ";
  270. if (item is IStorageFile file)
  271. {
  272. resultText += @$"
  273. Content:
  274. ";
  275. #if NET6_0_OR_GREATER
  276. await using var stream = await file.OpenReadAsync();
  277. #else
  278. using var stream = await file.OpenReadAsync();
  279. #endif
  280. using var reader = new System.IO.StreamReader(stream);
  281. // 4GB file test, shouldn't load more than 10000 chars into a memory.
  282. const int length = 10000;
  283. var buffer = ArrayPool<char>.Shared.Rent(length);
  284. try
  285. {
  286. var charsRead = await reader.ReadAsync(buffer, 0, length);
  287. resultText += new string(buffer, 0, charsRead);
  288. }
  289. finally
  290. {
  291. ArrayPool<char>.Shared.Return(buffer);
  292. }
  293. }
  294. openedFileContent.Text = resultText;
  295. var parent = await item.GetParentAsync();
  296. SetFolder(parent);
  297. if (parent is not null)
  298. {
  299. mappedResults.Add(FullPathOrName(parent));
  300. }
  301. foreach (var selectedItem in items)
  302. {
  303. mappedResults.Add("+> " + FullPathOrName(selectedItem));
  304. if (selectedItem is IStorageFolder folder)
  305. {
  306. foreach (var innerItems in await folder.GetItemsAsync())
  307. {
  308. mappedResults.Add("++> " + FullPathOrName(innerItems));
  309. }
  310. }
  311. }
  312. }
  313. results.Items = mappedResults;
  314. resultsVisible.IsVisible = mappedResults.Any();
  315. }
  316. }
  317. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  318. {
  319. base.OnAttachedToVisualTree(e);
  320. var openedFileContent = this.Get<TextBox>("OpenedFileContent");
  321. try
  322. {
  323. var storageProvider = GetStorageProvider();
  324. openedFileContent.Text = $@"CanOpen: {storageProvider.CanOpen}
  325. CanSave: {storageProvider.CanSave}
  326. CanPickFolder: {storageProvider.CanPickFolder}";
  327. }
  328. catch (Exception ex)
  329. {
  330. openedFileContent.Text = "Storage provider is not available: " + ex.Message;
  331. }
  332. }
  333. private Window CreateSampleWindow()
  334. {
  335. Button button;
  336. Button dialogButton;
  337. var window = new Window
  338. {
  339. Height = 200,
  340. Width = 200,
  341. Content = new StackPanel
  342. {
  343. Spacing = 4,
  344. Children =
  345. {
  346. new TextBlock { Text = "Hello world!" },
  347. (button = new Button
  348. {
  349. HorizontalAlignment = HorizontalAlignment.Center,
  350. Content = "Click to close",
  351. IsDefault = true
  352. }),
  353. (dialogButton = new Button
  354. {
  355. HorizontalAlignment = HorizontalAlignment.Center,
  356. Content = "Dialog",
  357. IsDefault = false
  358. })
  359. }
  360. },
  361. WindowStartupLocation = WindowStartupLocation.CenterOwner
  362. };
  363. button.Click += (_, __) => window.Close();
  364. dialogButton.Click += (_, __) =>
  365. {
  366. var dialog = CreateSampleWindow();
  367. dialog.Height = 200;
  368. dialog.ShowDialog(window);
  369. };
  370. return window;
  371. }
  372. private IStorageProvider GetStorageProvider()
  373. {
  374. var forceManaged = this.Get<CheckBox>("ForceManaged").IsChecked ?? false;
  375. return forceManaged
  376. ? new ManagedStorageProvider<Window>(GetWindow(), null)
  377. : GetTopLevel().StorageProvider;
  378. }
  379. private static string FullPathOrName(IStorageItem? item)
  380. {
  381. if (item is null) return "(null)";
  382. return item.Path is { IsAbsoluteUri: true } path ? path.ToString() : item.Name;
  383. }
  384. Window GetWindow() => TopLevel.GetTopLevel(this) as Window ?? throw new NullReferenceException("Invalid Owner");
  385. TopLevel GetTopLevel() => TopLevel.GetTopLevel(this) ?? throw new NullReferenceException("Invalid Owner");
  386. private void InitializeComponent()
  387. {
  388. AvaloniaXamlLoader.Load(this);
  389. }
  390. }
  391. }
  392. #pragma warning restore CS0618 // Type or member is obsolete