FileDialogState.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Abstractions;
  5. using System.Linq;
  6. namespace Terminal.Gui {
  7. internal class FileDialogState {
  8. public FileSystemInfoStats Selected { get; set; }
  9. protected readonly FileDialog Parent;
  10. public FileDialogState (IDirectoryInfo dir, FileDialog parent)
  11. {
  12. this.Directory = dir;
  13. Parent = parent;
  14. this.RefreshChildren ();
  15. }
  16. public IDirectoryInfo Directory { get; }
  17. public FileSystemInfoStats [] Children { get; protected set; }
  18. internal virtual void RefreshChildren ()
  19. {
  20. var dir = this.Directory;
  21. Children = GetChildren (dir).ToArray ();
  22. }
  23. protected virtual IEnumerable<FileSystemInfoStats> GetChildren (IDirectoryInfo dir)
  24. {
  25. try {
  26. List<FileSystemInfoStats> children;
  27. // if directories only
  28. if (Parent.OpenMode == OpenMode.Directory) {
  29. children = dir.GetDirectories ().Select (e => new FileSystemInfoStats (e)).ToList ();
  30. } else {
  31. children = dir.GetFileSystemInfos ().Select (e => new FileSystemInfoStats (e)).ToList ();
  32. }
  33. // if only allowing specific file types
  34. if (Parent.AllowedTypes.Any () && Parent.OpenMode == OpenMode.File) {
  35. children = children.Where (
  36. c => c.IsDir () ||
  37. (c.FileSystemInfo is IFileInfo f && Parent.IsCompatibleWithAllowedExtensions (f)))
  38. .ToList ();
  39. }
  40. // if theres a UI filter in place too
  41. if (Parent.CurrentFilter != null) {
  42. children = children.Where (MatchesApiFilter).ToList ();
  43. }
  44. // allow navigating up as '..'
  45. if (dir.Parent != null) {
  46. children.Add (new FileSystemInfoStats (dir.Parent) { IsParent = true });
  47. }
  48. return children;
  49. } catch (Exception) {
  50. // Access permissions Exceptions, Dir not exists etc
  51. return Enumerable.Empty<FileSystemInfoStats> ();
  52. }
  53. }
  54. protected bool MatchesApiFilter (FileSystemInfoStats arg)
  55. {
  56. return arg.IsDir () ||
  57. (arg.FileSystemInfo is IFileInfo f && Parent.CurrentFilter.IsAllowed (f.FullName));
  58. }
  59. }
  60. }