FileDialogState.cs 2.2 KB

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