View.cs 20 KB

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