View.cs 20 KB

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