2
0

View.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. if (ApplicationImpl.Instance.IsLegacy)
  140. {
  141. // TODO: Figure out how to move this out of here and just depend on LayoutNeeded in Mainloop
  142. Layout (); // the EventLog in AllViewsTester fails to layout correctly if this is not here (convoluted Dim.Fill(Func)).
  143. }
  144. SetNeedsLayout ();
  145. Initialized?.Invoke (this, EventArgs.Empty);
  146. }
  147. #endregion Constructors and Initialization
  148. #region Visibility
  149. private bool _enabled = true;
  150. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can respond to user interaction.</summary>
  151. public bool Enabled
  152. {
  153. get => _enabled;
  154. set
  155. {
  156. if (_enabled == value)
  157. {
  158. return;
  159. }
  160. _enabled = value;
  161. if (!_enabled && HasFocus)
  162. {
  163. HasFocus = false;
  164. }
  165. if (_enabled
  166. && CanFocus
  167. && Visible
  168. && !HasFocus
  169. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  170. {
  171. SetFocus ();
  172. }
  173. OnEnabledChanged ();
  174. SetNeedsDraw ();
  175. if (Border is { })
  176. {
  177. Border.Enabled = _enabled;
  178. }
  179. if (_subviews is null)
  180. {
  181. return;
  182. }
  183. foreach (View view in _subviews)
  184. {
  185. view.Enabled = Enabled;
  186. }
  187. }
  188. }
  189. /// <summary>Raised when the <see cref="Enabled"/> value is being changed.</summary>
  190. public event EventHandler? EnabledChanged;
  191. // TODO: Change this event to match the standard TG event model.
  192. /// <summary>Invoked when the <see cref="Enabled"/> property from a view is changed.</summary>
  193. public virtual void OnEnabledChanged () { EnabledChanged?.Invoke (this, EventArgs.Empty); }
  194. private bool _visible = true;
  195. // TODO: Remove virtual once Menu/MenuBar are removed. MenuBar is the only override.
  196. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> is visible.</summary>
  197. public virtual bool Visible
  198. {
  199. get => _visible;
  200. set
  201. {
  202. if (_visible == value)
  203. {
  204. return;
  205. }
  206. if (OnVisibleChanging ())
  207. {
  208. return;
  209. }
  210. CancelEventArgs<bool> args = new (in _visible, ref value);
  211. VisibleChanging?.Invoke (this, args);
  212. if (args.Cancel)
  213. {
  214. return;
  215. }
  216. _visible = value;
  217. if (!_visible)
  218. {
  219. if (HasFocus)
  220. {
  221. HasFocus = false;
  222. }
  223. }
  224. if (_visible
  225. && CanFocus
  226. && Enabled
  227. && !HasFocus
  228. && SuperView is null or { HasFocus: true, Visible: true, Enabled: true, Focused: null })
  229. {
  230. SetFocus ();
  231. }
  232. OnVisibleChanged ();
  233. VisibleChanged?.Invoke (this, EventArgs.Empty);
  234. SetNeedsLayout ();
  235. SuperView?.SetNeedsLayout ();
  236. SetNeedsDraw ();
  237. if (SuperView is { })
  238. {
  239. SuperView?.SetNeedsDraw ();
  240. }
  241. else
  242. {
  243. Application.ClearScreenNextIteration = true;
  244. }
  245. }
  246. }
  247. /// <summary>Called when <see cref="Visible"/> is changing. Can be cancelled by returning <see langword="true"/>.</summary>
  248. protected virtual bool OnVisibleChanging () { return false; }
  249. /// <summary>
  250. /// Raised when the <see cref="Visible"/> value is being changed. Can be cancelled by setting Cancel to
  251. /// <see langword="true"/>.
  252. /// </summary>
  253. public event EventHandler<CancelEventArgs<bool>>? VisibleChanging;
  254. /// <summary>Called when <see cref="Visible"/> has changed.</summary>
  255. protected virtual void OnVisibleChanged () { }
  256. /// <summary>Raised when <see cref="Visible"/> has changed.</summary>
  257. public event EventHandler? VisibleChanged;
  258. /// <summary>
  259. /// INTERNAL Indicates whether all views up the Superview hierarchy are visible.
  260. /// </summary>
  261. /// <param name="view">The view to test.</param>
  262. /// <returns>
  263. /// <see langword="false"/> if `view.Visible` is <see langword="false"/> or any Superview is not visible,
  264. /// <see langword="true"/> otherwise.
  265. /// </returns>
  266. internal static bool CanBeVisible (View view)
  267. {
  268. if (!view.Visible)
  269. {
  270. return false;
  271. }
  272. for (View? c = view.SuperView; c != null; c = c.SuperView)
  273. {
  274. if (!c.Visible)
  275. {
  276. return false;
  277. }
  278. }
  279. return true;
  280. }
  281. #endregion Visibility
  282. #region Title
  283. private string _title = string.Empty;
  284. /// <summary>Gets the <see cref="Gui.TextFormatter"/> used to format <see cref="Title"/>.</summary>
  285. internal TextFormatter TitleTextFormatter { get; init; } = new ();
  286. /// <summary>
  287. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.
  288. /// <see cref="Thickness.Top"/> is greater than 0. The title can be used to set the <see cref="HotKey"/>
  289. /// for the view by prefixing character with <see cref="HotKeySpecifier"/> (e.g. <c>"T_itle"</c>).
  290. /// </summary>
  291. /// <remarks>
  292. /// <para>
  293. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable Title-based hotkey support set
  294. /// <see cref="HotKeySpecifier"/> to <c>(Rune)0xffff</c>.
  295. /// </para>
  296. /// <para>
  297. /// Only the first HotKey specifier found in <see cref="Title"/> is supported.
  298. /// </para>
  299. /// <para>
  300. /// To cause the hotkey to be rendered with <see cref="Text"/>,
  301. /// set <c>View.</c><see cref="TextFormatter.HotKeySpecifier"/> to the desired character.
  302. /// </para>
  303. /// </remarks>
  304. /// <value>The title.</value>
  305. public string Title
  306. {
  307. get
  308. {
  309. #if DEBUG_IDISPOSABLE
  310. if (WasDisposed)
  311. {
  312. throw new ObjectDisposedException (GetType ().FullName);
  313. }
  314. #endif
  315. return _title;
  316. }
  317. set
  318. {
  319. #if DEBUG_IDISPOSABLE
  320. if (WasDisposed)
  321. {
  322. throw new ObjectDisposedException (GetType ().FullName);
  323. }
  324. #endif
  325. if (value == _title)
  326. {
  327. return;
  328. }
  329. if (!OnTitleChanging (ref value))
  330. {
  331. string old = _title;
  332. _title = value;
  333. TitleTextFormatter.Text = _title;
  334. SetTitleTextFormatterSize ();
  335. SetHotKeyFromTitle ();
  336. SetNeedsDraw ();
  337. #if DEBUG
  338. if (string.IsNullOrEmpty (Id))
  339. {
  340. Id = _title;
  341. }
  342. #endif // DEBUG
  343. OnTitleChanged ();
  344. }
  345. }
  346. }
  347. private void SetTitleTextFormatterSize ()
  348. {
  349. TitleTextFormatter.ConstrainToSize = new (
  350. TextFormatter.GetWidestLineLength (TitleTextFormatter.Text)
  351. - (TitleTextFormatter.Text?.Contains ((char)HotKeySpecifier.Value) == true
  352. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  353. : 0),
  354. 1);
  355. }
  356. // TODO: Change this event to match the standard TG event model.
  357. /// <summary>Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.</summary>
  358. protected void OnTitleChanged () { TitleChanged?.Invoke (this, new (in _title)); }
  359. /// <summary>
  360. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can
  361. /// be cancelled.
  362. /// </summary>
  363. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  364. /// <returns>`true` if an event handler canceled the Title change.</returns>
  365. protected bool OnTitleChanging (ref string newTitle)
  366. {
  367. CancelEventArgs<string> args = new (ref _title, ref newTitle);
  368. TitleChanging?.Invoke (this, args);
  369. return args.Cancel;
  370. }
  371. /// <summary>Raised after the <see cref="View.Title"/> has been changed.</summary>
  372. public event EventHandler<EventArgs<string>>? TitleChanged;
  373. /// <summary>
  374. /// Raised when the <see cref="View.Title"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to `true`
  375. /// to cancel the Title change.
  376. /// </summary>
  377. public event EventHandler<CancelEventArgs<string>>? TitleChanging;
  378. #endregion
  379. /// <summary>Pretty prints the View</summary>
  380. /// <returns></returns>
  381. public override string ToString () { return $"{GetType ().Name}({Id}){Frame}"; }
  382. private bool _disposedValue;
  383. /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
  384. /// <remarks>
  385. /// If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and
  386. /// unmanaged resources can be disposed. If disposing equals false, the method has been called by the runtime from
  387. /// inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed.
  388. /// </remarks>
  389. /// <param name="disposing"></param>
  390. protected virtual void Dispose (bool disposing)
  391. {
  392. LineCanvas.Dispose ();
  393. DisposeMouse ();
  394. DisposeKeyboard ();
  395. DisposeAdornments ();
  396. DisposeScrollBars ();
  397. for (int i = InternalSubviews.Count - 1; i >= 0; i--)
  398. {
  399. View subview = InternalSubviews [i];
  400. Remove (subview);
  401. subview.Dispose ();
  402. }
  403. if (!_disposedValue)
  404. {
  405. if (disposing)
  406. {
  407. // TODO: dispose managed state (managed objects)
  408. }
  409. _disposedValue = true;
  410. }
  411. Debug.Assert (InternalSubviews.Count == 0);
  412. }
  413. /// <summary>
  414. /// Riased when the <see cref="View"/> is being disposed.
  415. /// </summary>
  416. public event EventHandler? Disposing;
  417. /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resource.</summary>
  418. public void Dispose ()
  419. {
  420. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  421. Disposing?.Invoke (this, EventArgs.Empty);
  422. Dispose (true);
  423. GC.SuppressFinalize (this);
  424. #if DEBUG_IDISPOSABLE
  425. WasDisposed = true;
  426. foreach (View instance in Instances.Where (x => x.WasDisposed).ToList ())
  427. {
  428. Instances.Remove (instance);
  429. }
  430. #endif
  431. }
  432. #if DEBUG_IDISPOSABLE
  433. /// <summary>For debug purposes to verify objects are being disposed properly</summary>
  434. public bool WasDisposed { get; set; }
  435. /// <summary>For debug purposes to verify objects are being disposed properly</summary>
  436. public int DisposedCount { get; set; } = 0;
  437. /// <summary>For debug purposes</summary>
  438. public static List<View> Instances { get; set; } = [];
  439. #endif
  440. }