View.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. namespace Terminal.Gui;
  6. #region API Docs
  7. /// <summary>
  8. /// View is the base class all visible elements. View can render itself and
  9. /// contains zero or more nested views, called SubViews. View provides basic functionality for layout, arrangement, and
  10. /// drawing. In addition, View provides keyboard and mouse event handling.
  11. /// <para>
  12. /// See the
  13. /// <see href="../docs/view.md">
  14. /// View
  15. /// Deep Dive
  16. /// </see>
  17. /// for more.
  18. /// </para>
  19. /// </summary>
  20. #endregion API Docs
  21. public partial class View : IDisposable, ISupportInitializeNotification
  22. {
  23. private bool _disposedValue;
  24. /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resource.</summary>
  25. public void Dispose ()
  26. {
  27. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  28. Disposing?.Invoke (this, EventArgs.Empty);
  29. Dispose (true);
  30. GC.SuppressFinalize (this);
  31. #if DEBUG_IDISPOSABLE
  32. WasDisposed = true;
  33. // Safely remove any disposed views from the Instances list
  34. List<View> itemsToKeep = Instances.Where (view => !view.WasDisposed).ToList ();
  35. Instances = new ConcurrentBag<View> (itemsToKeep);
  36. #endif
  37. }
  38. /// <summary>
  39. /// Riased when the <see cref="View"/> is being disposed.
  40. /// </summary>
  41. public event EventHandler? Disposing;
  42. /// <summary>Pretty prints the View</summary>
  43. /// <returns></returns>
  44. public override string ToString () { return $"{GetType ().Name}({Id}){Frame}"; }
  45. /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
  46. /// <remarks>
  47. /// If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and
  48. /// unmanaged resources can be disposed. If disposing equals false, the method has been called by the runtime from
  49. /// inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed.
  50. /// </remarks>
  51. /// <param name="disposing"></param>
  52. protected virtual void Dispose (bool disposing)
  53. {
  54. if (disposing)
  55. {
  56. LineCanvas.Dispose ();
  57. DisposeMouse ();
  58. DisposeKeyboard ();
  59. DisposeAdornments ();
  60. DisposeScrollBars ();
  61. for (int i = InternalSubViews.Count - 1; i >= 0; i--)
  62. {
  63. View subview = InternalSubViews [i];
  64. Remove (subview);
  65. subview.Dispose ();
  66. }
  67. if (!_disposedValue)
  68. {
  69. if (disposing)
  70. {
  71. // TODO: dispose managed state (managed objects)
  72. }
  73. _disposedValue = true;
  74. }
  75. Debug.Assert (InternalSubViews.Count == 0);
  76. }
  77. }
  78. #region Constructors and Initialization
  79. /// <summary>Gets or sets arbitrary data for the view.</summary>
  80. /// <remarks>This property is not used internally.</remarks>
  81. public object? Data { get; set; }
  82. /// <summary>Gets or sets an identifier for the view;</summary>
  83. /// <value>The identifier.</value>
  84. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  85. public string Id { get; set; } = "";
  86. /// <summary>
  87. /// Points to the current driver in use by the view, it is a convenience property for simplifying the development
  88. /// of new views.
  89. /// </summary>
  90. public static IConsoleDriver? Driver => Application.Driver;
  91. /// <summary>Initializes a new instance of <see cref="View"/>.</summary>
  92. /// <remarks>
  93. /// <para>
  94. /// Use <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties to dynamically
  95. /// control the size and location of the view.
  96. /// </para>
  97. /// </remarks>
  98. public View ()
  99. {
  100. #if DEBUG_IDISPOSABLE
  101. Instances.Add (this);
  102. #endif
  103. SetupAdornments ();
  104. SetupCommands ();
  105. SetupKeyboard ();
  106. SetupMouse ();
  107. SetupText ();
  108. SetupScrollBars ();
  109. }
  110. /// <summary>
  111. /// Raised once when the <see cref="View"/> is being initialized for the first time. Allows
  112. /// configurations and assignments to be performed before the <see cref="View"/> being shown.
  113. /// View implements <see cref="ISupportInitializeNotification"/> to allow for more sophisticated initialization.
  114. /// </summary>
  115. public event EventHandler? Initialized;
  116. /// <summary>
  117. /// Get or sets if the <see cref="View"/> has been initialized (via <see cref="ISupportInitialize.BeginInit"/>
  118. /// and <see cref="ISupportInitialize.EndInit"/>).
  119. /// </summary>
  120. /// <para>
  121. /// If first-run-only initialization is preferred, overrides to
  122. /// <see cref="ISupportInitializeNotification.IsInitialized"/> can be implemented, in which case the
  123. /// <see cref="ISupportInitialize"/> methods will only be called if
  124. /// <see cref="ISupportInitializeNotification.IsInitialized"/> is <see langword="false"/>. This allows proper
  125. /// <see cref="View"/> inheritance hierarchies to override base class layout code optimally by doing so only on first
  126. /// run, instead of on every run.
  127. /// </para>
  128. public virtual bool IsInitialized { get; set; }
  129. /// <summary>Signals the View that initialization is starting. See <see cref="ISupportInitialize"/>.</summary>
  130. /// <remarks>
  131. /// <para>
  132. /// Views can opt-in to more sophisticated initialization by implementing overrides to
  133. /// <see cref="ISupportInitialize.BeginInit"/> and <see cref="ISupportInitialize.EndInit"/> which will be called
  134. /// when the <see cref="SuperView"/> is initialized.
  135. /// </para>
  136. /// <para>
  137. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/> can
  138. /// be implemented too, in which case the <see cref="ISupportInitialize"/> methods will only be called if
  139. /// <see cref="ISupportInitializeNotification.IsInitialized"/> is <see langword="false"/>. This allows proper
  140. /// <see cref="View"/> inheritance hierarchies to override base class layout code optimally by doing so only on
  141. /// first run, instead of on every run.
  142. /// </para>
  143. /// </remarks>
  144. public virtual void BeginInit ()
  145. {
  146. if (IsInitialized)
  147. {
  148. throw new InvalidOperationException ("The view is already initialized.");
  149. }
  150. #if AUTO_CANFOCUS
  151. _oldCanFocus = CanFocus;
  152. _oldTabIndex = _tabIndex;
  153. #endif
  154. BeginInitAdornments ();
  155. if (InternalSubViews?.Count > 0)
  156. {
  157. foreach (View view in InternalSubViews)
  158. {
  159. if (!view.IsInitialized)
  160. {
  161. view.BeginInit ();
  162. }
  163. }
  164. }
  165. }
  166. // TODO: Implement logic that allows EndInit to throw if BeginInit has not been called
  167. // TODO: See EndInit_Called_Without_BeginInit_Throws test.
  168. /// <summary>Signals the View that initialization is ending. See <see cref="ISupportInitialize"/>.</summary>
  169. /// <remarks>
  170. /// <para>Initializes all SubViews and Invokes the <see cref="Initialized"/> event.</para>
  171. /// </remarks>
  172. public virtual void EndInit ()
  173. {
  174. if (IsInitialized)
  175. {
  176. throw new InvalidOperationException ("The view is already initialized.");
  177. }
  178. IsInitialized = true;
  179. EndInitAdornments ();
  180. // TODO: Move these into ViewText.cs as EndInit_Text() to consolidate.
  181. // TODO: Verify UpdateTextDirection really needs to be called here.
  182. // These calls were moved from BeginInit as they access Viewport which is indeterminate until EndInit is called.
  183. UpdateTextDirection (TextDirection);
  184. UpdateTextFormatterText ();
  185. foreach (View view in InternalSubViews)
  186. {
  187. if (!view.IsInitialized)
  188. {
  189. view.EndInit ();
  190. }
  191. }
  192. if (ApplicationImpl.Instance.IsLegacy)
  193. {
  194. // TODO: Figure out how to move this out of here and just depend on LayoutNeeded in Mainloop
  195. Layout (); // the EventLog in AllViewsTester fails to layout correctly if this is not here (convoluted Dim.Fill(Func)).
  196. }
  197. SetNeedsLayout ();
  198. Initialized?.Invoke (this, EventArgs.Empty);
  199. }
  200. #endregion Constructors and Initialization
  201. #region Visibility
  202. private bool _enabled = true;
  203. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can respond to user interaction.</summary>
  204. public bool Enabled
  205. {
  206. get => _enabled;
  207. set
  208. {
  209. if (_enabled == value)
  210. {
  211. return;
  212. }
  213. _enabled = value;
  214. if (!_enabled && HasFocus)
  215. {
  216. HasFocus = false;
  217. }
  218. if (_enabled
  219. && CanFocus
  220. && Visible
  221. && !HasFocus
  222. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  223. {
  224. SetFocus ();
  225. }
  226. OnEnabledChanged ();
  227. SetNeedsDraw ();
  228. if (Border is { })
  229. {
  230. Border.Enabled = _enabled;
  231. }
  232. foreach (View view in InternalSubViews)
  233. {
  234. view.Enabled = Enabled;
  235. }
  236. }
  237. }
  238. /// <summary>Raised when the <see cref="Enabled"/> value is being changed.</summary>
  239. public event EventHandler? EnabledChanged;
  240. // TODO: Change this event to match the standard TG event model.
  241. /// <summary>Invoked when the <see cref="Enabled"/> property from a view is changed.</summary>
  242. public virtual void OnEnabledChanged () { EnabledChanged?.Invoke (this, EventArgs.Empty); }
  243. private bool _visible = true;
  244. // TODO: Remove virtual once Menu/MenuBar are removed. MenuBar is the only override.
  245. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> is visible.</summary>
  246. public virtual bool Visible
  247. {
  248. get => _visible;
  249. set
  250. {
  251. if (_visible == value)
  252. {
  253. return;
  254. }
  255. if (OnVisibleChanging ())
  256. {
  257. return;
  258. }
  259. CancelEventArgs<bool> args = new (in _visible, ref value);
  260. VisibleChanging?.Invoke (this, args);
  261. if (args.Cancel)
  262. {
  263. return;
  264. }
  265. _visible = value;
  266. if (!_visible)
  267. {
  268. // BUGBUG: Ideally we'd reset _previouslyFocused to the first focusable subview
  269. _previouslyFocused = SubViews.FirstOrDefault (v => v.CanFocus);
  270. if (HasFocus)
  271. {
  272. HasFocus = false;
  273. }
  274. }
  275. if (_visible
  276. && CanFocus
  277. && Enabled
  278. && !HasFocus
  279. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  280. {
  281. SetFocus ();
  282. }
  283. OnVisibleChanged ();
  284. VisibleChanged?.Invoke (this, EventArgs.Empty);
  285. SetNeedsLayout ();
  286. SuperView?.SetNeedsLayout ();
  287. SetNeedsDraw ();
  288. if (SuperView is { })
  289. {
  290. SuperView?.SetNeedsDraw ();
  291. }
  292. else
  293. {
  294. Application.ClearScreenNextIteration = true;
  295. }
  296. }
  297. }
  298. /// <summary>Called when <see cref="Visible"/> is changing. Can be cancelled by returning <see langword="true"/>.</summary>
  299. protected virtual bool OnVisibleChanging () { return false; }
  300. /// <summary>
  301. /// Raised when the <see cref="Visible"/> value is being changed. Can be cancelled by setting Cancel to
  302. /// <see langword="true"/>.
  303. /// </summary>
  304. public event EventHandler<CancelEventArgs<bool>>? VisibleChanging;
  305. /// <summary>Called when <see cref="Visible"/> has changed.</summary>
  306. protected virtual void OnVisibleChanged () { }
  307. /// <summary>Raised when <see cref="Visible"/> has changed.</summary>
  308. public event EventHandler? VisibleChanged;
  309. /// <summary>
  310. /// INTERNAL Indicates whether all views up the Superview hierarchy are visible.
  311. /// </summary>
  312. /// <param name="view">The view to test.</param>
  313. /// <returns>
  314. /// <see langword="false"/> if `view.Visible` is <see langword="false"/> or any Superview is not visible,
  315. /// <see langword="true"/> otherwise.
  316. /// </returns>
  317. internal static bool CanBeVisible (View view)
  318. {
  319. if (!view.Visible)
  320. {
  321. return false;
  322. }
  323. for (View? c = view.SuperView; c != null; c = c.SuperView)
  324. {
  325. if (!c.Visible)
  326. {
  327. return false;
  328. }
  329. }
  330. return true;
  331. }
  332. #endregion Visibility
  333. #region Title
  334. private string _title = string.Empty;
  335. /// <summary>Gets the <see cref="Gui.TextFormatter"/> used to format <see cref="Title"/>.</summary>
  336. internal TextFormatter TitleTextFormatter { get; init; } = new ();
  337. /// <summary>
  338. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.
  339. /// <see cref="Thickness.Top"/> is greater than 0. The title can be used to set the <see cref="HotKey"/>
  340. /// for the view by prefixing character with <see cref="HotKeySpecifier"/> (e.g. <c>"T_itle"</c>).
  341. /// </summary>
  342. /// <remarks>
  343. /// <para>
  344. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable Title-based hotkey support set
  345. /// <see cref="HotKeySpecifier"/> to <c>(Rune)0xffff</c>.
  346. /// </para>
  347. /// <para>
  348. /// Only the first HotKey specifier found in <see cref="Title"/> is supported.
  349. /// </para>
  350. /// <para>
  351. /// To cause the hotkey to be rendered with <see cref="Text"/>,
  352. /// set <c>View.</c><see cref="TextFormatter.HotKeySpecifier"/> to the desired character.
  353. /// </para>
  354. /// </remarks>
  355. /// <value>The title.</value>
  356. public string Title
  357. {
  358. get
  359. {
  360. return _title;
  361. }
  362. set
  363. {
  364. #if DEBUG_IDISPOSABLE
  365. if (EnableDebugIDisposableAsserts && WasDisposed)
  366. {
  367. throw new ObjectDisposedException (GetType ().FullName);
  368. }
  369. #endif
  370. if (value == _title)
  371. {
  372. return;
  373. }
  374. if (!OnTitleChanging (ref value))
  375. {
  376. string old = _title;
  377. _title = value;
  378. TitleTextFormatter.Text = _title;
  379. SetTitleTextFormatterSize ();
  380. SetHotKeyFromTitle ();
  381. SetNeedsDraw ();
  382. OnTitleChanged ();
  383. }
  384. }
  385. }
  386. private void SetTitleTextFormatterSize ()
  387. {
  388. TitleTextFormatter.ConstrainToSize = new (
  389. TextFormatter.GetWidestLineLength (TitleTextFormatter.Text)
  390. - (TitleTextFormatter.Text?.Contains ((char)HotKeySpecifier.Value) == true
  391. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  392. : 0),
  393. 1);
  394. }
  395. // TODO: Change this event to match the standard TG event model.
  396. /// <summary>Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.</summary>
  397. protected void OnTitleChanged () { TitleChanged?.Invoke (this, new (in _title)); }
  398. /// <summary>
  399. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can
  400. /// be cancelled.
  401. /// </summary>
  402. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  403. /// <returns>`true` if an event handler canceled the Title change.</returns>
  404. protected bool OnTitleChanging (ref string newTitle)
  405. {
  406. CancelEventArgs<string> args = new (ref _title, ref newTitle);
  407. TitleChanging?.Invoke (this, args);
  408. return args.Cancel;
  409. }
  410. /// <summary>Raised after the <see cref="View.Title"/> has been changed.</summary>
  411. public event EventHandler<EventArgs<string>>? TitleChanged;
  412. /// <summary>
  413. /// Raised when the <see cref="View.Title"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to `true`
  414. /// to cancel the Title change.
  415. /// </summary>
  416. public event EventHandler<CancelEventArgs<string>>? TitleChanging;
  417. #endregion
  418. #if DEBUG_IDISPOSABLE
  419. /// <summary>
  420. /// Gets or sets whether failure to appropriately call Dispose() on a View will result in an Assert.
  421. /// The default is <see langword="true"/>.
  422. /// Note, this is a static property and will affect all Views.
  423. /// For debug purposes to verify objects are being disposed properly.
  424. /// Only valid when DEBUG_IDISPOSABLE is defined.
  425. /// </summary>
  426. public static bool EnableDebugIDisposableAsserts { get; set; } = true;
  427. /// <summary>
  428. /// Gets whether <see cref="Dispose"/> was called on this view or not.
  429. /// For debug purposes to verify objects are being disposed properly.
  430. /// Only valid when DEBUG_IDISPOSABLE is defined.
  431. /// </summary>
  432. public bool WasDisposed { get; private set; }
  433. /// <summary>
  434. /// Gets the number of times <see cref="Dispose"/> was called on this view.
  435. /// For debug purposes to verify objects are being disposed properly.
  436. /// Only valid when DEBUG_IDISPOSABLE is defined.
  437. /// </summary>
  438. public int DisposedCount { get; private set; } = 0;
  439. /// <summary>
  440. /// Gets the list of Views that have been created and not yet disposed.
  441. /// Note, this is a static property and will affect all Views.
  442. /// For debug purposes to verify objects are being disposed properly.
  443. /// Only valid when DEBUG_IDISPOSABLE is defined.
  444. /// </summary>
  445. public static ConcurrentBag<View> Instances { get; private set; } = [];
  446. #endif
  447. }