View.cs 19 KB

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