View.cs 21 KB

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