FileDialogState.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.IO.Abstractions;
  2. namespace Terminal.Gui;
  3. internal class FileDialogState
  4. {
  5. protected readonly FileDialog Parent;
  6. public FileDialogState (IDirectoryInfo dir, FileDialog parent)
  7. {
  8. Directory = dir;
  9. Parent = parent;
  10. Path = parent.Path;
  11. RefreshChildren ();
  12. }
  13. public FileSystemInfoStats [] Children { get; internal set; }
  14. public IDirectoryInfo Directory { get; }
  15. /// <summary>Gets what was entered in the path text box of the dialog when the state was active.</summary>
  16. public string Path { get; }
  17. public FileSystemInfoStats Selected { get; set; }
  18. protected virtual IEnumerable<FileSystemInfoStats> GetChildren (IDirectoryInfo dir)
  19. {
  20. try
  21. {
  22. List<FileSystemInfoStats> children;
  23. // if directories only
  24. if (Parent.OpenMode == OpenMode.Directory)
  25. {
  26. children = dir.GetDirectories ()
  27. .Select (e => new FileSystemInfoStats (e, Parent.Style.Culture))
  28. .ToList ();
  29. }
  30. else
  31. {
  32. children = dir.GetFileSystemInfos ()
  33. .Select (e => new FileSystemInfoStats (e, Parent.Style.Culture))
  34. .ToList ();
  35. }
  36. // if only allowing specific file types
  37. if (Parent.AllowedTypes.Any () && Parent.OpenMode == OpenMode.File)
  38. {
  39. children = children.Where (
  40. c => c.IsDir
  41. || (c.FileSystemInfo is IFileInfo f
  42. && Parent.IsCompatibleWithAllowedExtensions (f))
  43. )
  44. .ToList ();
  45. }
  46. // if there's a UI filter in place too
  47. if (Parent.CurrentFilter is { })
  48. {
  49. children = children.Where (MatchesApiFilter).ToList ();
  50. }
  51. // allow navigating up as '..'
  52. if (dir.Parent is { })
  53. {
  54. children.Add (new FileSystemInfoStats (dir.Parent, Parent.Style.Culture) { IsParent = true });
  55. }
  56. return children;
  57. }
  58. catch (Exception)
  59. {
  60. // Access permissions Exceptions, Dir not exists etc
  61. return Enumerable.Empty<FileSystemInfoStats> ();
  62. }
  63. }
  64. protected bool MatchesApiFilter (FileSystemInfoStats arg)
  65. {
  66. return arg.IsDir
  67. || (arg.FileSystemInfo is IFileInfo f
  68. && Parent.CurrentFilter.IsAllowed (f.FullName));
  69. }
  70. internal virtual void RefreshChildren ()
  71. {
  72. IDirectoryInfo dir = Directory;
  73. Children = GetChildren (dir).ToArray ();
  74. }
  75. }