ManagedFileChooserViewModel.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using Avalonia.Collections;
  7. using Avalonia.Controls;
  8. using Avalonia.Threading;
  9. namespace Avalonia.Dialogs
  10. {
  11. internal class ManagedFileChooserViewModel : InternalViewModelBase
  12. {
  13. public event Action CancelRequested;
  14. public event Action<string[]> CompleteRequested;
  15. public AvaloniaList<ManagedFileChooserItemViewModel> QuickLinks { get; } =
  16. new AvaloniaList<ManagedFileChooserItemViewModel>();
  17. public AvaloniaList<ManagedFileChooserItemViewModel> Items { get; } =
  18. new AvaloniaList<ManagedFileChooserItemViewModel>();
  19. public AvaloniaList<ManagedFileChooserFilterViewModel> Filters { get; } =
  20. new AvaloniaList<ManagedFileChooserFilterViewModel>();
  21. public AvaloniaList<ManagedFileChooserItemViewModel> SelectedItems { get; } =
  22. new AvaloniaList<ManagedFileChooserItemViewModel>();
  23. string _location;
  24. string _fileName;
  25. private bool _showHiddenFiles;
  26. private ManagedFileChooserFilterViewModel _selectedFilter;
  27. private bool _selectingDirectory;
  28. private bool _savingFile;
  29. private bool _scheduledSelectionValidation;
  30. private string _defaultExtension;
  31. public string Location
  32. {
  33. get => _location;
  34. private set => this.RaiseAndSetIfChanged(ref _location, value);
  35. }
  36. public string FileName
  37. {
  38. get => _fileName;
  39. private set => this.RaiseAndSetIfChanged(ref _fileName, value);
  40. }
  41. public bool SelectingFolder => _selectingDirectory;
  42. public bool ShowFilters { get; }
  43. public SelectionMode SelectionMode { get; }
  44. public string Title { get; }
  45. public int QuickLinksSelectedIndex
  46. {
  47. get
  48. {
  49. for (var index = 0; index < QuickLinks.Count; index++)
  50. {
  51. var i = QuickLinks[index];
  52. if (i.Path == Location)
  53. {
  54. return index;
  55. }
  56. }
  57. return -1;
  58. }
  59. set => this.RaisePropertyChanged(nameof(QuickLinksSelectedIndex));
  60. }
  61. public ManagedFileChooserFilterViewModel SelectedFilter
  62. {
  63. get => _selectedFilter;
  64. set
  65. {
  66. this.RaiseAndSetIfChanged(ref _selectedFilter, value);
  67. Refresh();
  68. }
  69. }
  70. public bool ShowHiddenFiles
  71. {
  72. get => _showHiddenFiles;
  73. set
  74. {
  75. this.RaiseAndSetIfChanged(ref _showHiddenFiles, value);
  76. Refresh();
  77. }
  78. }
  79. public ManagedFileChooserViewModel(FileSystemDialog dialog)
  80. {
  81. var quickSources = AvaloniaLocator.Current.GetService<ManagedFileChooserSources>()
  82. ?? new ManagedFileChooserSources();
  83. QuickLinks.Clear();
  84. QuickLinks.AddRange(quickSources.GetAllItems().Select(i => new ManagedFileChooserItemViewModel(i)));
  85. Title = dialog.Title ?? (
  86. dialog is OpenFileDialog ? "Open file"
  87. : dialog is SaveFileDialog ? "Save file"
  88. : dialog is OpenFolderDialog ? "Select directory"
  89. : throw new ArgumentException(nameof(dialog)));
  90. var directory = dialog.InitialDirectory;
  91. if (directory == null || !Directory.Exists(directory))
  92. {
  93. directory = Directory.GetCurrentDirectory();
  94. }
  95. if (dialog is FileDialog fd)
  96. {
  97. if (fd.Filters?.Count > 0)
  98. {
  99. Filters.AddRange(fd.Filters.Select(f => new ManagedFileChooserFilterViewModel(f)));
  100. _selectedFilter = Filters[0];
  101. ShowFilters = true;
  102. }
  103. if (dialog is OpenFileDialog ofd)
  104. {
  105. if (ofd.AllowMultiple)
  106. {
  107. SelectionMode = SelectionMode.Multiple;
  108. }
  109. }
  110. }
  111. _selectingDirectory = dialog is OpenFolderDialog;
  112. if(dialog is SaveFileDialog sfd)
  113. {
  114. _savingFile = true;
  115. _defaultExtension = sfd.DefaultExtension;
  116. FileName = sfd.InitialFileName;
  117. }
  118. Navigate(directory, (dialog as FileDialog)?.InitialFileName);
  119. SelectedItems.CollectionChanged += OnSelectionChangedAsync;
  120. }
  121. public void EnterPressed ()
  122. {
  123. if (Directory.Exists(Location))
  124. {
  125. Navigate(Location);
  126. }
  127. else if (File.Exists(Location))
  128. {
  129. CompleteRequested?.Invoke(new[] { Location });
  130. }
  131. }
  132. private async void OnSelectionChangedAsync(object sender, NotifyCollectionChangedEventArgs e)
  133. {
  134. if (_scheduledSelectionValidation)
  135. {
  136. return;
  137. }
  138. _scheduledSelectionValidation = true;
  139. await Dispatcher.UIThread.InvokeAsync(() =>
  140. {
  141. try
  142. {
  143. if (_selectingDirectory)
  144. {
  145. SelectedItems.Clear();
  146. }
  147. else
  148. {
  149. var invalidItems = SelectedItems.Where(i => i.IsDirectory).ToList();
  150. foreach (var item in invalidItems)
  151. {
  152. SelectedItems.Remove(item);
  153. }
  154. if(!_selectingDirectory)
  155. {
  156. FileName = SelectedItems.FirstOrDefault()?.DisplayName;
  157. }
  158. }
  159. }
  160. finally
  161. {
  162. _scheduledSelectionValidation = false;
  163. }
  164. });
  165. }
  166. void NavigateRoot(string initialSelectionName)
  167. {
  168. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  169. {
  170. Navigate(Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)), initialSelectionName);
  171. }
  172. else
  173. {
  174. Navigate("/", initialSelectionName);
  175. }
  176. }
  177. public void Refresh() => Navigate(Location);
  178. public void Navigate(string path, string initialSelectionName = null)
  179. {
  180. if (!Directory.Exists(path))
  181. {
  182. NavigateRoot(initialSelectionName);
  183. }
  184. else
  185. {
  186. Location = path;
  187. Items.Clear();
  188. SelectedItems.Clear();
  189. try
  190. {
  191. var infos = new DirectoryInfo(path).EnumerateFileSystemInfos();
  192. if (!ShowHiddenFiles)
  193. {
  194. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  195. {
  196. infos = infos.Where(i => (i.Attributes & (FileAttributes.Hidden | FileAttributes.System)) != 0);
  197. }
  198. else
  199. {
  200. infos = infos.Where(i => !i.Name.StartsWith("."));
  201. }
  202. }
  203. if (SelectedFilter != null)
  204. {
  205. infos = infos.Where(i => i is DirectoryInfo || SelectedFilter.Match(i.Name));
  206. }
  207. Items.AddRange(infos.Where(x =>
  208. {
  209. if (_selectingDirectory)
  210. {
  211. if (!(x is DirectoryInfo))
  212. {
  213. return false;
  214. }
  215. }
  216. return true;
  217. })
  218. .Where(x => x.Exists)
  219. .Select(info => new ManagedFileChooserItemViewModel
  220. {
  221. DisplayName = info.Name,
  222. Path = info.FullName,
  223. IsDirectory = info is DirectoryInfo,
  224. Type = info is FileInfo ? info.Extension : "File Folder",
  225. Size = info is FileInfo f ? f.Length : 0,
  226. Modified = info.LastWriteTime
  227. })
  228. .OrderByDescending(x => x.IsDirectory)
  229. .ThenBy(x => x.DisplayName, StringComparer.InvariantCultureIgnoreCase));
  230. if (initialSelectionName != null)
  231. {
  232. var sel = Items.FirstOrDefault(i => !i.IsDirectory && i.DisplayName == initialSelectionName);
  233. if (sel != null)
  234. {
  235. SelectedItems.Add(sel);
  236. }
  237. }
  238. this.RaisePropertyChanged(nameof(QuickLinksSelectedIndex));
  239. }
  240. catch (System.UnauthorizedAccessException)
  241. {
  242. }
  243. }
  244. }
  245. public void GoUp()
  246. {
  247. var parent = Path.GetDirectoryName(Location);
  248. if (string.IsNullOrWhiteSpace(parent))
  249. {
  250. return;
  251. }
  252. Navigate(parent);
  253. }
  254. public void Cancel()
  255. {
  256. CancelRequested?.Invoke();
  257. }
  258. public void Ok()
  259. {
  260. if (_selectingDirectory)
  261. {
  262. CompleteRequested?.Invoke(new[] { Location });
  263. }
  264. else if(_savingFile)
  265. {
  266. if (!string.IsNullOrWhiteSpace(FileName))
  267. {
  268. if (!Path.HasExtension(FileName) && !string.IsNullOrWhiteSpace(_defaultExtension))
  269. {
  270. FileName = Path.ChangeExtension(FileName, _defaultExtension);
  271. }
  272. CompleteRequested?.Invoke(new[] { Path.Combine(Location, FileName) });
  273. }
  274. }
  275. else
  276. {
  277. CompleteRequested?.Invoke(SelectedItems.Select(i => i.Path).ToArray());
  278. }
  279. }
  280. public void SelectSingleFile(ManagedFileChooserItemViewModel item)
  281. {
  282. CompleteRequested?.Invoke(new[] { item.Path });
  283. }
  284. }
  285. }