FileDialogState.cs 2.8 KB

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