FileDialogHistory.cs 2.1 KB

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