DialogsPage.xaml.cs 16 KB

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