View.cs 20 KB

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