View.Hierarchy.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. using System.Diagnostics;
  2. using System.Diagnostics.CodeAnalysis;
  3. namespace Terminal.Gui.ViewBase;
  4. public partial class View // SuperView/SubView hierarchy management (SuperView, SubViews, Add, Remove, etc.)
  5. {
  6. private static readonly IReadOnlyCollection<View> _empty = [];
  7. private readonly List<View>? _subviews = [];
  8. // Internally, we use InternalSubViews rather than subviews, as we do not expect us
  9. // to make the same mistakes our users make when they poke at the SubViews.
  10. internal IList<View> InternalSubViews => _subviews ?? [];
  11. /// <summary>Gets the list of SubViews.</summary>
  12. /// <remarks>
  13. /// Use <see cref="Add(View?)"/> and <see cref="Remove(View?)"/> to add or remove subviews.
  14. /// </remarks>
  15. public IReadOnlyCollection<View> SubViews => InternalSubViews?.AsReadOnly () ?? _empty;
  16. private View? _superView;
  17. /// <summary>
  18. /// Gets this Views SuperView (the View's container), or <see langword="null"/> if this view has not been added as a
  19. /// SubView.
  20. /// </summary>
  21. /// <seealso cref="OnSuperViewChanging"/>
  22. /// <seealso cref="SuperViewChanging"/>
  23. /// <seealso cref="OnSuperViewChanged"/>
  24. /// <seealso cref="SuperViewChanged"/>
  25. public View? SuperView => _superView!;
  26. /// <summary>
  27. /// INTERNAL: Sets the SuperView of this View.
  28. /// </summary>
  29. /// <param name="value"></param>
  30. /// <returns><see langword="true"/> if the SuperView was changed; otherwise, <see langword="false"/>.</returns>
  31. private bool SetSuperView (View? value)
  32. {
  33. if (_superView == value)
  34. {
  35. return true;
  36. }
  37. return CWPPropertyHelper.ChangeProperty (
  38. this,
  39. ref _superView,
  40. value,
  41. OnSuperViewChanging,
  42. SuperViewChanging,
  43. newValue => _superView = newValue,
  44. OnSuperViewChanged,
  45. SuperViewChanged,
  46. out View? _);
  47. }
  48. /// <summary>
  49. /// Called when the SuperView of this View is about to be changed. This is called before the SuperView property
  50. /// is updated, allowing access to the current SuperView and its resources (such as <see cref="App"/>) for
  51. /// cleanup purposes.
  52. /// </summary>
  53. /// <param name="args">Hold the new SuperView that will be set, or <see langword="null"/> if being removed.</param>
  54. /// <returns><see langword="true"/> to cancel the change; <see langword="false"/> to allow it.</returns>
  55. protected virtual bool OnSuperViewChanging (ValueChangingEventArgs<View?> args) => false;
  56. /// <summary>
  57. /// Raised when the SuperView of this View is about to be changed. This is raised before the SuperView property
  58. /// is updated, allowing access to the current SuperView and its resources (such as <see cref="App"/>) for
  59. /// cleanup purposes.
  60. /// </summary>
  61. /// <remarks>
  62. /// <para>
  63. /// This event follows the Cancellable Work Pattern (CWP). Set <see cref="ValueChangingEventArgs{T}.Handled"/>
  64. /// to <see langword="true"/> in the event args to cancel the change.
  65. /// </para>
  66. /// </remarks>
  67. public event EventHandler<ValueChangingEventArgs<View?>>? SuperViewChanging;
  68. /// <summary>
  69. /// Called when the SuperView of this View has changed.
  70. /// </summary>
  71. protected virtual void OnSuperViewChanged (ValueChangedEventArgs<View?> args) { }
  72. /// <summary>Raised when the SuperView of this View has changed.</summary>
  73. public event EventHandler<ValueChangedEventArgs<View?>>? SuperViewChanged;
  74. #region AddRemove
  75. // TODO: Make this non-virtual once WizardStep is refactored to use events
  76. /// <summary>Adds a SubView (child) to this view.</summary>
  77. /// <remarks>
  78. /// <para>
  79. /// The Views that have been added to this view can be retrieved via the <see cref="SubViews"/> property.
  80. /// </para>
  81. /// <para>
  82. /// To check if a View has been added to this View, compare it's <see cref="SuperView"/> property to this View.
  83. /// </para>
  84. /// <para>
  85. /// SubViews will be disposed when this View is disposed. In other-words, calling this method causes
  86. /// the lifecycle of the subviews to be transferred to this View.
  87. /// </para>
  88. /// <para>
  89. /// Calls/Raises the <see cref="OnSubViewAdded"/>/<see cref="SubViewAdded"/> event.
  90. /// </para>
  91. /// <para>
  92. /// The <see cref="OnSuperViewChanged"/>/<see cref="SuperViewChanged"/> event will be raised on the added View.
  93. /// </para>
  94. /// </remarks>
  95. /// <param name="view">The view to add.</param>
  96. /// <returns>The view that was added.</returns>
  97. /// <seealso cref="Remove(View)"/>
  98. /// <seealso cref="RemoveAll"/>
  99. /// <seealso cref="OnSubViewAdded"/>
  100. /// <seealso cref="SubViewAdded"/>
  101. /// <seealso cref="OnSuperViewChanging"/>
  102. /// <seealso cref="SuperViewChanging"/>
  103. /// <seealso cref="OnSuperViewChanged"/>
  104. /// <seealso cref="SuperViewChanged"/>
  105. public virtual View? Add (View? view)
  106. {
  107. if (view is null)
  108. {
  109. return null;
  110. }
  111. //Debug.Assert (view.SuperView is null, $"{view} already has a SuperView: {view.SuperView}.");
  112. if (view.SuperView is { })
  113. {
  114. Logging.Warning ($"{view} already has a SuperView: {view.SuperView}.");
  115. }
  116. //Debug.Assert (!InternalSubViews.Contains (view), $"{view} has already been Added to {this}.");
  117. if (InternalSubViews.Contains (view))
  118. {
  119. Logging.Warning ($"{view} has already been Added to {this}.");
  120. }
  121. // TODO: Make this thread safe
  122. InternalSubViews.Add (view);
  123. // Try to set the SuperView - this may be cancelled
  124. if (!view.SetSuperView (this))
  125. {
  126. InternalSubViews.Remove (view);
  127. // The change was cancelled
  128. return null;
  129. }
  130. // Ensure views don't have focus when being added
  131. view.HasFocus = false;
  132. if (view is { Enabled: true, Visible: true, CanFocus: true })
  133. {
  134. // Add will cause the newly added subview to gain focus if it's focusable
  135. if (HasFocus)
  136. {
  137. view.SetFocus ();
  138. }
  139. }
  140. if (view.Enabled && !Enabled)
  141. {
  142. view.Enabled = false;
  143. }
  144. // Raise event indicating a subview has been added
  145. // We do this before Init.
  146. RaiseSubViewAdded (view);
  147. if (IsInitialized && !view.IsInitialized)
  148. {
  149. view.BeginInit ();
  150. view.EndInit ();
  151. }
  152. SetNeedsDraw ();
  153. SetNeedsLayout ();
  154. return view;
  155. }
  156. /// <summary>Adds the specified SubView (children) to the view.</summary>
  157. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  158. /// <remarks>
  159. /// <para>
  160. /// The Views that have been added to this view can be retrieved via the <see cref="SubViews"/> property. See also
  161. /// <seealso cref="Remove(View)"/> and <seealso cref="RemoveAll"/>.
  162. /// </para>
  163. /// <para>
  164. /// SubViews will be disposed when this View is disposed. In other-words, calling this method causes
  165. /// the lifecycle of the subviews to be transferred to this View.
  166. /// </para>
  167. /// </remarks>
  168. public void Add (params View []? views)
  169. {
  170. if (views is null)
  171. {
  172. return;
  173. }
  174. foreach (View view in views)
  175. {
  176. Add (view);
  177. }
  178. }
  179. internal void RaiseSubViewAdded (View view)
  180. {
  181. OnSubViewAdded (view);
  182. SubViewAdded?.Invoke (this, new (this, view));
  183. }
  184. /// <summary>
  185. /// Called when a SubView has been added to this View.
  186. /// </summary>
  187. /// <remarks>
  188. /// If the SubView has not been initialized, this happens before BeginInit/EndInit is called.
  189. /// </remarks>
  190. /// <param name="view"></param>
  191. protected virtual void OnSubViewAdded (View view) { }
  192. /// <summary>Raised when a SubView has been added to this View.</summary>
  193. /// <remarks>
  194. /// If the SubView has not been initialized, this happens before BeginInit/EndInit is called.
  195. /// </remarks>
  196. public event EventHandler<SuperViewChangedEventArgs>? SubViewAdded;
  197. // TODO: Make this non-virtual once WizardStep is refactored to use events
  198. /// <summary>Removes a SubView added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.</summary>
  199. /// <remarks>
  200. /// <para>
  201. /// Normally SubViews will be disposed when this View is disposed. Removing a SubView causes ownership of the
  202. /// SubView's
  203. /// lifecycle to be transferred to the caller; the caller must call <see cref="Dispose()"/>.
  204. /// </para>
  205. /// <para>
  206. /// Calls/Raises the <see cref="OnSubViewRemoved"/>/<see cref="SubViewRemoved"/> event.
  207. /// </para>
  208. /// <para>
  209. /// The <see cref="OnSuperViewChanged"/>/<see cref="SuperViewChanged"/> event will be raised on the removed View.
  210. /// </para>
  211. /// </remarks>
  212. /// <returns>
  213. /// The removed View. <see langword="null"/> if the View could not be removed.
  214. /// </returns>
  215. /// <seealso cref="Add(View)"/>
  216. /// <seealso cref="RemoveAll"/>
  217. /// <seealso cref="OnSubViewAdded"/>
  218. /// <seealso cref="OnSubViewRemoved"/>
  219. /// <seealso cref="SubViewRemoved"/>
  220. /// <seealso cref="OnSuperViewChanging"/>
  221. /// <seealso cref="SuperViewChanging"/>
  222. /// <seealso cref="OnSuperViewChanged"/>
  223. /// <seealso cref="SuperViewChanged"/>
  224. public virtual View? Remove (View? view)
  225. {
  226. if (view is null)
  227. {
  228. return null;
  229. }
  230. if (InternalSubViews.Count == 0)
  231. {
  232. return view;
  233. }
  234. if (view.SuperView is null)
  235. {
  236. Logging.Warning ($"{view} cannot be Removed. SuperView is null.");
  237. }
  238. if (view.SuperView != this)
  239. {
  240. Logging.Warning ($"{view} cannot be Removed. SuperView is not this ({view.SuperView}.");
  241. }
  242. if (!InternalSubViews.Contains (view))
  243. {
  244. Logging.Warning ($"{view} cannot be Removed. It has not been added to {this}.");
  245. }
  246. if (App?.Mouse.MouseGrabView == view)
  247. {
  248. App.Mouse.UngrabMouse ();
  249. }
  250. Rectangle touched = view.Frame;
  251. bool hadFocus = view.HasFocus;
  252. bool couldFocus = view.CanFocus;
  253. if (hadFocus)
  254. {
  255. view.CanFocus = false; // If view had focus, this will ensure it doesn't and it stays that way
  256. }
  257. Debug.Assert (!view.HasFocus);
  258. View? previousSuperView = view.SuperView;
  259. // Try to clear the SuperView - this may be cancelled
  260. if (!view.SetSuperView (null))
  261. {
  262. // The change was cancelled, restore state and return null
  263. view.CanFocus = couldFocus;
  264. return null;
  265. }
  266. Debug.Assert(view.SuperView is null);
  267. InternalSubViews.Remove (view);
  268. // Clean up focus stuff
  269. _previouslyFocused = null;
  270. if (previousSuperView is { } && previousSuperView._previouslyFocused == this)
  271. {
  272. previousSuperView._previouslyFocused = null;
  273. }
  274. SetNeedsLayout ();
  275. SetNeedsDraw ();
  276. foreach (View v in InternalSubViews)
  277. {
  278. if (v.Frame.IntersectsWith (touched))
  279. {
  280. view.SetNeedsDraw ();
  281. }
  282. }
  283. view.CanFocus = couldFocus; // Restore to previous value
  284. if (_previouslyFocused == view)
  285. {
  286. _previouslyFocused = null;
  287. }
  288. RaiseSubViewRemoved (view);
  289. return view;
  290. }
  291. internal void RaiseSubViewRemoved (View view)
  292. {
  293. OnSubViewRemoved (view);
  294. SubViewRemoved?.Invoke (this, new (this, view));
  295. }
  296. /// <summary>
  297. /// Called when a SubView has been removed from this View.
  298. /// </summary>
  299. /// <param name="view"></param>
  300. protected virtual void OnSubViewRemoved (View view) { }
  301. /// <summary>Raised when a SubView has been added to this View.</summary>
  302. public event EventHandler<SuperViewChangedEventArgs>? SubViewRemoved;
  303. // TODO: Make this non-virtual once WizardStep is refactored to use events
  304. /// <summary>
  305. /// Removes all SubViews added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  306. /// </summary>
  307. /// <remarks>
  308. /// <para>
  309. /// Normally SubViews will be disposed when this View is disposed. Removing a SubView causes ownership of the
  310. /// SubView's
  311. /// lifecycle to be transferred to the caller; the caller must call <see cref="Dispose()"/> on any Views that were
  312. /// added.
  313. /// </para>
  314. /// </remarks>
  315. /// <returns>
  316. /// A list of removed Views.
  317. /// </returns>
  318. /// <seealso cref="Add(View)"/>
  319. /// <seealso cref="Remove(View)"/>
  320. /// <seealso cref="OnSubViewAdded"/>
  321. /// <seealso cref="OnSubViewRemoved"/>
  322. /// <seealso cref="SubViewRemoved"/>
  323. /// <seealso cref="OnSuperViewChanging"/>
  324. /// <seealso cref="SuperViewChanging"/>
  325. /// <seealso cref="OnSuperViewChanged"/>
  326. /// <seealso cref="SuperViewChanged"/>
  327. public virtual IReadOnlyCollection<View> RemoveAll ()
  328. {
  329. List<View> removedList = new ();
  330. while (InternalSubViews.Count > 0)
  331. {
  332. View? removed = Remove (InternalSubViews [0]);
  333. if (removed is { })
  334. {
  335. removedList.Add (removed);
  336. }
  337. }
  338. return removedList.AsReadOnly ();
  339. }
  340. /// <summary>
  341. /// Removes all SubViews of a type added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  342. /// </summary>
  343. /// <remarks>
  344. /// <para>
  345. /// Normally SubViews will be disposed when this View is disposed. Removing a SubView causes ownership of the
  346. /// SubView's
  347. /// lifecycle to be transferred to the caller; the caller must call <see cref="Dispose()"/> on any Views that were
  348. /// added.
  349. /// </para>
  350. /// </remarks>
  351. /// <returns>
  352. /// A list of removed Views.
  353. /// </returns>
  354. public IReadOnlyCollection<TView> RemoveAll<TView> () where TView : View
  355. {
  356. List<TView> removedList = new ();
  357. foreach (TView view in InternalSubViews.OfType<TView> ().ToList ())
  358. {
  359. Remove (view);
  360. removedList.Add (view);
  361. }
  362. return removedList.AsReadOnly ();
  363. }
  364. #pragma warning disable CS0067 // The event is never used
  365. /// <summary>Raised when a SubView has been removed from this View.</summary>
  366. public event EventHandler<SuperViewChangedEventArgs>? Removed;
  367. #pragma warning restore CS0067 // The event is never used
  368. #endregion AddRemove
  369. // TODO: This drives a weird coupling of Application.TopRunnable and View. It's not clear why this is needed.
  370. /// <summary>Get the top superview of a given <see cref="View"/>.</summary>
  371. /// <returns>The superview view.</returns>
  372. internal View? GetTopSuperView (View? view = null, View? superview = null)
  373. {
  374. View? top = superview ?? App?.TopRunnableView;
  375. for (View? v = view?.SuperView ?? this?.SuperView; v != null; v = v.SuperView)
  376. {
  377. top = v;
  378. if (top == superview)
  379. {
  380. break;
  381. }
  382. }
  383. return top;
  384. }
  385. /// <summary>
  386. /// Gets whether <paramref name="view"/> is in the View hierarchy of <paramref name="start"/>.
  387. /// </summary>
  388. /// <param name="start">The View at the start of the hierarchy.</param>
  389. /// <param name="view">The View to test.</param>
  390. /// <param name="includeAdornments">Will include all <see cref="Adornment"/>s in addition to Subviews if true.</param>
  391. /// <returns></returns>
  392. public static bool IsInHierarchy (View? start, View? view, bool includeAdornments = false)
  393. {
  394. if (view is null || start is null)
  395. {
  396. return false;
  397. }
  398. if (view == start)
  399. {
  400. return true;
  401. }
  402. foreach (View subView in start.InternalSubViews)
  403. {
  404. if (view == subView)
  405. {
  406. return true;
  407. }
  408. bool found = IsInHierarchy (subView, view, includeAdornments);
  409. if (found)
  410. {
  411. return found;
  412. }
  413. }
  414. if (includeAdornments)
  415. {
  416. bool found = IsInHierarchy (start.Padding, view, includeAdornments);
  417. if (found)
  418. {
  419. return found;
  420. }
  421. found = IsInHierarchy (start.Border, view, includeAdornments);
  422. if (found)
  423. {
  424. return found;
  425. }
  426. found = IsInHierarchy (start.Margin, view, includeAdornments);
  427. if (found)
  428. {
  429. return found;
  430. }
  431. }
  432. return false;
  433. }
  434. #region SubViewOrdering
  435. /// <summary>
  436. /// Moves <paramref name="subview"/> one position towards the end of the <see cref="SubViews"/> list.
  437. /// </summary>
  438. /// <param name="subview">The subview to move.</param>
  439. public void MoveSubViewTowardsEnd (View subview)
  440. {
  441. PerformActionForSubView (
  442. subview,
  443. x =>
  444. {
  445. int idx = InternalSubViews!.IndexOf (x);
  446. if (idx + 1 < InternalSubViews.Count)
  447. {
  448. InternalSubViews.Remove (x);
  449. InternalSubViews.Insert (idx + 1, x);
  450. }
  451. }
  452. );
  453. }
  454. /// <summary>
  455. /// Moves <paramref name="subview"/> to the end of the <see cref="SubViews"/> list.
  456. /// If the <see cref="Arrangement"/> is <see cref="ViewArrangement.Overlapped"/>, keeps the original sorting.
  457. /// </summary>
  458. /// <param name="subview">The subview to move.</param>
  459. public void MoveSubViewToEnd (View subview)
  460. {
  461. if (Arrangement.HasFlag (ViewArrangement.Overlapped))
  462. {
  463. PerformActionForSubView (
  464. subview,
  465. x =>
  466. {
  467. while (InternalSubViews!.IndexOf (x) != InternalSubViews.Count - 1)
  468. {
  469. View v = InternalSubViews [0];
  470. InternalSubViews!.Remove (v);
  471. InternalSubViews.Add (v);
  472. }
  473. }
  474. );
  475. return;
  476. }
  477. PerformActionForSubView (
  478. subview,
  479. x =>
  480. {
  481. InternalSubViews!.Remove (x);
  482. InternalSubViews.Add (x);
  483. }
  484. );
  485. }
  486. /// <summary>
  487. /// Moves <paramref name="subview"/> one position towards the start of the <see cref="SubViews"/> list.
  488. /// </summary>
  489. /// <param name="subview">The subview to move.</param>
  490. public void MoveSubViewTowardsStart (View subview)
  491. {
  492. PerformActionForSubView (
  493. subview,
  494. x =>
  495. {
  496. int idx = InternalSubViews!.IndexOf (x);
  497. if (idx > 0)
  498. {
  499. InternalSubViews.Remove (x);
  500. InternalSubViews.Insert (idx - 1, x);
  501. }
  502. }
  503. );
  504. }
  505. /// <summary>
  506. /// Moves <paramref name="subview"/> to the start of the <see cref="SubViews"/> list.
  507. /// </summary>
  508. /// <param name="subview">The subview to move.</param>
  509. public void MoveSubViewToStart (View subview)
  510. {
  511. PerformActionForSubView (
  512. subview,
  513. x =>
  514. {
  515. InternalSubViews!.Remove (x);
  516. InternalSubViews.Insert (0, subview);
  517. }
  518. );
  519. }
  520. /// <summary>
  521. /// Internal API that runs <paramref name="action"/> on a subview if it is part of the <see cref="SubViews"/> list.
  522. /// </summary>
  523. /// <param name="subview"></param>
  524. /// <param name="action"></param>
  525. private void PerformActionForSubView (View subview, Action<View> action)
  526. {
  527. if (InternalSubViews.Contains (subview))
  528. {
  529. action (subview);
  530. }
  531. // BUGBUG: this is odd. Why is this needed?
  532. SetNeedsDraw ();
  533. subview.SetNeedsDraw ();
  534. }
  535. #endregion SubViewOrdering
  536. }