DialogsPage.xaml.cs 17 KB

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