2
0

View.cs 17 KB

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