View.cs 20 KB

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