2
0

View.cs 19 KB

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