FileDialogHistory.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #nullable disable
  2. using System.IO.Abstractions;
  3. namespace Terminal.Gui.Views;
  4. internal class FileDialogHistory
  5. {
  6. private readonly Stack<FileDialogState> back = new ();
  7. private readonly FileDialog dlg;
  8. private readonly Stack<FileDialogState> forward = new ();
  9. public FileDialogHistory (FileDialog dlg) { this.dlg = dlg; }
  10. public bool Back ()
  11. {
  12. IDirectoryInfo goTo = null;
  13. FileSystemInfoStats restoreSelection = null;
  14. string restorePath = null;
  15. if (CanBack ())
  16. {
  17. FileDialogState backTo = back.Pop ();
  18. goTo = backTo.Directory;
  19. restoreSelection = backTo.Selected;
  20. restorePath = backTo.Path;
  21. }
  22. else if (CanUp ())
  23. {
  24. goTo = dlg.State?.Directory.Parent;
  25. }
  26. // nowhere to go
  27. if (goTo is null)
  28. {
  29. return false;
  30. }
  31. forward.Push (dlg.State);
  32. dlg.PushState (goTo, false, true, false, restorePath);
  33. if (restoreSelection is { })
  34. {
  35. dlg.RestoreSelection (restoreSelection.FileSystemInfo);
  36. }
  37. return true;
  38. }
  39. internal bool CanBack () { return back.Count > 0; }
  40. internal bool CanForward () { return forward.Count > 0; }
  41. internal bool CanUp () { return dlg.State?.Directory.Parent != null; }
  42. internal void ClearForward () { forward.Clear (); }
  43. internal bool Forward ()
  44. {
  45. if (forward.Count > 0)
  46. {
  47. dlg.PushState (forward.Pop ().Directory, true, true, false);
  48. return true;
  49. }
  50. return false;
  51. }
  52. internal void Push (FileDialogState state, bool clearForward)
  53. {
  54. if (state is null)
  55. {
  56. return;
  57. }
  58. // if changing to a new directory push onto the Back history
  59. if (back.Count == 0 || back.Peek ().Directory.FullName != state.Directory.FullName)
  60. {
  61. back.Push (state);
  62. if (clearForward)
  63. {
  64. ClearForward ();
  65. }
  66. }
  67. }
  68. internal bool Up ()
  69. {
  70. IDirectoryInfo parent = dlg.State?.Directory.Parent;
  71. if (parent is { })
  72. {
  73. back.Push (new FileDialogState (parent, dlg));
  74. dlg.PushState (parent, false);
  75. return true;
  76. }
  77. return false;
  78. }
  79. }