View.cs 20 KB

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