ApplicationNavigation.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Helper class for <see cref="Application"/> navigation. Held by <see cref="Application.Navigation"/>
  5. /// </summary>
  6. public class ApplicationNavigation
  7. {
  8. /// <summary>
  9. /// Initializes a new instance of the <see cref="ApplicationNavigation"/> class.
  10. /// </summary>
  11. public ApplicationNavigation ()
  12. {
  13. // TODO: Move navigation key bindings here from AddApplicationKeyBindings
  14. }
  15. private View? _focused = null;
  16. /// <summary>
  17. /// Gets the most focused <see cref="View"/> in the application, if there is one.
  18. /// </summary>
  19. public View? GetFocused () { return _focused; }
  20. /// <summary>
  21. /// INTERNAL method to record the most focused <see cref="View"/> in the application.
  22. /// </summary>
  23. /// <remarks>
  24. /// Raises <see cref="FocusedChanged"/>.
  25. /// </remarks>
  26. internal void SetFocused (View? value)
  27. {
  28. if (_focused == value)
  29. {
  30. return;
  31. }
  32. _focused = value;
  33. FocusedChanged?.Invoke (null, EventArgs.Empty);
  34. return;
  35. }
  36. /// <summary>
  37. /// Raised when the most focused <see cref="View"/> in the application has changed.
  38. /// </summary>
  39. public event EventHandler<EventArgs>? FocusedChanged;
  40. /// <summary>
  41. /// Gets whether <paramref name="view"/> is in the Subview hierarchy of <paramref name="start"/>.
  42. /// </summary>
  43. /// <param name="start"></param>
  44. /// <param name="view"></param>
  45. /// <returns></returns>
  46. public static bool IsInHierarchy (View? start, View? view)
  47. {
  48. if (view is null)
  49. {
  50. return false;
  51. }
  52. if (view == start || start is null)
  53. {
  54. return true;
  55. }
  56. foreach (View subView in start.Subviews)
  57. {
  58. if (view == subView)
  59. {
  60. return true;
  61. }
  62. var found = IsInHierarchy (subView, view);
  63. if (found)
  64. {
  65. return found;
  66. }
  67. }
  68. return false;
  69. }
  70. /// <summary>
  71. /// Gets the deepest focused subview of the specified <paramref name="view"/>.
  72. /// </summary>
  73. /// <param name="view"></param>
  74. /// <returns></returns>
  75. internal static View? GetDeepestFocusedSubview (View? view)
  76. {
  77. if (view is null)
  78. {
  79. return null;
  80. }
  81. foreach (View v in view.Subviews)
  82. {
  83. if (v.HasFocus)
  84. {
  85. return GetDeepestFocusedSubview (v);
  86. }
  87. }
  88. return view;
  89. }
  90. }