View.cs 19 KB

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