View.cs 20 KB

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