View.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. // Force a layout each time a View is initialized
  209. // See: https://github.com/gui-cs/Terminal.Gui/issues/3951
  210. // See: https://github.com/gui-cs/Terminal.Gui/issues/4204
  211. Layout (); // the EventLog in AllViewsTester fails to layout correctly if this is not here (convoluted Dim.Fill(Func)).
  212. // Complex layout scenarios (e.g. DimAuto and PosAlign) may require multiple layouts to be performed.
  213. // Thus, we call SetNeedsLayout() to ensure that the layout is performed at least once.
  214. SetNeedsLayout ();
  215. Initialized?.Invoke (this, EventArgs.Empty);
  216. }
  217. #endregion Constructors and Initialization
  218. #region Visibility
  219. private bool _enabled = true;
  220. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can respond to user interaction.</summary>
  221. public bool Enabled
  222. {
  223. get => _enabled;
  224. set
  225. {
  226. if (_enabled == value)
  227. {
  228. return;
  229. }
  230. _enabled = value;
  231. if (!_enabled && HasFocus)
  232. {
  233. HasFocus = false;
  234. }
  235. if (_enabled
  236. && CanFocus
  237. && Visible
  238. && !HasFocus
  239. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  240. {
  241. SetFocus ();
  242. }
  243. OnEnabledChanged ();
  244. SetNeedsDraw ();
  245. if (Border is { })
  246. {
  247. Border.Enabled = _enabled;
  248. }
  249. foreach (View view in InternalSubViews)
  250. {
  251. view.Enabled = Enabled;
  252. }
  253. }
  254. }
  255. /// <summary>Raised when the <see cref="Enabled"/> value is being changed.</summary>
  256. public event EventHandler? EnabledChanged;
  257. // TODO: Change this event to match the standard TG event model.
  258. /// <summary>Invoked when the <see cref="Enabled"/> property from a view is changed.</summary>
  259. public virtual void OnEnabledChanged () { EnabledChanged?.Invoke (this, EventArgs.Empty); }
  260. private bool _visible = true;
  261. // TODO: Remove virtual once Menu/MenuBar are removed. MenuBar is the only override.
  262. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> is visible.</summary>
  263. public virtual bool Visible
  264. {
  265. get => _visible;
  266. set
  267. {
  268. if (_visible == value)
  269. {
  270. return;
  271. }
  272. if (OnVisibleChanging ())
  273. {
  274. return;
  275. }
  276. CancelEventArgs<bool> args = new (in _visible, ref value);
  277. VisibleChanging?.Invoke (this, args);
  278. if (args.Cancel)
  279. {
  280. return;
  281. }
  282. _visible = value;
  283. if (!_visible)
  284. {
  285. // BUGBUG: Ideally we'd reset _previouslyFocused to the first focusable subview
  286. _previouslyFocused = SubViews.FirstOrDefault (v => v.CanFocus);
  287. if (HasFocus)
  288. {
  289. HasFocus = false;
  290. }
  291. }
  292. if (_visible
  293. && CanFocus
  294. && Enabled
  295. && !HasFocus
  296. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  297. {
  298. SetFocus ();
  299. }
  300. OnVisibleChanged ();
  301. VisibleChanged?.Invoke (this, EventArgs.Empty);
  302. SetNeedsLayout ();
  303. SuperView?.SetNeedsLayout ();
  304. SetNeedsDraw ();
  305. if (SuperView is { })
  306. {
  307. SuperView?.SetNeedsDraw ();
  308. }
  309. else
  310. {
  311. Application.ClearScreenNextIteration = true;
  312. }
  313. }
  314. }
  315. /// <summary>Called when <see cref="Visible"/> is changing. Can be cancelled by returning <see langword="true"/>.</summary>
  316. protected virtual bool OnVisibleChanging () { return false; }
  317. /// <summary>
  318. /// Raised when the <see cref="Visible"/> value is being changed. Can be cancelled by setting Cancel to
  319. /// <see langword="true"/>.
  320. /// </summary>
  321. public event EventHandler<CancelEventArgs<bool>>? VisibleChanging;
  322. /// <summary>Called when <see cref="Visible"/> has changed.</summary>
  323. protected virtual void OnVisibleChanged () { }
  324. /// <summary>Raised when <see cref="Visible"/> has changed.</summary>
  325. public event EventHandler? VisibleChanged;
  326. /// <summary>
  327. /// INTERNAL Indicates whether all views up the Superview hierarchy are visible.
  328. /// </summary>
  329. /// <param name="view">The view to test.</param>
  330. /// <returns>
  331. /// <see langword="false"/> if `view.Visible` is <see langword="false"/> or any Superview is not visible,
  332. /// <see langword="true"/> otherwise.
  333. /// </returns>
  334. internal static bool CanBeVisible (View view)
  335. {
  336. if (!view.Visible)
  337. {
  338. return false;
  339. }
  340. for (View? c = view.SuperView; c != null; c = c.SuperView)
  341. {
  342. if (!c.Visible)
  343. {
  344. return false;
  345. }
  346. }
  347. return true;
  348. }
  349. #endregion Visibility
  350. #region Title
  351. private string _title = string.Empty;
  352. /// <summary>Gets the <see cref="Text.TextFormatter"/> used to format <see cref="Title"/>.</summary>
  353. internal TextFormatter TitleTextFormatter { get; init; } = new ();
  354. /// <summary>
  355. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.
  356. /// <see cref="Thickness.Top"/> is greater than 0. The title can be used to set the <see cref="HotKey"/>
  357. /// for the view by prefixing character with <see cref="HotKeySpecifier"/> (e.g. <c>"T_itle"</c>).
  358. /// </summary>
  359. /// <remarks>
  360. /// <para>
  361. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable Title-based hotkey support set
  362. /// <see cref="HotKeySpecifier"/> to <c>(Rune)0xffff</c>.
  363. /// </para>
  364. /// <para>
  365. /// Only the first HotKey specifier found in <see cref="Title"/> is supported.
  366. /// </para>
  367. /// <para>
  368. /// To cause the hotkey to be rendered with <see cref="Text"/>,
  369. /// set <c>View.</c><see cref="TextFormatter.HotKeySpecifier"/> to the desired character.
  370. /// </para>
  371. /// </remarks>
  372. /// <value>The title.</value>
  373. public string Title
  374. {
  375. get
  376. {
  377. return _title;
  378. }
  379. set
  380. {
  381. #if DEBUG_IDISPOSABLE
  382. if (EnableDebugIDisposableAsserts && WasDisposed)
  383. {
  384. throw new ObjectDisposedException (GetType ().FullName);
  385. }
  386. #endif
  387. if (value == _title)
  388. {
  389. return;
  390. }
  391. if (!OnTitleChanging (ref value))
  392. {
  393. string old = _title;
  394. _title = value;
  395. TitleTextFormatter.Text = _title;
  396. SetTitleTextFormatterSize ();
  397. SetHotKeyFromTitle ();
  398. SetNeedsDraw ();
  399. OnTitleChanged ();
  400. }
  401. }
  402. }
  403. private void SetTitleTextFormatterSize ()
  404. {
  405. TitleTextFormatter.ConstrainToSize = new (
  406. TextFormatter.GetWidestLineLength (TitleTextFormatter.Text)
  407. - (TitleTextFormatter.Text?.Contains ((char)HotKeySpecifier.Value) == true
  408. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  409. : 0),
  410. 1);
  411. }
  412. // TODO: Change this event to match the standard TG event model.
  413. /// <summary>Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.</summary>
  414. protected void OnTitleChanged () { TitleChanged?.Invoke (this, new (in _title)); }
  415. /// <summary>
  416. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can
  417. /// be cancelled.
  418. /// </summary>
  419. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  420. /// <returns>`true` if an event handler canceled the Title change.</returns>
  421. protected bool OnTitleChanging (ref string newTitle)
  422. {
  423. CancelEventArgs<string> args = new (ref _title, ref newTitle);
  424. TitleChanging?.Invoke (this, args);
  425. return args.Cancel;
  426. }
  427. /// <summary>Raised after the <see cref="View.Title"/> has been changed.</summary>
  428. public event EventHandler<EventArgs<string>>? TitleChanged;
  429. /// <summary>
  430. /// Raised when the <see cref="View.Title"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to `true`
  431. /// to cancel the Title change.
  432. /// </summary>
  433. public event EventHandler<CancelEventArgs<string>>? TitleChanging;
  434. #endregion
  435. #if DEBUG_IDISPOSABLE
  436. #pragma warning disable CS0419 // Ambiguous reference in cref attribute
  437. /// <summary>
  438. /// Gets or sets whether failure to appropriately call Dispose() on a View will result in an Assert.
  439. /// The default is <see langword="true"/>.
  440. /// Note, this is a static property and will affect all Views.
  441. /// For debug purposes to verify objects are being disposed properly.
  442. /// Only valid when DEBUG_IDISPOSABLE is defined.
  443. /// </summary>
  444. public static bool EnableDebugIDisposableAsserts { get; set; } = true;
  445. /// <summary>
  446. /// Gets whether <see cref="View.Dispose"/> was called on this view or not.
  447. /// For debug purposes to verify objects are being disposed properly.
  448. /// Only valid when DEBUG_IDISPOSABLE is defined.
  449. /// </summary>
  450. public bool WasDisposed { get; private set; }
  451. /// <summary>
  452. /// Gets the number of times <see cref="View.Dispose"/> was called on this view.
  453. /// For debug purposes to verify objects are being disposed properly.
  454. /// Only valid when DEBUG_IDISPOSABLE is defined.
  455. /// </summary>
  456. public int DisposedCount { get; private set; } = 0;
  457. /// <summary>
  458. /// Gets the list of Views that have been created and not yet disposed.
  459. /// Note, this is a static property and will affect all Views.
  460. /// For debug purposes to verify objects are being disposed properly.
  461. /// Only valid when DEBUG_IDISPOSABLE is defined.
  462. /// </summary>
  463. public static ConcurrentBag<View> Instances { get; private set; } = [];
  464. #pragma warning restore CS0419 // Ambiguous reference in cref attribute
  465. #endif
  466. }