View.cs 20 KB

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