ViewSubViews.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Terminal.Gui {
  7. public partial class View {
  8. static readonly IList<View> _empty = new List<View> (0).AsReadOnly ();
  9. View _superView = null;
  10. /// <summary>
  11. /// Returns the container for this view, or null if this view has not been added to a container.
  12. /// </summary>
  13. /// <value>The super view.</value>
  14. public virtual View SuperView {
  15. get {
  16. return _superView;
  17. }
  18. set {
  19. throw new NotImplementedException ();
  20. }
  21. }
  22. List<View> _subviews; // This is null, and allocated on demand.
  23. /// <summary>
  24. /// This returns a list of the subviews contained by this view.
  25. /// </summary>
  26. /// <value>The subviews.</value>
  27. public IList<View> Subviews => _subviews?.AsReadOnly () ?? _empty;
  28. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  29. // to make the same mistakes our users make when they poke at the Subviews.
  30. internal IList<View> InternalSubviews => _subviews ?? _empty;
  31. /// <summary>
  32. /// Returns a value indicating if this View is currently on Top (Active)
  33. /// </summary>
  34. public bool IsCurrentTop => Application.Current == this;
  35. /// <summary>
  36. /// Event fired when this view is added to another.
  37. /// </summary>
  38. public event EventHandler<SuperViewChangedEventArgs> Added;
  39. internal bool _addingView;
  40. /// <summary>
  41. /// Adds a subview (child) to this view.
  42. /// </summary>
  43. /// <remarks>
  44. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property.
  45. /// See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  46. /// </remarks>
  47. public virtual void Add (View view)
  48. {
  49. if (view == null) {
  50. return;
  51. }
  52. if (_subviews == null) {
  53. _subviews = new List<View> ();
  54. }
  55. if (_tabIndexes == null) {
  56. _tabIndexes = new List<View> ();
  57. }
  58. _subviews.Add (view);
  59. _tabIndexes.Add (view);
  60. view._superView = this;
  61. if (view.CanFocus) {
  62. _addingView = true;
  63. if (SuperView?.CanFocus == false) {
  64. SuperView._addingView = true;
  65. SuperView.CanFocus = true;
  66. SuperView._addingView = false;
  67. }
  68. CanFocus = true;
  69. view._tabIndex = _tabIndexes.IndexOf (view);
  70. _addingView = false;
  71. }
  72. if (view.Enabled && !Enabled) {
  73. view._oldEnabled = true;
  74. view.Enabled = false;
  75. }
  76. OnAdded (new SuperViewChangedEventArgs (this, view));
  77. if (IsInitialized && !view.IsInitialized) {
  78. view.BeginInit ();
  79. view.EndInit ();
  80. }
  81. SetNeedsLayout ();
  82. SetNeedsDisplay ();
  83. }
  84. /// <summary>
  85. /// Adds the specified views (children) to the view.
  86. /// </summary>
  87. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  88. /// <remarks>
  89. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property.
  90. /// See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  91. /// </remarks>
  92. public void Add (params View [] views)
  93. {
  94. if (views == null) {
  95. return;
  96. }
  97. foreach (var view in views) {
  98. Add (view);
  99. }
  100. }
  101. /// <summary>
  102. /// Method invoked when a subview is being added to this view.
  103. /// </summary>
  104. /// <param name="e">Event where <see cref="ViewEventArgs.View"/> is the subview being added.</param>
  105. public virtual void OnAdded (SuperViewChangedEventArgs e)
  106. {
  107. var view = e.Child;
  108. view.IsAdded = true;
  109. view.OnResizeNeeded ();
  110. view._x ??= view._frame.X;
  111. view._y ??= view._frame.Y;
  112. view._width ??= view._frame.Width;
  113. view._height ??= view._frame.Height;
  114. view.Added?.Invoke (this, e);
  115. }
  116. /// <summary>
  117. /// Indicates whether the view was added to <see cref="SuperView"/>.
  118. /// </summary>
  119. public bool IsAdded { get; private set; }
  120. /// <summary>
  121. /// Event fired when this view is removed from another.
  122. /// </summary>
  123. public event EventHandler<SuperViewChangedEventArgs> Removed;
  124. /// <summary>
  125. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  126. /// </summary>
  127. public virtual void RemoveAll ()
  128. {
  129. if (_subviews == null) {
  130. return;
  131. }
  132. while (_subviews.Count > 0) {
  133. Remove (_subviews [0]);
  134. }
  135. }
  136. /// <summary>
  137. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  138. /// </summary>
  139. /// <remarks>
  140. /// </remarks>
  141. public virtual void Remove (View view)
  142. {
  143. if (view == null || _subviews == null) return;
  144. var touched = view.Frame;
  145. _subviews.Remove (view);
  146. _tabIndexes.Remove (view);
  147. view._superView = null;
  148. view._tabIndex = -1;
  149. SetNeedsLayout ();
  150. SetNeedsDisplay ();
  151. foreach (var v in _subviews) {
  152. if (v.Frame.IntersectsWith (touched))
  153. view.SetNeedsDisplay ();
  154. }
  155. OnRemoved (new SuperViewChangedEventArgs (this, view));
  156. if (_focused == view) {
  157. _focused = null;
  158. }
  159. }
  160. /// <summary>
  161. /// Method invoked when a subview is being removed from this view.
  162. /// </summary>
  163. /// <param name="e">Event args describing the subview being removed.</param>
  164. public virtual void OnRemoved (SuperViewChangedEventArgs e)
  165. {
  166. var view = e.Child;
  167. view.IsAdded = false;
  168. view.Removed?.Invoke (this, e);
  169. }
  170. void PerformActionForSubview (View subview, Action<View> action)
  171. {
  172. if (_subviews.Contains (subview)) {
  173. action (subview);
  174. }
  175. SetNeedsDisplay ();
  176. subview.SetNeedsDisplay ();
  177. }
  178. /// <summary>
  179. /// Brings the specified subview to the front so it is drawn on top of any other views.
  180. /// </summary>
  181. /// <param name="subview">The subview to send to the front</param>
  182. /// <remarks>
  183. /// <seealso cref="SendSubviewToBack"/>.
  184. /// </remarks>
  185. public void BringSubviewToFront (View subview)
  186. {
  187. PerformActionForSubview (subview, x => {
  188. _subviews.Remove (x);
  189. _subviews.Add (x);
  190. });
  191. }
  192. /// <summary>
  193. /// Sends the specified subview to the front so it is the first view drawn
  194. /// </summary>
  195. /// <param name="subview">The subview to send to the front</param>
  196. /// <remarks>
  197. /// <seealso cref="BringSubviewToFront(View)"/>.
  198. /// </remarks>
  199. public void SendSubviewToBack (View subview)
  200. {
  201. PerformActionForSubview (subview, x => {
  202. _subviews.Remove (x);
  203. _subviews.Insert (0, subview);
  204. });
  205. }
  206. /// <summary>
  207. /// Moves the subview backwards in the hierarchy, only one step
  208. /// </summary>
  209. /// <param name="subview">The subview to send backwards</param>
  210. /// <remarks>
  211. /// If you want to send the view all the way to the back use SendSubviewToBack.
  212. /// </remarks>
  213. public void SendSubviewBackwards (View subview)
  214. {
  215. PerformActionForSubview (subview, x => {
  216. var idx = _subviews.IndexOf (x);
  217. if (idx > 0) {
  218. _subviews.Remove (x);
  219. _subviews.Insert (idx - 1, x);
  220. }
  221. });
  222. }
  223. /// <summary>
  224. /// Moves the subview backwards in the hierarchy, only one step
  225. /// </summary>
  226. /// <param name="subview">The subview to send backwards</param>
  227. /// <remarks>
  228. /// If you want to send the view all the way to the back use SendSubviewToBack.
  229. /// </remarks>
  230. public void BringSubviewForward (View subview)
  231. {
  232. PerformActionForSubview (subview, x => {
  233. var idx = _subviews.IndexOf (x);
  234. if (idx + 1 < _subviews.Count) {
  235. _subviews.Remove (x);
  236. _subviews.Insert (idx + 1, x);
  237. }
  238. });
  239. }
  240. /// <summary>
  241. /// Get the top superview of a given <see cref="View"/>.
  242. /// </summary>
  243. /// <returns>The superview view.</returns>
  244. public View GetTopSuperView (View view = null, View superview = null)
  245. {
  246. View top = superview ?? Application.Top;
  247. for (var v = view?.SuperView ?? (this?.SuperView); v != null; v = v.SuperView) {
  248. top = v;
  249. if (top == superview) {
  250. break;
  251. }
  252. }
  253. return top;
  254. }
  255. #region Focus
  256. View _focused = null;
  257. internal enum Direction {
  258. Forward,
  259. Backward
  260. }
  261. /// <summary>
  262. /// Event fired when the view gets focus.
  263. /// </summary>
  264. public event EventHandler<FocusEventArgs> Enter;
  265. /// <summary>
  266. /// Event fired when the view looses focus.
  267. /// </summary>
  268. public event EventHandler<FocusEventArgs> Leave;
  269. Direction _focusDirection;
  270. internal Direction FocusDirection {
  271. get => SuperView?.FocusDirection ?? _focusDirection;
  272. set {
  273. if (SuperView != null)
  274. SuperView.FocusDirection = value;
  275. else
  276. _focusDirection = value;
  277. }
  278. }
  279. // BUGBUG: v2 - Seems weird that this is in View and not Responder.
  280. bool _hasFocus;
  281. /// <inheritdoc/>
  282. public override bool HasFocus => _hasFocus;
  283. void SetHasFocus (bool value, View view, bool force = false)
  284. {
  285. if (_hasFocus != value || force) {
  286. _hasFocus = value;
  287. if (value) {
  288. OnEnter (view);
  289. } else {
  290. OnLeave (view);
  291. }
  292. SetNeedsDisplay ();
  293. }
  294. // Remove focus down the chain of subviews if focus is removed
  295. if (!value && _focused != null) {
  296. var f = _focused;
  297. f.OnLeave (view);
  298. f.SetHasFocus (false, view);
  299. _focused = null;
  300. }
  301. }
  302. /// <summary>
  303. /// Event fired when the <see cref="CanFocus"/> value is being changed.
  304. /// </summary>
  305. public event EventHandler CanFocusChanged;
  306. /// <inheritdoc/>
  307. public override void OnCanFocusChanged () => CanFocusChanged?.Invoke (this, EventArgs.Empty);
  308. bool _oldCanFocus;
  309. /// <inheritdoc/>
  310. public override bool CanFocus {
  311. get => base.CanFocus;
  312. set {
  313. if (!_addingView && IsInitialized && SuperView?.CanFocus == false && value) {
  314. throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
  315. }
  316. if (base.CanFocus != value) {
  317. base.CanFocus = value;
  318. switch (value) {
  319. case false when _tabIndex > -1:
  320. TabIndex = -1;
  321. break;
  322. case true when SuperView?.CanFocus == false && _addingView:
  323. SuperView.CanFocus = true;
  324. break;
  325. }
  326. if (value && _tabIndex == -1) {
  327. TabIndex = SuperView != null ? SuperView._tabIndexes.IndexOf (this) : -1;
  328. }
  329. TabStop = value;
  330. if (!value && SuperView?.Focused == this) {
  331. SuperView._focused = null;
  332. }
  333. if (!value && HasFocus) {
  334. SetHasFocus (false, this);
  335. SuperView?.EnsureFocus ();
  336. if (SuperView != null && SuperView.Focused == null) {
  337. SuperView.FocusNext ();
  338. if (SuperView.Focused == null && Application.Current != null) {
  339. Application.Current.FocusNext ();
  340. }
  341. Application.BringOverlappedTopToFront ();
  342. }
  343. }
  344. if (_subviews != null && IsInitialized) {
  345. foreach (var view in _subviews) {
  346. if (view.CanFocus != value) {
  347. if (!value) {
  348. view._oldCanFocus = view.CanFocus;
  349. view._oldTabIndex = view._tabIndex;
  350. view.CanFocus = false;
  351. view._tabIndex = -1;
  352. } else {
  353. if (_addingView) {
  354. view._addingView = true;
  355. }
  356. view.CanFocus = view._oldCanFocus;
  357. view._tabIndex = view._oldTabIndex;
  358. view._addingView = false;
  359. }
  360. }
  361. }
  362. }
  363. OnCanFocusChanged ();
  364. SetNeedsDisplay ();
  365. }
  366. }
  367. }
  368. /// <inheritdoc/>
  369. public override bool OnEnter (View view)
  370. {
  371. var args = new FocusEventArgs (view);
  372. Enter?.Invoke (this, args);
  373. if (args.Handled) {
  374. return true;
  375. }
  376. if (base.OnEnter (view)) {
  377. return true;
  378. }
  379. return false;
  380. }
  381. /// <inheritdoc/>
  382. public override bool OnLeave (View view)
  383. {
  384. var args = new FocusEventArgs (view);
  385. Leave?.Invoke (this, args);
  386. if (args.Handled) {
  387. return true;
  388. }
  389. if (base.OnLeave (view)) {
  390. return true;
  391. }
  392. Driver?.SetCursorVisibility (CursorVisibility.Invisible);
  393. return false;
  394. }
  395. /// <summary>
  396. /// Returns the currently focused view inside this view, or null if nothing is focused.
  397. /// </summary>
  398. /// <value>The focused.</value>
  399. public View Focused => _focused;
  400. /// <summary>
  401. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  402. /// </summary>
  403. /// <value>The most focused View.</value>
  404. public View MostFocused {
  405. get {
  406. if (Focused == null)
  407. return null;
  408. var most = Focused.MostFocused;
  409. if (most != null)
  410. return most;
  411. return Focused;
  412. }
  413. }
  414. /// <summary>
  415. /// Causes the specified subview to have focus.
  416. /// </summary>
  417. /// <param name="view">View.</param>
  418. void SetFocus (View view)
  419. {
  420. if (view == null) {
  421. return;
  422. }
  423. //Console.WriteLine ($"Request to focus {view}");
  424. if (!view.CanFocus || !view.Visible || !view.Enabled) {
  425. return;
  426. }
  427. if (_focused?._hasFocus == true && _focused == view) {
  428. return;
  429. }
  430. if ((_focused?._hasFocus == true && _focused?.SuperView == view) || view == this) {
  431. if (!view._hasFocus) {
  432. view._hasFocus = true;
  433. }
  434. return;
  435. }
  436. // Make sure that this view is a subview
  437. View c;
  438. for (c = view._superView; c != null; c = c._superView)
  439. if (c == this)
  440. break;
  441. if (c == null)
  442. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  443. if (_focused != null)
  444. _focused.SetHasFocus (false, view);
  445. var f = _focused;
  446. _focused = view;
  447. _focused.SetHasFocus (true, f);
  448. _focused.EnsureFocus ();
  449. // Send focus upwards
  450. if (SuperView != null) {
  451. SuperView.SetFocus (this);
  452. } else {
  453. SetFocus (this);
  454. }
  455. }
  456. /// <summary>
  457. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  458. /// </summary>
  459. public void SetFocus ()
  460. {
  461. if (!CanBeVisible (this) || !Enabled) {
  462. if (HasFocus) {
  463. SetHasFocus (false, this);
  464. }
  465. return;
  466. }
  467. if (SuperView != null) {
  468. SuperView.SetFocus (this);
  469. } else {
  470. SetFocus (this);
  471. }
  472. }
  473. /// <summary>
  474. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, does nothing.
  475. /// </summary>
  476. public void EnsureFocus ()
  477. {
  478. if (_focused == null && _subviews?.Count > 0) {
  479. if (FocusDirection == Direction.Forward) {
  480. FocusFirst ();
  481. } else {
  482. FocusLast ();
  483. }
  484. }
  485. }
  486. /// <summary>
  487. /// Focuses the first focusable subview if one exists.
  488. /// </summary>
  489. public void FocusFirst ()
  490. {
  491. if (!CanBeVisible (this)) {
  492. return;
  493. }
  494. if (_tabIndexes == null) {
  495. SuperView?.SetFocus (this);
  496. return;
  497. }
  498. foreach (var view in _tabIndexes) {
  499. if (view.CanFocus && view._tabStop && view.Visible && view.Enabled) {
  500. SetFocus (view);
  501. return;
  502. }
  503. }
  504. }
  505. /// <summary>
  506. /// Focuses the last focusable subview if one exists.
  507. /// </summary>
  508. public void FocusLast ()
  509. {
  510. if (!CanBeVisible (this)) {
  511. return;
  512. }
  513. if (_tabIndexes == null) {
  514. SuperView?.SetFocus (this);
  515. return;
  516. }
  517. for (var i = _tabIndexes.Count; i > 0;) {
  518. i--;
  519. var v = _tabIndexes [i];
  520. if (v.CanFocus && v._tabStop && v.Visible && v.Enabled) {
  521. SetFocus (v);
  522. return;
  523. }
  524. }
  525. }
  526. /// <summary>
  527. /// Focuses the previous view.
  528. /// </summary>
  529. /// <returns><see langword="true"/> if previous was focused, <see langword="false"/> otherwise.</returns>
  530. public bool FocusPrev ()
  531. {
  532. if (!CanBeVisible (this)) {
  533. return false;
  534. }
  535. FocusDirection = Direction.Backward;
  536. if (_tabIndexes == null || _tabIndexes.Count == 0)
  537. return false;
  538. if (_focused == null) {
  539. FocusLast ();
  540. return _focused != null;
  541. }
  542. var focusedIdx = -1;
  543. for (var i = _tabIndexes.Count; i > 0;) {
  544. i--;
  545. var w = _tabIndexes [i];
  546. if (w.HasFocus) {
  547. if (w.FocusPrev ())
  548. return true;
  549. focusedIdx = i;
  550. continue;
  551. }
  552. if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled) {
  553. _focused.SetHasFocus (false, w);
  554. if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
  555. w.FocusLast ();
  556. SetFocus (w);
  557. return true;
  558. }
  559. }
  560. if (_focused != null) {
  561. _focused.SetHasFocus (false, this);
  562. _focused = null;
  563. }
  564. return false;
  565. }
  566. /// <summary>
  567. /// Focuses the next view.
  568. /// </summary>
  569. /// <returns><see langword="true"/> if next was focused, <see langword="false"/> otherwise.</returns>
  570. public bool FocusNext ()
  571. {
  572. if (!CanBeVisible (this)) {
  573. return false;
  574. }
  575. FocusDirection = Direction.Forward;
  576. if (_tabIndexes == null || _tabIndexes.Count == 0)
  577. return false;
  578. if (_focused == null) {
  579. FocusFirst ();
  580. return _focused != null;
  581. }
  582. var focusedIdx = -1;
  583. for (var i = 0; i < _tabIndexes.Count; i++) {
  584. var w = _tabIndexes [i];
  585. if (w.HasFocus) {
  586. if (w.FocusNext ())
  587. return true;
  588. focusedIdx = i;
  589. continue;
  590. }
  591. if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled) {
  592. _focused.SetHasFocus (false, w);
  593. if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
  594. w.FocusFirst ();
  595. SetFocus (w);
  596. return true;
  597. }
  598. }
  599. if (_focused != null) {
  600. _focused.SetHasFocus (false, this);
  601. _focused = null;
  602. }
  603. return false;
  604. }
  605. View GetMostFocused (View view)
  606. {
  607. if (view == null) {
  608. return null;
  609. }
  610. return view._focused != null ? GetMostFocused (view._focused) : view;
  611. }
  612. /// <summary>
  613. /// Positions the cursor in the right position based on the currently focused view in the chain.
  614. /// </summary>
  615. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  616. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  617. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  618. /// the last focused view. Views should make sure that they place the cursor
  619. /// in a visually sensible place.
  620. public virtual void PositionCursor ()
  621. {
  622. if (!CanBeVisible (this) || !Enabled) {
  623. return;
  624. }
  625. // BUGBUG: v2 - This needs to support children of Frames too
  626. if (_focused == null && SuperView != null) {
  627. SuperView.EnsureFocus ();
  628. } else if (_focused?.Visible == true && _focused?.Enabled == true && _focused?.Frame.Width > 0 && _focused.Frame.Height > 0) {
  629. _focused.PositionCursor ();
  630. } else if (_focused?.Visible == true && _focused?.Enabled == false) {
  631. _focused = null;
  632. } else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  633. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  634. } else {
  635. Move (_frame.X, _frame.Y);
  636. }
  637. }
  638. #endregion Focus
  639. }
  640. }