View.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 (InternalSubViews?.Count > 0)
  168. {
  169. foreach (View view in InternalSubViews)
  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. foreach (View view in InternalSubViews)
  198. {
  199. if (!view.IsInitialized)
  200. {
  201. view.EndInit ();
  202. }
  203. }
  204. if (ApplicationImpl.Instance.IsLegacy)
  205. {
  206. // TODO: Figure out how to move this out of here and just depend on LayoutNeeded in Mainloop
  207. Layout (); // the EventLog in AllViewsTester fails to layout correctly if this is not here (convoluted Dim.Fill(Func)).
  208. }
  209. SetNeedsLayout ();
  210. Initialized?.Invoke (this, EventArgs.Empty);
  211. }
  212. #endregion Constructors and Initialization
  213. #region Visibility
  214. private bool _enabled = true;
  215. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can respond to user interaction.</summary>
  216. public bool Enabled
  217. {
  218. get => _enabled;
  219. set
  220. {
  221. if (_enabled == value)
  222. {
  223. return;
  224. }
  225. _enabled = value;
  226. if (!_enabled && HasFocus)
  227. {
  228. HasFocus = false;
  229. }
  230. if (_enabled
  231. && CanFocus
  232. && Visible
  233. && !HasFocus
  234. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  235. {
  236. SetFocus ();
  237. }
  238. OnEnabledChanged ();
  239. SetNeedsDraw ();
  240. if (Border is { })
  241. {
  242. Border.Enabled = _enabled;
  243. }
  244. foreach (View view in InternalSubViews)
  245. {
  246. view.Enabled = Enabled;
  247. }
  248. }
  249. }
  250. /// <summary>Raised when the <see cref="Enabled"/> value is being changed.</summary>
  251. public event EventHandler? EnabledChanged;
  252. // TODO: Change this event to match the standard TG event model.
  253. /// <summary>Invoked when the <see cref="Enabled"/> property from a view is changed.</summary>
  254. public virtual void OnEnabledChanged () { EnabledChanged?.Invoke (this, EventArgs.Empty); }
  255. private bool _visible = true;
  256. // TODO: Remove virtual once Menu/MenuBar are removed. MenuBar is the only override.
  257. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> is visible.</summary>
  258. public virtual bool Visible
  259. {
  260. get => _visible;
  261. set
  262. {
  263. if (_visible == value)
  264. {
  265. return;
  266. }
  267. if (OnVisibleChanging ())
  268. {
  269. return;
  270. }
  271. CancelEventArgs<bool> args = new (in _visible, ref value);
  272. VisibleChanging?.Invoke (this, args);
  273. if (args.Cancel)
  274. {
  275. return;
  276. }
  277. _visible = value;
  278. if (!_visible)
  279. {
  280. if (HasFocus)
  281. {
  282. HasFocus = false;
  283. }
  284. }
  285. if (_visible
  286. && CanFocus
  287. && Enabled
  288. && !HasFocus
  289. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  290. {
  291. SetFocus ();
  292. }
  293. OnVisibleChanged ();
  294. VisibleChanged?.Invoke (this, EventArgs.Empty);
  295. SetNeedsLayout ();
  296. SuperView?.SetNeedsLayout ();
  297. SetNeedsDraw ();
  298. if (SuperView is { })
  299. {
  300. SuperView?.SetNeedsDraw ();
  301. }
  302. else
  303. {
  304. Application.ClearScreenNextIteration = true;
  305. }
  306. }
  307. }
  308. /// <summary>Called when <see cref="Visible"/> is changing. Can be cancelled by returning <see langword="true"/>.</summary>
  309. protected virtual bool OnVisibleChanging () { return false; }
  310. /// <summary>
  311. /// Raised when the <see cref="Visible"/> value is being changed. Can be cancelled by setting Cancel to
  312. /// <see langword="true"/>.
  313. /// </summary>
  314. public event EventHandler<CancelEventArgs<bool>>? VisibleChanging;
  315. /// <summary>Called when <see cref="Visible"/> has changed.</summary>
  316. protected virtual void OnVisibleChanged () { }
  317. /// <summary>Raised when <see cref="Visible"/> has changed.</summary>
  318. public event EventHandler? VisibleChanged;
  319. /// <summary>
  320. /// INTERNAL Indicates whether all views up the Superview hierarchy are visible.
  321. /// </summary>
  322. /// <param name="view">The view to test.</param>
  323. /// <returns>
  324. /// <see langword="false"/> if `view.Visible` is <see langword="false"/> or any Superview is not visible,
  325. /// <see langword="true"/> otherwise.
  326. /// </returns>
  327. internal static bool CanBeVisible (View view)
  328. {
  329. if (!view.Visible)
  330. {
  331. return false;
  332. }
  333. for (View? c = view.SuperView; c != null; c = c.SuperView)
  334. {
  335. if (!c.Visible)
  336. {
  337. return false;
  338. }
  339. }
  340. return true;
  341. }
  342. #endregion Visibility
  343. #region Title
  344. private string _title = string.Empty;
  345. /// <summary>Gets the <see cref="Gui.TextFormatter"/> used to format <see cref="Title"/>.</summary>
  346. internal TextFormatter TitleTextFormatter { get; init; } = new ();
  347. /// <summary>
  348. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.
  349. /// <see cref="Thickness.Top"/> is greater than 0. The title can be used to set the <see cref="HotKey"/>
  350. /// for the view by prefixing character with <see cref="HotKeySpecifier"/> (e.g. <c>"T_itle"</c>).
  351. /// </summary>
  352. /// <remarks>
  353. /// <para>
  354. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable Title-based hotkey support set
  355. /// <see cref="HotKeySpecifier"/> to <c>(Rune)0xffff</c>.
  356. /// </para>
  357. /// <para>
  358. /// Only the first HotKey specifier found in <see cref="Title"/> is supported.
  359. /// </para>
  360. /// <para>
  361. /// To cause the hotkey to be rendered with <see cref="Text"/>,
  362. /// set <c>View.</c><see cref="TextFormatter.HotKeySpecifier"/> to the desired character.
  363. /// </para>
  364. /// </remarks>
  365. /// <value>The title.</value>
  366. public string Title
  367. {
  368. get
  369. {
  370. #if DEBUG_IDISPOSABLE
  371. if (DebugIDisposable && WasDisposed)
  372. {
  373. throw new ObjectDisposedException (GetType ().FullName);
  374. }
  375. #endif
  376. return _title;
  377. }
  378. set
  379. {
  380. #if DEBUG_IDISPOSABLE
  381. if (DebugIDisposable && WasDisposed)
  382. {
  383. throw new ObjectDisposedException (GetType ().FullName);
  384. }
  385. #endif
  386. if (value == _title)
  387. {
  388. return;
  389. }
  390. if (!OnTitleChanging (ref value))
  391. {
  392. string old = _title;
  393. _title = value;
  394. TitleTextFormatter.Text = _title;
  395. SetTitleTextFormatterSize ();
  396. SetHotKeyFromTitle ();
  397. SetNeedsDraw ();
  398. #if DEBUG
  399. if (string.IsNullOrEmpty (Id))
  400. {
  401. Id = _title;
  402. }
  403. #endif // DEBUG
  404. OnTitleChanged ();
  405. }
  406. }
  407. }
  408. private void SetTitleTextFormatterSize ()
  409. {
  410. TitleTextFormatter.ConstrainToSize = new (
  411. TextFormatter.GetWidestLineLength (TitleTextFormatter.Text)
  412. - (TitleTextFormatter.Text?.Contains ((char)HotKeySpecifier.Value) == true
  413. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  414. : 0),
  415. 1);
  416. }
  417. // TODO: Change this event to match the standard TG event model.
  418. /// <summary>Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.</summary>
  419. protected void OnTitleChanged () { TitleChanged?.Invoke (this, new (in _title)); }
  420. /// <summary>
  421. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can
  422. /// be cancelled.
  423. /// </summary>
  424. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  425. /// <returns>`true` if an event handler canceled the Title change.</returns>
  426. protected bool OnTitleChanging (ref string newTitle)
  427. {
  428. CancelEventArgs<string> args = new (ref _title, ref newTitle);
  429. TitleChanging?.Invoke (this, args);
  430. return args.Cancel;
  431. }
  432. /// <summary>Raised after the <see cref="View.Title"/> has been changed.</summary>
  433. public event EventHandler<EventArgs<string>>? TitleChanged;
  434. /// <summary>
  435. /// Raised when the <see cref="View.Title"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to `true`
  436. /// to cancel the Title change.
  437. /// </summary>
  438. public event EventHandler<CancelEventArgs<string>>? TitleChanging;
  439. #endregion
  440. #if DEBUG_IDISPOSABLE
  441. /// <summary>
  442. /// Set to false to disable the debug IDisposable feature.
  443. /// </summary>
  444. public static bool DebugIDisposable { get; set; } = false;
  445. /// <summary>For debug purposes to verify objects are being disposed properly</summary>
  446. public bool WasDisposed { get; set; }
  447. /// <summary>For debug purposes to verify objects are being disposed properly</summary>
  448. public int DisposedCount { get; set; } = 0;
  449. /// <summary>For debug purposes</summary>
  450. public static List<View> Instances { get; set; } = [];
  451. #endif
  452. }