View.cs 18 KB

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