View.cs 21 KB

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