View.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. // BUGBUG: Ideally we'd reset _previouslyFocused to the first focusable subview
  281. _previouslyFocused = SubViews.FirstOrDefault(v => v.CanFocus);
  282. if (HasFocus)
  283. {
  284. HasFocus = false;
  285. }
  286. }
  287. if (_visible
  288. && CanFocus
  289. && Enabled
  290. && !HasFocus
  291. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  292. {
  293. SetFocus ();
  294. }
  295. OnVisibleChanged ();
  296. VisibleChanged?.Invoke (this, EventArgs.Empty);
  297. SetNeedsLayout ();
  298. SuperView?.SetNeedsLayout ();
  299. SetNeedsDraw ();
  300. if (SuperView is { })
  301. {
  302. SuperView?.SetNeedsDraw ();
  303. }
  304. else
  305. {
  306. Application.ClearScreenNextIteration = true;
  307. }
  308. }
  309. }
  310. /// <summary>Called when <see cref="Visible"/> is changing. Can be cancelled by returning <see langword="true"/>.</summary>
  311. protected virtual bool OnVisibleChanging () { return false; }
  312. /// <summary>
  313. /// Raised when the <see cref="Visible"/> value is being changed. Can be cancelled by setting Cancel to
  314. /// <see langword="true"/>.
  315. /// </summary>
  316. public event EventHandler<CancelEventArgs<bool>>? VisibleChanging;
  317. /// <summary>Called when <see cref="Visible"/> has changed.</summary>
  318. protected virtual void OnVisibleChanged () { }
  319. /// <summary>Raised when <see cref="Visible"/> has changed.</summary>
  320. public event EventHandler? VisibleChanged;
  321. /// <summary>
  322. /// INTERNAL Indicates whether all views up the Superview hierarchy are visible.
  323. /// </summary>
  324. /// <param name="view">The view to test.</param>
  325. /// <returns>
  326. /// <see langword="false"/> if `view.Visible` is <see langword="false"/> or any Superview is not visible,
  327. /// <see langword="true"/> otherwise.
  328. /// </returns>
  329. internal static bool CanBeVisible (View view)
  330. {
  331. if (!view.Visible)
  332. {
  333. return false;
  334. }
  335. for (View? c = view.SuperView; c != null; c = c.SuperView)
  336. {
  337. if (!c.Visible)
  338. {
  339. return false;
  340. }
  341. }
  342. return true;
  343. }
  344. #endregion Visibility
  345. #region Title
  346. private string _title = string.Empty;
  347. /// <summary>Gets the <see cref="Gui.TextFormatter"/> used to format <see cref="Title"/>.</summary>
  348. internal TextFormatter TitleTextFormatter { get; init; } = new ();
  349. /// <summary>
  350. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.
  351. /// <see cref="Thickness.Top"/> is greater than 0. The title can be used to set the <see cref="HotKey"/>
  352. /// for the view by prefixing character with <see cref="HotKeySpecifier"/> (e.g. <c>"T_itle"</c>).
  353. /// </summary>
  354. /// <remarks>
  355. /// <para>
  356. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable Title-based hotkey support set
  357. /// <see cref="HotKeySpecifier"/> to <c>(Rune)0xffff</c>.
  358. /// </para>
  359. /// <para>
  360. /// Only the first HotKey specifier found in <see cref="Title"/> is supported.
  361. /// </para>
  362. /// <para>
  363. /// To cause the hotkey to be rendered with <see cref="Text"/>,
  364. /// set <c>View.</c><see cref="TextFormatter.HotKeySpecifier"/> to the desired character.
  365. /// </para>
  366. /// </remarks>
  367. /// <value>The title.</value>
  368. public string Title
  369. {
  370. get
  371. {
  372. #if DEBUG_IDISPOSABLE
  373. if (DebugIDisposable && WasDisposed)
  374. {
  375. throw new ObjectDisposedException (GetType ().FullName);
  376. }
  377. #endif
  378. return _title;
  379. }
  380. set
  381. {
  382. #if DEBUG_IDISPOSABLE
  383. if (DebugIDisposable && WasDisposed)
  384. {
  385. throw new ObjectDisposedException (GetType ().FullName);
  386. }
  387. #endif
  388. if (value == _title)
  389. {
  390. return;
  391. }
  392. if (!OnTitleChanging (ref value))
  393. {
  394. string old = _title;
  395. _title = value;
  396. TitleTextFormatter.Text = _title;
  397. SetTitleTextFormatterSize ();
  398. SetHotKeyFromTitle ();
  399. SetNeedsDraw ();
  400. #if DEBUG
  401. if (string.IsNullOrEmpty (Id))
  402. {
  403. Id = _title;
  404. }
  405. #endif // DEBUG
  406. OnTitleChanged ();
  407. }
  408. }
  409. }
  410. private void SetTitleTextFormatterSize ()
  411. {
  412. TitleTextFormatter.ConstrainToSize = new (
  413. TextFormatter.GetWidestLineLength (TitleTextFormatter.Text)
  414. - (TitleTextFormatter.Text?.Contains ((char)HotKeySpecifier.Value) == true
  415. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  416. : 0),
  417. 1);
  418. }
  419. // TODO: Change this event to match the standard TG event model.
  420. /// <summary>Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.</summary>
  421. protected void OnTitleChanged () { TitleChanged?.Invoke (this, new (in _title)); }
  422. /// <summary>
  423. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can
  424. /// be cancelled.
  425. /// </summary>
  426. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  427. /// <returns>`true` if an event handler canceled the Title change.</returns>
  428. protected bool OnTitleChanging (ref string newTitle)
  429. {
  430. CancelEventArgs<string> args = new (ref _title, ref newTitle);
  431. TitleChanging?.Invoke (this, args);
  432. return args.Cancel;
  433. }
  434. /// <summary>Raised after the <see cref="View.Title"/> has been changed.</summary>
  435. public event EventHandler<EventArgs<string>>? TitleChanged;
  436. /// <summary>
  437. /// Raised when the <see cref="View.Title"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to `true`
  438. /// to cancel the Title change.
  439. /// </summary>
  440. public event EventHandler<CancelEventArgs<string>>? TitleChanging;
  441. #endregion
  442. #if DEBUG_IDISPOSABLE
  443. /// <summary>
  444. /// Set to false to disable the debug IDisposable feature.
  445. /// </summary>
  446. public static bool DebugIDisposable { get; set; } = false;
  447. /// <summary>For debug purposes to verify objects are being disposed properly</summary>
  448. public bool WasDisposed { get; set; }
  449. /// <summary>For debug purposes to verify objects are being disposed properly</summary>
  450. public int DisposedCount { get; set; } = 0;
  451. /// <summary>For debug purposes</summary>
  452. public static List<View> Instances { get; set; } = [];
  453. #endif
  454. }