View.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. using System.ComponentModel;
  2. using System.Diagnostics;
  3. namespace Terminal.Gui;
  4. #region API Docs
  5. /// <summary>
  6. /// View is the base class for all views on the screen and represents a visible element that can render itself and
  7. /// contains zero or more nested views, called SubViews. View provides basic functionality for layout, positioning, and
  8. /// drawing. In addition, View provides keyboard and mouse event handling.
  9. /// </summary>
  10. /// <remarks>
  11. /// <list type="table">
  12. /// <listheader>
  13. /// <term>Term</term><description>Definition</description>
  14. /// </listheader>
  15. /// <item>
  16. /// <term>SubView</term>
  17. /// <description>
  18. /// A View that is contained in another view and will be rendered as part of the containing view's
  19. /// ContentArea. SubViews are added to another view via the <see cref="View.Add(View)"/>` method. A View
  20. /// may only be a SubView of a single View.
  21. /// </description>
  22. /// </item>
  23. /// <item>
  24. /// <term>SuperView</term><description>The View that is a container for SubViews.</description>
  25. /// </item>
  26. /// </list>
  27. /// <para>
  28. /// Focus is a concept that is used to describe which View is currently receiving user input. Only Views that are
  29. /// <see cref="Enabled"/>, <see cref="Visible"/>, and <see cref="CanFocus"/> will receive focus.
  30. /// </para>
  31. /// <para>
  32. /// Views that are focusable should override <see cref="PositionCursor"/> to make sure that the cursor is
  33. /// placed in a location that makes sense. Some terminals do not have a way of hiding the cursor, so it can be
  34. /// distracting to have the cursor left at the last focused view. So views should make sure that they place the
  35. /// cursor in a visually sensible place. The default implementation of <see cref="PositionCursor"/> will place the
  36. /// cursor at either the hotkey (if defined) or <c>0,0</c>.
  37. /// </para>
  38. /// <para>
  39. /// The View defines the base functionality for user interface elements in Terminal.Gui. Views can contain one or
  40. /// more subviews, can respond to user input and render themselves on the screen.
  41. /// </para>
  42. /// <para>
  43. /// To create a View using Absolute layout, call a constructor that takes a Rect parameter to specify the
  44. /// absolute position and size or simply set <see cref="View.Frame "/>). To create a View using Computed layout use
  45. /// a constructor that does not take a Rect parameter and set the X, Y, Width and Height properties on the view to
  46. /// non-absolute values. Both approaches use coordinates that are relative to the <see cref="Viewport"/> of the
  47. /// <see cref="SuperView"/> the View is added to.
  48. /// </para>
  49. /// <para>
  50. /// Computed layout is more flexible and supports dynamic console apps where controls adjust layout as the
  51. /// terminal resizes or other Views change size or position. The <see cref="X"/>, <see cref="Y"/>,
  52. /// <see cref="Width"/>, and <see cref="Height"/> properties are <see cref="Dim"/> and <see cref="Pos"/> objects
  53. /// that dynamically update the position of a view. The X and Y properties are of type <see cref="Pos"/> and you
  54. /// can use either absolute positions, percentages, or anchor points. The Width and Height properties are of type
  55. /// <see cref="Dim"/> and can use absolute position, percentages, and anchors. These are useful as they will take
  56. /// care of repositioning views when view's adornments are resized or if the terminal size changes.
  57. /// </para>
  58. /// <para>
  59. /// Absolute layout requires specifying coordinates and sizes of Views explicitly, and the View will typically
  60. /// stay in a fixed position and size. To change the position and size use the <see cref="Frame"/> property.
  61. /// </para>
  62. /// <para>
  63. /// Subviews (child views) can be added to a View by calling the <see cref="Add(View)"/> method. The container of
  64. /// a View can be accessed with the <see cref="SuperView"/> property.
  65. /// </para>
  66. /// <para>
  67. /// To flag a region of the View's <see cref="Viewport"/> to be redrawn call
  68. /// <see cref="SetNeedsDisplay(Rectangle)"/>
  69. /// .
  70. /// To flag the entire view for redraw call <see cref="SetNeedsDisplay()"/>.
  71. /// </para>
  72. /// <para>
  73. /// The <see cref="LayoutSubviews"/> method is invoked when the size or layout of a view has changed.
  74. /// </para>
  75. /// <para>
  76. /// Views have a <see cref="ColorScheme"/> property that defines the default colors that subviews should use for
  77. /// rendering. This ensures that the views fit in the context where they are being used, and allows for themes to
  78. /// be plugged in. For example, the default colors for windows and Toplevels uses a blue background, while it uses
  79. /// a white background for dialog boxes and a red background for errors.
  80. /// </para>
  81. /// <para>
  82. /// Subclasses should not rely on <see cref="ColorScheme"/> being set at construction time. If a
  83. /// <see cref="ColorScheme"/> is not set on a view, the view will inherit the value from its
  84. /// <see cref="SuperView"/> and the value might only be valid once a view has been added to a SuperView.
  85. /// </para>
  86. /// <para>By using <see cref="ColorScheme"/> applications will work both in color as well as black and white displays.</para>
  87. /// <para>
  88. /// Views can also opt-in to more sophisticated initialization by implementing overrides to
  89. /// <see cref="ISupportInitialize.BeginInit"/> and <see cref="ISupportInitialize.EndInit"/> which will be called
  90. /// when the view is added to a <see cref="SuperView"/>.
  91. /// </para>
  92. /// <para>
  93. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/> can
  94. /// be implemented, in which case the <see cref="ISupportInitialize"/> methods will only be called if
  95. /// <see cref="ISupportInitializeNotification.IsInitialized"/> is <see langword="false"/>. This allows proper
  96. /// <see cref="View"/> inheritance hierarchies to override base class layout code optimally by doing so only on
  97. /// first run, instead of on every run.
  98. /// </para>
  99. /// <para>See <see href="../docs/keyboard.md">for an overview of View keyboard handling.</see></para>
  100. /// ///
  101. /// </remarks>
  102. #endregion API Docs
  103. public partial class View : Responder, ISupportInitializeNotification
  104. {
  105. /// <summary>
  106. /// Cancelable event fired when the <see cref="Command.Accept"/> command is invoked. Set
  107. /// <see cref="HandledEventArgs.Handled"/>
  108. /// to cancel the event.
  109. /// </summary>
  110. public event EventHandler<HandledEventArgs> Accept;
  111. /// <summary>Gets or sets arbitrary data for the view.</summary>
  112. /// <remarks>This property is not used internally.</remarks>
  113. public object Data { get; set; }
  114. /// <summary>Gets or sets an identifier for the view;</summary>
  115. /// <value>The identifier.</value>
  116. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  117. public string Id { get; set; } = "";
  118. /// <summary>Pretty prints the View</summary>
  119. /// <returns></returns>
  120. public override string ToString () { return $"{GetType ().Name}({Id}){Frame}"; }
  121. /// <inheritdoc/>
  122. protected override void Dispose (bool disposing)
  123. {
  124. LineCanvas.Dispose ();
  125. DisposeKeyboard ();
  126. DisposeAdornments ();
  127. for (int i = InternalSubviews.Count - 1; i >= 0; i--)
  128. {
  129. View subview = InternalSubviews [i];
  130. Remove (subview);
  131. subview.Dispose ();
  132. }
  133. base.Dispose (disposing);
  134. Debug.Assert (InternalSubviews.Count == 0);
  135. }
  136. /// <summary>
  137. /// Called when the <see cref="Command.Accept"/> command is invoked. Raises <see cref="Accept"/>
  138. /// event.
  139. /// </summary>
  140. /// <returns>
  141. /// If <see langword="true"/> the event was canceled. If <see langword="false"/> the event was raised but not canceled.
  142. /// If <see langword="null"/> no event was raised.
  143. /// </returns>
  144. protected bool? OnAccept ()
  145. {
  146. var args = new HandledEventArgs ();
  147. Accept?.Invoke (this, args);
  148. return Accept is null ? null : args.Handled;
  149. }
  150. #region Constructors and Initialization
  151. /// <summary>
  152. /// Points to the current driver in use by the view, it is a convenience property for simplifying the development
  153. /// of new views.
  154. /// </summary>
  155. public static ConsoleDriver Driver => Application.Driver;
  156. /// <summary>Initializes a new instance of <see cref="View"/>.</summary>
  157. /// <remarks>
  158. /// <para>
  159. /// Use <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties to dynamically
  160. /// control the size and location of the view.
  161. /// </para>
  162. /// </remarks>
  163. public View ()
  164. {
  165. SetupAdornments ();
  166. SetupKeyboard ();
  167. //SetupMouse ();
  168. SetupText ();
  169. }
  170. /// <summary>
  171. /// Event called only once when the <see cref="View"/> is being initialized for the first time. Allows
  172. /// configurations and assignments to be performed before the <see cref="View"/> being shown.
  173. /// View implements <see cref="ISupportInitializeNotification"/> to allow for more sophisticated initialization.
  174. /// </summary>
  175. public event EventHandler Initialized;
  176. /// <summary>
  177. /// Get or sets if the <see cref="View"/> has been initialized (via <see cref="ISupportInitialize.BeginInit"/>
  178. /// and <see cref="ISupportInitialize.EndInit"/>).
  179. /// </summary>
  180. /// <para>
  181. /// If first-run-only initialization is preferred, overrides to
  182. /// <see cref="ISupportInitializeNotification.IsInitialized"/> can be implemented, in which case the
  183. /// <see cref="ISupportInitialize"/> methods will only be called if
  184. /// <see cref="ISupportInitializeNotification.IsInitialized"/> is <see langword="false"/>. This allows proper
  185. /// <see cref="View"/> inheritance hierarchies to override base class layout code optimally by doing so only on first
  186. /// run, instead of on every run.
  187. /// </para>
  188. public virtual bool IsInitialized { get; set; }
  189. /// <summary>Signals the View that initialization is starting. See <see cref="ISupportInitialize"/>.</summary>
  190. /// <remarks>
  191. /// <para>
  192. /// Views can opt-in to more sophisticated initialization by implementing overrides to
  193. /// <see cref="ISupportInitialize.BeginInit"/> and <see cref="ISupportInitialize.EndInit"/> which will be called
  194. /// when the <see cref="SuperView"/> is initialized.
  195. /// </para>
  196. /// <para>
  197. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/> can
  198. /// be implemented too, in which case the <see cref="ISupportInitialize"/> methods will only be called if
  199. /// <see cref="ISupportInitializeNotification.IsInitialized"/> is <see langword="false"/>. This allows proper
  200. /// <see cref="View"/> inheritance hierarchies to override base class layout code optimally by doing so only on
  201. /// first run, instead of on every run.
  202. /// </para>
  203. /// </remarks>
  204. public virtual void BeginInit ()
  205. {
  206. if (IsInitialized)
  207. {
  208. throw new InvalidOperationException ("The view is already initialized.");
  209. }
  210. #if AUTO_CANFOCUS
  211. _oldCanFocus = CanFocus;
  212. _oldTabIndex = _tabIndex;
  213. #endif
  214. BeginInitAdornments ();
  215. if (_subviews?.Count > 0)
  216. {
  217. foreach (View view in _subviews)
  218. {
  219. if (!view.IsInitialized)
  220. {
  221. view.BeginInit ();
  222. }
  223. }
  224. }
  225. }
  226. // TODO: Implement logic that allows EndInit to throw if BeginInit has not been called
  227. // TODO: See EndInit_Called_Without_BeginInit_Throws test.
  228. /// <summary>Signals the View that initialization is ending. See <see cref="ISupportInitialize"/>.</summary>
  229. /// <remarks>
  230. /// <para>Initializes all Subviews and Invokes the <see cref="Initialized"/> event.</para>
  231. /// </remarks>
  232. public virtual void EndInit ()
  233. {
  234. if (IsInitialized)
  235. {
  236. throw new InvalidOperationException ("The view is already initialized.");
  237. }
  238. IsInitialized = true;
  239. EndInitAdornments ();
  240. // TODO: Move these into ViewText.cs as EndInit_Text() to consolidate.
  241. // TODO: Verify UpdateTextDirection really needs to be called here.
  242. // These calls were moved from BeginInit as they access Viewport which is indeterminate until EndInit is called.
  243. UpdateTextDirection (TextDirection);
  244. UpdateTextFormatterText ();
  245. OnResizeNeeded ();
  246. if (_subviews is { })
  247. {
  248. foreach (View view in _subviews)
  249. {
  250. if (!view.IsInitialized)
  251. {
  252. view.EndInit ();
  253. }
  254. }
  255. }
  256. Initialized?.Invoke (this, EventArgs.Empty);
  257. }
  258. #endregion Constructors and Initialization
  259. #region Visibility
  260. private bool _enabled = true;
  261. // This is a cache of the Enabled property so that we can restore it when the superview is re-enabled.
  262. private bool _oldEnabled;
  263. /// <summary>Gets or sets a value indicating whether this <see cref="Responder"/> can respond to user interaction.</summary>
  264. public bool Enabled
  265. {
  266. get => _enabled;
  267. set
  268. {
  269. if (_enabled == value)
  270. {
  271. return;
  272. }
  273. _enabled = value;
  274. if (!_enabled && HasFocus)
  275. {
  276. HasFocus = false;
  277. }
  278. if (_enabled && CanFocus && Visible && !HasFocus && SuperView is { } && SuperView?.Focused is null)
  279. {
  280. SetFocus ();
  281. }
  282. OnEnabledChanged ();
  283. SetNeedsDisplay ();
  284. if (_subviews is null)
  285. {
  286. return;
  287. }
  288. foreach (View view in _subviews)
  289. {
  290. if (!_enabled)
  291. {
  292. view._oldEnabled = view.Enabled;
  293. view.Enabled = _enabled;
  294. }
  295. else
  296. {
  297. view.Enabled = view._oldEnabled;
  298. #if AUTO_CANFOCUS
  299. view._addingViewSoCanFocusAlsoUpdatesSuperView = _enabled;
  300. #endif
  301. }
  302. }
  303. }
  304. }
  305. /// <summary>Event fired when the <see cref="Enabled"/> value is being changed.</summary>
  306. public event EventHandler EnabledChanged;
  307. /// <summary>Method invoked when the <see cref="Enabled"/> property from a view is changed.</summary>
  308. public virtual void OnEnabledChanged () { EnabledChanged?.Invoke (this, EventArgs.Empty); }
  309. private bool _visible = true;
  310. /// <summary>Gets or sets a value indicating whether this <see cref="Responder"/> and all its child controls are displayed.</summary>
  311. public virtual bool Visible
  312. {
  313. get => _visible;
  314. set
  315. {
  316. if (_visible == value)
  317. {
  318. return;
  319. }
  320. _visible = value;
  321. if (!_visible)
  322. {
  323. if (HasFocus)
  324. {
  325. HasFocus = false;
  326. }
  327. if (IsInitialized && ClearOnVisibleFalse)
  328. {
  329. Clear ();
  330. }
  331. }
  332. if (_visible && CanFocus && Enabled && !HasFocus && SuperView?.Focused == null)
  333. {
  334. SetFocus ();
  335. }
  336. OnVisibleChanged ();
  337. SetNeedsDisplay ();
  338. }
  339. }
  340. /// <summary>Method invoked when the <see cref="Visible"/> property from a view is changed.</summary>
  341. public virtual void OnVisibleChanged () { VisibleChanged?.Invoke (this, EventArgs.Empty); }
  342. /// <summary>Gets or sets whether a view is cleared if the <see cref="Visible"/> property is <see langword="false"/>.</summary>
  343. public bool ClearOnVisibleFalse { get; set; } = true;
  344. /// <summary>Event fired when the <see cref="Visible"/> value is being changed.</summary>
  345. public event EventHandler VisibleChanged;
  346. /// <summary>
  347. /// INTERNAL method for determining if all the specified view and all views up the Superview hierarchy are visible.
  348. /// </summary>
  349. /// <param name="view">The view to test.</param>
  350. /// <returns> <see langword="false"/> if `view.Visible` is <see langword="false"/> or any Superview is not visible, <see langword="true"/> otherwise.</returns>
  351. private static bool CanBeVisible (View view)
  352. {
  353. if (!view.Visible)
  354. {
  355. return false;
  356. }
  357. for (View c = view.SuperView; c != null; c = c.SuperView)
  358. {
  359. if (!c.Visible)
  360. {
  361. return false;
  362. }
  363. }
  364. return true;
  365. }
  366. #endregion Visibility
  367. #region Title
  368. private string _title = string.Empty;
  369. /// <summary>Gets the <see cref="Gui.TextFormatter"/> used to format <see cref="Title"/>.</summary>
  370. internal TextFormatter TitleTextFormatter { get; init; } = new ();
  371. /// <summary>
  372. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.
  373. /// <see cref="Thickness.Top"/> is greater than 0. The title can be used to set the <see cref="HotKey"/>
  374. /// for the view by prefixing character with <see cref="HotKeySpecifier"/> (e.g. <c>"T_itle"</c>).
  375. /// </summary>
  376. /// <remarks>
  377. /// <para>
  378. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable Title-based hotkey support set
  379. /// <see cref="HotKeySpecifier"/> to <c>(Rune)0xffff</c>.
  380. /// </para>
  381. /// <para>
  382. /// Only the first HotKey specifier found in <see cref="Title"/> is supported.
  383. /// </para>
  384. /// <para>
  385. /// To cause the hotkey to be rendered with <see cref="Text"/>,
  386. /// set <c>View.</c><see cref="TextFormatter.HotKeySpecifier"/> to the desired character.
  387. /// </para>
  388. /// </remarks>
  389. /// <value>The title.</value>
  390. public string Title
  391. {
  392. get
  393. {
  394. #if DEBUG_IDISPOSABLE
  395. if (WasDisposed)
  396. {
  397. throw new ObjectDisposedException (GetType ().FullName);
  398. }
  399. #endif
  400. return _title;
  401. }
  402. set
  403. {
  404. #if DEBUG_IDISPOSABLE
  405. if (WasDisposed)
  406. {
  407. throw new ObjectDisposedException (GetType ().FullName);
  408. }
  409. #endif
  410. if (value == _title)
  411. {
  412. return;
  413. }
  414. if (!OnTitleChanging (ref value))
  415. {
  416. string old = _title;
  417. _title = value;
  418. TitleTextFormatter.Text = _title;
  419. SetTitleTextFormatterSize ();
  420. SetHotKeyFromTitle ();
  421. SetNeedsDisplay ();
  422. #if DEBUG
  423. if (_title is { } && string.IsNullOrEmpty (Id))
  424. {
  425. Id = _title;
  426. }
  427. #endif // DEBUG
  428. OnTitleChanged ();
  429. }
  430. }
  431. }
  432. private void SetTitleTextFormatterSize ()
  433. {
  434. TitleTextFormatter.ConstrainToSize = new (
  435. TextFormatter.GetWidestLineLength (TitleTextFormatter.Text)
  436. - (TitleTextFormatter.Text?.Contains ((char)HotKeySpecifier.Value) == true
  437. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  438. : 0),
  439. 1);
  440. }
  441. /// <summary>Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.</summary>
  442. protected void OnTitleChanged ()
  443. {
  444. TitleChanged?.Invoke (this, new (in _title));
  445. }
  446. /// <summary>
  447. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can
  448. /// be cancelled.
  449. /// </summary>
  450. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  451. /// <returns>`true` if an event handler canceled the Title change.</returns>
  452. protected bool OnTitleChanging (ref string newTitle)
  453. {
  454. CancelEventArgs<string> args = new (ref _title, ref newTitle);
  455. TitleChanging?.Invoke (this, args);
  456. return args.Cancel;
  457. }
  458. /// <summary>Event fired after the <see cref="View.Title"/> has been changed.</summary>
  459. public event EventHandler<EventArgs<string>> TitleChanged;
  460. /// <summary>
  461. /// Event fired when the <see cref="View.Title"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to `true`
  462. /// to cancel the Title change.
  463. /// </summary>
  464. public event EventHandler<CancelEventArgs<string>> TitleChanging;
  465. #endregion
  466. }