FileDialogHistory.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. if (this.CanBack ()) {
  18. var backTo = this.back.Pop ();
  19. goTo = backTo.Directory;
  20. restoreSelection = backTo.Selected;
  21. } else if (this.CanUp ()) {
  22. goTo = this.dlg.State?.Directory.Parent;
  23. }
  24. // nowhere to go
  25. if (goTo == null) {
  26. return false;
  27. }
  28. this.forward.Push (this.dlg.State);
  29. this.dlg.PushState (goTo, false, true, false);
  30. if (restoreSelection != null) {
  31. this.dlg.RestoreSelection (restoreSelection.FileSystemInfo);
  32. }
  33. return true;
  34. }
  35. internal bool CanBack ()
  36. {
  37. return this.back.Count > 0;
  38. }
  39. internal bool Forward ()
  40. {
  41. if (this.forward.Count > 0) {
  42. this.dlg.PushState (this.forward.Pop ().Directory, true, true, false);
  43. return true;
  44. }
  45. return false;
  46. }
  47. internal bool Up ()
  48. {
  49. var parent = this.dlg.State?.Directory.Parent;
  50. if (parent != null) {
  51. this.back.Push (new FileDialogState (parent, this.dlg));
  52. this.dlg.PushState (parent, false);
  53. return true;
  54. }
  55. return false;
  56. }
  57. internal bool CanUp ()
  58. {
  59. return this.dlg.State?.Directory.Parent != null;
  60. }
  61. internal void Push (FileDialogState state, bool clearForward)
  62. {
  63. if (state == null) {
  64. return;
  65. }
  66. // if changing to a new directory push onto the Back history
  67. if (this.back.Count == 0 || this.back.Peek ().Directory.FullName != state.Directory.FullName) {
  68. this.back.Push (state);
  69. if (clearForward) {
  70. this.ClearForward ();
  71. }
  72. }
  73. }
  74. internal bool CanForward ()
  75. {
  76. return this.forward.Count > 0;
  77. }
  78. internal void ClearForward ()
  79. {
  80. this.forward.Clear ();
  81. }
  82. }
  83. }