View.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. //
  2. // Authors:
  3. // Miguel de Icaza ([email protected])
  4. //
  5. // Pending:
  6. // - Check for NeedDisplay on the hierarchy and repaint
  7. // - Layout support
  8. // - "Colors" type or "Attributes" type?
  9. // - What to surface as "BackgroundCOlor" when clearing a window, an attribute or colors?
  10. //
  11. // Optimziations
  12. // - Add rendering limitation to the exposed area
  13. using System;
  14. using System.Collections;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.Linq;
  18. using NStack;
  19. namespace Terminal.Gui {
  20. /// <summary>
  21. /// Text alignment enumeration, controls how text is displayed.
  22. /// </summary>
  23. public enum TextAlignment {
  24. /// <summary>
  25. /// Aligns the text to the left of the frame.
  26. /// </summary>
  27. Left,
  28. /// <summary>
  29. /// Aligns the text to the right side of the frame.
  30. /// </summary>
  31. Right,
  32. /// <summary>
  33. /// Centers the text in the frame.
  34. /// </summary>
  35. Centered,
  36. /// <summary>
  37. /// Shows the text as justified text in the frame.
  38. /// </summary>
  39. Justified
  40. }
  41. /// <summary>
  42. /// Determines the LayoutStyle for a view, if Absolute, during LayoutSubviews, the
  43. /// value from the Frame will be used, if the value is Computed, then the Frame
  44. /// will be updated from the X, Y Pos objects and the Width and Height Dim objects.
  45. /// </summary>
  46. public enum LayoutStyle {
  47. /// <summary>
  48. /// The position and size of the view are based on the Frame value.
  49. /// </summary>
  50. Absolute,
  51. /// <summary>
  52. /// The position and size of the view will be computed based on the
  53. /// X, Y, Width and Height properties and set on the Frame.
  54. /// </summary>
  55. Computed
  56. }
  57. /// <summary>
  58. /// View is the base class for all views on the screen and represents a visible element that can render itself and contains zero or more nested views.
  59. /// </summary>
  60. /// <remarks>
  61. /// <para>
  62. /// The View defines the base functionality for user interface elements in Terminal.Gui. Views
  63. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  64. /// </para>
  65. /// <para>
  66. /// Views supports two layout styles: Absolute or Computed. The choice as to which layout style is used by the View
  67. /// is determined when the View is initizlied. To create a View using Absolute layout, call a constructor that takes a
  68. /// Rect parameter to specify the absolute position and size (the <c>View.<see cref="Frame "/></c>)/. To create a View
  69. /// using Computed layout use a constructor that does not take a Rect parametr and set the X, Y, Width and Height
  70. /// properties on the view. Both approaches use coordinates that are relative to the container they are being added to.
  71. /// </para>
  72. /// <para>
  73. /// To switch between Absolute and Computed layout, use the <see cref="LayoutStyle"/> property.
  74. /// </para>
  75. /// <para>
  76. /// Computed layout is more flexible and supports dynamic console apps where controls adjust layout
  77. /// as the terminal resizes or other Views change size or position. The X, Y, Width and Height
  78. /// properties are Dim and Pos objects that dynamically update the position of a view.
  79. /// The X and Y properties are of type <see cref="Pos"/>
  80. /// and you can use either absolute positions, percentages or anchor
  81. /// points. The Width and Height properties are of type
  82. /// <see cref="Dim"/> and can use absolute position,
  83. /// percentages and anchors. These are useful as they will take
  84. /// care of repositioning views when view's frames are resized or
  85. /// if the terminal size changes.
  86. /// </para>
  87. /// <para>
  88. /// Absolute layout requires specifying coordiantes and sizes of Views explicitly, and the
  89. /// View will typcialy stay in a fixed position and size. To change the position and size use the
  90. /// <see cref="Frame"/> property.
  91. /// </para>
  92. /// <para>
  93. /// Subviews (child views) can be added to a View by calling the <see cref="Add(View)"/> method.
  94. /// The container of a View can be accessed with the <see cref="SuperView"/> property.
  95. /// </para>
  96. /// <para>
  97. /// To flag a region of the View's <see cref="Bounds"/> to be redrawn call <see cref="SetNeedsDisplay(Rect)"/>. To flag the entire view
  98. /// for redraw call <see cref="SetNeedsDisplay()"/>.
  99. /// </para>
  100. /// <para>
  101. /// Views have a <see cref="ColorScheme"/> property that defines the default colors that subviews
  102. /// should use for rendering. This ensures that the views fit in the context where
  103. /// they are being used, and allows for themes to be plugged in. For example, the
  104. /// default colors for windows and toplevels uses a blue background, while it uses
  105. /// a white background for dialog boxes and a red background for errors.
  106. /// </para>
  107. /// <para>
  108. /// Subclasses should not rely on <see cref="ColorScheme"/> being
  109. /// set at construction time. If a <see cref="ColorScheme"/> is not set on a view, the view will inherit the
  110. /// value from its <see cref="SuperView"/> and the value might only be valid once a view has been
  111. /// added to a SuperView.
  112. /// </para>
  113. /// <para>
  114. /// By using <see cref="ColorScheme"/> applications will work both
  115. /// in color as well as black and white displays.
  116. /// </para>
  117. /// <para>
  118. /// Views that are focusable should implement the <see cref="PositionCursor"/> to make sure that
  119. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  120. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  121. /// the last focused view. So views should make sure that they place the cursor
  122. /// in a visually sensible place.
  123. /// </para>
  124. /// <para>
  125. /// The <see cref="LayoutSubviews"/> method is invoked when the size or layout of a view has
  126. /// changed. The default processing system will keep the size and dimensions
  127. /// for views that use the <see cref="LayoutStyle.Absolute"/>, and will recompute the
  128. /// frames for the vies that use <see cref="LayoutStyle.Computed"/>.
  129. /// </para>
  130. /// </remarks>
  131. public class View : Responder, IEnumerable {
  132. /// <summary>
  133. /// Suppports text formatting, including horizontal alignment and word wrap for <see cref="View"/>.
  134. /// </summary>
  135. public class ViewText {
  136. List<ustring> lines = new List<ustring> ();
  137. ustring text;
  138. TextAlignment textAlignment;
  139. Attribute textColor = -1;
  140. View view;
  141. /// <summary>
  142. /// Inititalizes a new <see cref="ViewText"/> object.
  143. /// </summary>
  144. /// <param name="view"></param>
  145. public ViewText (View view)
  146. {
  147. this.view = view;
  148. recalcPending = true;
  149. }
  150. /// <summary>
  151. /// The text to be displayed.
  152. /// </summary>
  153. public virtual ustring Text {
  154. get => text;
  155. set {
  156. text = value;
  157. recalcPending = true;
  158. view.SetNeedsDisplay ();
  159. }
  160. }
  161. // TODO: Add Vertical Text Alignment
  162. /// <summary>
  163. /// Controls the horizontal text-alignment property.
  164. /// </summary>
  165. /// <value>The text alignment.</value>
  166. public TextAlignment TextAlignment {
  167. get => textAlignment;
  168. set {
  169. textAlignment = value;
  170. recalcPending = true;
  171. view.SetNeedsDisplay ();
  172. }
  173. }
  174. /// <summary>
  175. /// The color used for the drawing of the <see cref="Text"/>.
  176. /// </summary>
  177. public Attribute TextColor {
  178. get => textColor;
  179. set {
  180. textColor = value;
  181. recalcPending = true;
  182. view.SetNeedsDisplay ();
  183. }
  184. }
  185. /// <summary>
  186. /// Gets the size of the area the text will be drawn in.
  187. /// </summary>
  188. public Size TextSize { get; internal set; }
  189. bool recalcPending = false;
  190. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  191. public Rune HotKey { get => hotKey; set => hotKey = value; }
  192. Rune hotKey;
  193. /// <summary>
  194. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  195. /// </summary>
  196. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  197. /// <summary>
  198. /// Causes the Text to be formatted, based on <see cref="TextAlignment"/> and <see cref="TextSize"/>.
  199. /// </summary>
  200. public void ReFormat ()
  201. {
  202. // With this check, we protect against subclasses with overrides of Text
  203. if (ustring.IsNullOrEmpty (Text)) {
  204. return;
  205. }
  206. recalcPending = false;
  207. var shown_text = ProcessHotKeyText (text, HotKeySpecifier, false, out hotKeyPos, out hotKey);
  208. Reformat (shown_text, lines, TextSize.Width, textAlignment, TextSize.Height > 1);
  209. }
  210. static ustring StripCRLF (ustring str)
  211. {
  212. var runes = new List<Rune> ();
  213. foreach (var r in str.ToRunes ()) {
  214. if (r != '\r' && r != '\n') {
  215. runes.Add (r);
  216. }
  217. }
  218. return ustring.Make (runes); ;
  219. }
  220. static ustring ReplaceCRLFWithSpace (ustring str)
  221. {
  222. var runes = new List<Rune> ();
  223. foreach (var r in str.ToRunes ()) {
  224. if (r == '\r' || r == '\n') {
  225. runes.Add (new Rune (' ')); // r + 0x2400)); // U+25A1 □ WHITE SQUARE
  226. } else {
  227. runes.Add (r);
  228. }
  229. }
  230. return ustring.Make (runes); ;
  231. }
  232. static List<ustring> WordWrap (ustring text, int margin)
  233. {
  234. int start = 0, end;
  235. var lines = new List<ustring> ();
  236. text = StripCRLF (text);
  237. while ((end = start + margin) < text.Length) {
  238. while (text [end] != ' ' && end > start)
  239. end -= 1;
  240. if (end == start)
  241. end = start + margin;
  242. lines.Add (text [start, end]);
  243. start = end + 1;
  244. }
  245. if (start < text.Length)
  246. lines.Add (text.Substring (start));
  247. return lines;
  248. }
  249. static ustring ClipAndJustify (ustring str, int width, TextAlignment talign)
  250. {
  251. int slen = str.RuneCount;
  252. if (slen > width) {
  253. var uints = str.ToRunes (width);
  254. var runes = new Rune [uints.Length];
  255. for (int i = 0; i < uints.Length; i++)
  256. runes [i] = uints [i];
  257. return ustring.Make (runes);
  258. } else {
  259. if (talign == TextAlignment.Justified) {
  260. // TODO: ustring needs this
  261. var words = str.ToString ().Split (whitespace, StringSplitOptions.RemoveEmptyEntries);
  262. int textCount = words.Sum (arg => arg.Length);
  263. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  264. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  265. var s = new System.Text.StringBuilder ();
  266. //s.Append ($"tc={textCount} sp={spaces},x={extras} - ");
  267. for (int w = 0; w < words.Length; w++) {
  268. var x = words [w];
  269. s.Append (x);
  270. if (w + 1 < words.Length)
  271. for (int i = 0; i < spaces; i++)
  272. s.Append (' ');
  273. if (extras > 0) {
  274. //s.Append ('_');
  275. extras--;
  276. }
  277. }
  278. return ustring.Make (s.ToString ());
  279. }
  280. return str;
  281. }
  282. }
  283. static char [] whitespace = new char [] { ' ', '\t' };
  284. private int hotKeyPos;
  285. /// <summary>
  286. /// Reformats text into lines, applying text alignment and word wraping.
  287. /// </summary>
  288. /// <param name="textStr"></param>
  289. /// <param name="lineResult"></param>
  290. /// <param name="width"></param>
  291. /// <param name="talign"></param>
  292. /// <param name="wordWrap">if <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces.</param>
  293. static void Reformat (ustring textStr, List<ustring> lineResult, int width, TextAlignment talign, bool wordWrap)
  294. {
  295. lineResult.Clear ();
  296. if (wordWrap == false) {
  297. textStr = ReplaceCRLFWithSpace (textStr);
  298. lineResult.Add (ClipAndJustify (textStr, width, talign));
  299. return;
  300. }
  301. int textLen = textStr.Length;
  302. int lp = 0;
  303. for (int i = 0; i < textLen; i++) {
  304. Rune c = textStr [i];
  305. if (c == '\n') {
  306. var wrappedLines = WordWrap (textStr [lp, i], width);
  307. foreach (var line in wrappedLines) {
  308. lineResult.Add (ClipAndJustify (line, width, talign));
  309. }
  310. if (wrappedLines.Count == 0) {
  311. lineResult.Add (ustring.Empty);
  312. }
  313. lp = i + 1;
  314. }
  315. }
  316. foreach (var line in WordWrap (textStr [lp, textLen], width)) {
  317. lineResult.Add (ClipAndJustify (line, width, talign));
  318. }
  319. }
  320. /// <summary>
  321. /// Computes the number of lines needed to render the specified text given the width.
  322. /// </summary>
  323. /// <returns>Number of lines.</returns>
  324. /// <param name="text">Text, may contain newlines.</param>
  325. /// <param name="width">The minimum width for the text.</param>
  326. public static int MaxLines (ustring text, int width)
  327. {
  328. var result = new List<ustring> ();
  329. ViewText.Reformat (text, result, width, TextAlignment.Left, true);
  330. return result.Count;
  331. }
  332. /// <summary>
  333. /// Computes the maximum width needed to render the text (single line or multple lines).
  334. /// </summary>
  335. /// <returns>Max width of lines.</returns>
  336. /// <param name="text">Text, may contain newlines.</param>
  337. /// <param name="width">The minimum width for the text.</param>
  338. public static int MaxWidth (ustring text, int width)
  339. {
  340. var result = new List<ustring> ();
  341. ViewText.Reformat (text, result, width, TextAlignment.Left, true);
  342. return result.Max (s => s.RuneCount);
  343. }
  344. internal void Draw (Rect bounds)
  345. {
  346. // With this check, we protect against subclasses with overrides of Text
  347. if (ustring.IsNullOrEmpty (text)) {
  348. return;
  349. }
  350. if (recalcPending) {
  351. ReFormat ();
  352. }
  353. if (TextColor != -1)
  354. Driver.SetAttribute (TextColor);
  355. else
  356. Driver.SetAttribute (view.ColorScheme.Normal);
  357. view.Clear ();
  358. for (int line = 0; line < lines.Count; line++) {
  359. if (line < bounds.Top || line >= bounds.Bottom)
  360. continue;
  361. var str = lines [line];
  362. int x;
  363. switch (textAlignment) {
  364. case TextAlignment.Left:
  365. x = 0;
  366. break;
  367. case TextAlignment.Justified:
  368. x = bounds.Left;
  369. break;
  370. case TextAlignment.Right:
  371. x = bounds.Right - str.Length;
  372. break;
  373. case TextAlignment.Centered:
  374. x = bounds.Left + (bounds.Width - str.Length) / 2;
  375. break;
  376. default:
  377. throw new ArgumentOutOfRangeException ();
  378. }
  379. view.Move (x, line);
  380. Driver.AddStr (str);
  381. }
  382. if (HotKeyPos != -1) {
  383. _ = GetAlignedText (lines [0], TextSize.Width, hotKeyPos, out hotKeyPos, textAlignment);
  384. view.Move (HotKeyPos, 0);
  385. Driver.SetAttribute (view.HasFocus ? view.ColorScheme.HotFocus : view.ColorScheme.HotNormal);
  386. Driver.AddRune (hotKey);
  387. }
  388. }
  389. /// <summary>
  390. /// Calculates the rectangle requried to hold text, assuming no word wrapping.
  391. /// </summary>
  392. /// <param name="x">The x location of the rectangle</param>
  393. /// <param name="y">The y location of the rectangle</param>
  394. /// <param name="text">The text to measure</param>
  395. /// <returns></returns>
  396. public static Rect CalcRect (int x, int y, ustring text)
  397. {
  398. if (ustring.IsNullOrEmpty (text))
  399. return Rect.Empty;
  400. int mw = 0;
  401. int ml = 1;
  402. int cols = 0;
  403. foreach (var rune in text) {
  404. if (rune == '\n') {
  405. ml++;
  406. if (cols > mw)
  407. mw = cols;
  408. cols = 0;
  409. } else
  410. cols++;
  411. }
  412. if (cols > mw)
  413. mw = cols;
  414. return new Rect (x, y, mw, ml);
  415. }
  416. /// <summary>
  417. /// Gets the position and Rune for the hotkey in text and removes the hotkey specifier.
  418. /// </summary>
  419. /// <param name="text">The text to manipulate.</param>
  420. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  421. /// <param name="firstUpperCase">If <c>true</c> and no hotkey is found via the hotkey specifier, the first upper case char found will be the hotkey.</param>
  422. /// <param name="hotPos">Returns the postion of the hot-key in the text. -1 if not found.</param>
  423. /// <param name="showHotKey">Returns the Rune immediately to the right of the hot-key position</param>
  424. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  425. public static ustring ProcessHotKeyText (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Rune showHotKey)
  426. {
  427. if (hotKeySpecifier == (Rune)0xFFFF) {
  428. hotPos = -1;
  429. showHotKey = (Rune)0xFFFF;
  430. return text;
  431. }
  432. Rune hot_key = (Rune)0;
  433. int hot_pos = -1;
  434. ustring shown_text = text;
  435. // Use first hot_key char passed into 'hotKey'.
  436. // TODO: Ignore hot_key of two are provided
  437. int i = 0;
  438. foreach (Rune c in shown_text) {
  439. if ((char)c != 0xFFFD) {
  440. if (c == hotKeySpecifier) {
  441. hot_pos = i;
  442. } else if (hot_pos > -1) {
  443. hot_key = c;
  444. break;
  445. }
  446. }
  447. i++;
  448. }
  449. // Legacy support - use first upper case char if the specifier was not found
  450. if (hot_pos == -1 && firstUpperCase) {
  451. i = 0;
  452. foreach (Rune c in shown_text) {
  453. if ((char)c != 0xFFFD) {
  454. if (Rune.IsUpper (c)) {
  455. hot_key = c;
  456. hot_pos = i;
  457. break;
  458. }
  459. }
  460. i++;
  461. }
  462. }
  463. else {
  464. if (hot_pos != -1) {
  465. // Use char after 'hotKey'
  466. ustring start = "";
  467. i = 0;
  468. foreach (Rune c in shown_text) {
  469. start += ustring.Make (c);
  470. i++;
  471. if (i == hot_pos)
  472. break;
  473. }
  474. var st = shown_text;
  475. shown_text = start;
  476. i = 0;
  477. foreach (Rune c in st) {
  478. i++;
  479. if (i > hot_pos + 1) {
  480. shown_text += ustring.Make (c);
  481. }
  482. }
  483. }
  484. }
  485. hotPos = hot_pos;
  486. showHotKey = hot_key;
  487. return shown_text;
  488. }
  489. /// <summary>
  490. /// Formats a single line of text with a hot-key and <see cref="TextAlignment"/>.
  491. /// </summary>
  492. /// <param name="shown_text">The text to align.</param>
  493. /// <param name="width">The maximum width for the text.</param>
  494. /// <param name="hot_pos">The hot-key position before reformatting.</param>
  495. /// <param name="c_hot_pos">The hot-key position after reformatting.</param>
  496. /// <param name="textAlignment">The <see cref="TextAlignment"/> to align to.</param>
  497. /// <returns>The aligned text.</returns>
  498. public static ustring GetAlignedText (ustring shown_text, int width, int hot_pos, out int c_hot_pos, TextAlignment textAlignment)
  499. {
  500. int start;
  501. var caption = shown_text;
  502. c_hot_pos = hot_pos;
  503. if (width > shown_text.Length + 1) {
  504. switch (textAlignment) {
  505. case TextAlignment.Left:
  506. caption += new string (' ', width - caption.RuneCount);
  507. break;
  508. case TextAlignment.Right:
  509. start = width - caption.RuneCount;
  510. caption = $"{new string (' ', width - caption.RuneCount)}{caption}";
  511. if (c_hot_pos > -1) {
  512. c_hot_pos += start;
  513. }
  514. break;
  515. case TextAlignment.Centered:
  516. start = width / 2 - caption.RuneCount / 2;
  517. caption = $"{new string (' ', start)}{caption}{new string (' ', width - caption.RuneCount - start)}";
  518. if (c_hot_pos > -1) {
  519. c_hot_pos += start;
  520. }
  521. break;
  522. case TextAlignment.Justified:
  523. var words = caption.Split (" ");
  524. var wLen = GetWordsLength (words, c_hot_pos, out int runeCount, out int w_hot_pos);
  525. var space = (width - runeCount) / (caption.Length - wLen);
  526. caption = "";
  527. for (int i = 0; i < words.Length; i++) {
  528. if (i == words.Length - 1) {
  529. caption += new string (' ', width - caption.RuneCount - 1);
  530. caption += words [i];
  531. } else {
  532. caption += words [i];
  533. }
  534. if (i < words.Length - 1) {
  535. caption += new string (' ', space);
  536. }
  537. }
  538. if (c_hot_pos > -1) {
  539. c_hot_pos += w_hot_pos * space - space - w_hot_pos + 1;
  540. }
  541. break;
  542. }
  543. }
  544. return caption;
  545. }
  546. static int GetWordsLength (ustring [] words, int hotPos, out int runeCount, out int wordHotPos)
  547. {
  548. int length = 0;
  549. int rCount = 0;
  550. int wHotPos = -1;
  551. for (int i = 0; i < words.Length; i++) {
  552. if (wHotPos == -1 && rCount + words [i].RuneCount >= hotPos)
  553. wHotPos = i;
  554. length += words [i].Length;
  555. rCount += words [i].RuneCount;
  556. }
  557. if (wHotPos == -1 && hotPos > -1)
  558. wHotPos = words.Length;
  559. runeCount = rCount;
  560. wordHotPos = wHotPos;
  561. return length;
  562. }
  563. }
  564. internal enum Direction {
  565. Forward,
  566. Backward
  567. }
  568. // container == SuperView
  569. View container = null;
  570. View focused = null;
  571. Direction focusDirection;
  572. ViewText viewText;
  573. /// <summary>
  574. /// Event fired when the view gets focus.
  575. /// </summary>
  576. public Action<FocusEventArgs> Enter;
  577. /// <summary>
  578. /// Event fired when the view looses focus.
  579. /// </summary>
  580. public Action<FocusEventArgs> Leave;
  581. /// <summary>
  582. /// Event fired when the view receives the mouse event for the first time.
  583. /// </summary>
  584. public Action<MouseEventArgs> MouseEnter;
  585. /// <summary>
  586. /// Event fired when the view receives a mouse event for the last time.
  587. /// </summary>
  588. public Action<MouseEventArgs> MouseLeave;
  589. /// <summary>
  590. /// Event fired when a mouse event is generated.
  591. /// </summary>
  592. public Action<MouseEventArgs> MouseClick;
  593. /// <summary>
  594. /// The HotKey defined for this view. A user pressing HotKey on the keyboard while this view has focus will cause the Clicked event to fire.
  595. /// </summary>
  596. public Rune HotKey { get => viewText.HotKey; set => viewText.HotKey = value; }
  597. /// <summary>
  598. ///
  599. /// </summary>
  600. public Rune HotKeySpecifier { get => viewText.HotKeySpecifier; set => viewText.HotKeySpecifier = value; }
  601. /// <summary>
  602. /// Clicked <see cref="Action"/>, raised when the user clicks the primary mouse button within the Bounds of this <see cref="View"/>
  603. /// or if the user presses the action key while this view is focused. (TODO: IsDefault)
  604. /// </summary>
  605. /// <remarks>
  606. /// Client code can hook up to this event, it is
  607. /// raised when the button is activated either with
  608. /// the mouse or the keyboard.
  609. /// </remarks>
  610. public Action Clicked;
  611. internal Direction FocusDirection {
  612. get => SuperView?.FocusDirection ?? focusDirection;
  613. set {
  614. if (SuperView != null)
  615. SuperView.FocusDirection = value;
  616. else
  617. focusDirection = value;
  618. }
  619. }
  620. /// <summary>
  621. /// Points to the current driver in use by the view, it is a convenience property
  622. /// for simplifying the development of new views.
  623. /// </summary>
  624. public static ConsoleDriver Driver { get { return Application.Driver; } }
  625. static IList<View> empty = new List<View> (0).AsReadOnly ();
  626. // This is null, and allocated on demand.
  627. List<View> subviews;
  628. /// <summary>
  629. /// This returns a list of the subviews contained by this view.
  630. /// </summary>
  631. /// <value>The subviews.</value>
  632. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  633. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  634. // to make the same mistakes our users make when they poke at the Subviews.
  635. internal IList<View> InternalSubviews => subviews ?? empty;
  636. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  637. // The frame for the object. Superview relative.
  638. Rect frame;
  639. /// <summary>
  640. /// Gets or sets an identifier for the view;
  641. /// </summary>
  642. /// <value>The identifier.</value>
  643. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  644. public ustring Id { get; set; } = "";
  645. /// <summary>
  646. /// Returns a value indicating if this View is currently on Top (Active)
  647. /// </summary>
  648. public bool IsCurrentTop {
  649. get {
  650. return Application.Current == this;
  651. }
  652. }
  653. /// <summary>
  654. /// Gets or sets a value indicating whether this <see cref="View"/> wants mouse position reports.
  655. /// </summary>
  656. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  657. public virtual bool WantMousePositionReports { get; set; } = false;
  658. /// <summary>
  659. /// Gets or sets a value indicating whether this <see cref="View"/> want continuous button pressed event.
  660. /// </summary>
  661. public virtual bool WantContinuousButtonPressed { get; set; } = false;
  662. /// <summary>
  663. /// Gets or sets the frame for the view. The frame is relative to the view's container (<see cref="SuperView"/>).
  664. /// </summary>
  665. /// <value>The frame.</value>
  666. /// <remarks>
  667. /// <para>
  668. /// Change the Frame when using the <see cref="LayoutStyle.Absolute"/> layout style to move or resize views.
  669. /// </para>
  670. /// <para>
  671. /// Altering the Frame of a view will trigger the redrawing of the
  672. /// view as well as the redrawing of the affected regions of the <see cref="SuperView"/>.
  673. /// </para>
  674. /// </remarks>
  675. public virtual Rect Frame {
  676. get => frame;
  677. set {
  678. if (SuperView != null) {
  679. SuperView.SetNeedsDisplay (frame);
  680. SuperView.SetNeedsDisplay (value);
  681. }
  682. frame = value;
  683. SetNeedsLayout ();
  684. SetNeedsDisplay (frame);
  685. }
  686. }
  687. /// <summary>
  688. /// Gets an enumerator that enumerates the subviews in this view.
  689. /// </summary>
  690. /// <returns>The enumerator.</returns>
  691. public IEnumerator GetEnumerator ()
  692. {
  693. foreach (var v in InternalSubviews)
  694. yield return v;
  695. }
  696. LayoutStyle layoutStyle;
  697. /// <summary>
  698. /// Controls how the View's <see cref="Frame"/> is computed during the LayoutSubviews method, if the style is set to <see cref="LayoutStyle.Absolute"/>,
  699. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using
  700. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  701. /// </summary>
  702. /// <value>The layout style.</value>
  703. public LayoutStyle LayoutStyle {
  704. get => layoutStyle;
  705. set {
  706. layoutStyle = value;
  707. SetNeedsLayout ();
  708. }
  709. }
  710. /// <summary>
  711. /// The bounds represent the View-relative rectangle used for this view; the area inside of the view.
  712. /// </summary>
  713. /// <value>The bounds.</value>
  714. /// <remarks>
  715. /// <para>
  716. /// Updates to the Bounds update the <see cref="Frame"/>,
  717. /// and has the same side effects as updating the <see cref="Frame"/>.
  718. /// </para>
  719. /// <para>
  720. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>,
  721. /// the coordinates of the upper-left corner of the rectangle returned by this property are (0,0).
  722. /// Use this property to obtain the size and coordinates of the client area of the
  723. /// control for tasks such as drawing on the surface of the control.
  724. /// </para>
  725. /// </remarks>
  726. public Rect Bounds {
  727. get => new Rect (Point.Empty, Frame.Size);
  728. set {
  729. Frame = new Rect (frame.Location, value.Size);
  730. }
  731. }
  732. Pos x, y;
  733. /// <summary>
  734. /// Gets or sets the X position for the view (the column). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  735. /// </summary>
  736. /// <value>The X Position.</value>
  737. /// <remarks>
  738. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  739. /// </remarks>
  740. public Pos X {
  741. get => x;
  742. set {
  743. x = value;
  744. SetNeedsLayout ();
  745. SetNeedsDisplay (frame);
  746. }
  747. }
  748. /// <summary>
  749. /// Gets or sets the Y position for the view (the row). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  750. /// </summary>
  751. /// <value>The y position (line).</value>
  752. /// <remarks>
  753. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  754. /// </remarks>
  755. public Pos Y {
  756. get => y;
  757. set {
  758. y = value;
  759. SetNeedsLayout ();
  760. SetNeedsDisplay (frame);
  761. }
  762. }
  763. Dim width, height;
  764. /// <summary>
  765. /// Gets or sets the width of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  766. /// </summary>
  767. /// <value>The width.</value>
  768. /// <remarks>
  769. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  770. /// </remarks>
  771. public Dim Width {
  772. get => width;
  773. set {
  774. width = value;
  775. SetNeedsLayout ();
  776. SetNeedsDisplay (frame);
  777. }
  778. }
  779. /// <summary>
  780. /// Gets or sets the height of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  781. /// </summary>
  782. /// <value>The height.</value>
  783. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  784. public Dim Height {
  785. get => height;
  786. set {
  787. height = value;
  788. SetNeedsLayout ();
  789. SetNeedsDisplay (frame);
  790. }
  791. }
  792. /// <summary>
  793. /// Returns the container for this view, or null if this view has not been added to a container.
  794. /// </summary>
  795. /// <value>The super view.</value>
  796. public View SuperView => container;
  797. /// <summary>
  798. /// Initializes a new instance of a <see cref="LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  799. /// dimensions specified in the <c>frame</c> parameter.
  800. /// </summary>
  801. /// <param name="frame">The region covered by this view.</param>
  802. /// <remarks>
  803. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Absolute"/>. Use <see cref="View()"/> to
  804. /// initialize a View with <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>
  805. /// </remarks>
  806. public View (Rect frame)
  807. {
  808. viewText = new ViewText (this);
  809. this.Text = ustring.Empty;
  810. this.Frame = frame;
  811. LayoutStyle = LayoutStyle.Absolute;
  812. }
  813. /// <summary>
  814. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  815. /// </summary>
  816. /// <remarks>
  817. /// <para>
  818. /// 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.
  819. /// The <see cref="Label"/> will be created using <see cref="LayoutStyle.Computed"/>
  820. /// coordinates. The initial size (<see cref="View.Frame"/> will be
  821. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  822. /// </para>
  823. /// <para>
  824. /// If <c>Height</c> is greater than one, word wrapping is provided.
  825. /// </para>
  826. /// <para>
  827. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>.
  828. /// 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.
  829. /// </para>
  830. /// </remarks>
  831. public View () : this (text: string.Empty) { }
  832. /// <summary>
  833. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  834. /// </summary>
  835. /// <remarks>
  836. /// <para>
  837. /// The <see cref="View"/> will be created at the given
  838. /// coordinates with the given string. The size (<see cref="View.Frame"/> will be
  839. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  840. /// </para>
  841. /// <para>
  842. /// No line wrapping is provided.
  843. /// </para>
  844. /// </remarks>
  845. /// <param name="x">column to locate the Label.</param>
  846. /// <param name="y">row to locate the Label.</param>
  847. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  848. public View (int x, int y, ustring text) : this (ViewText.CalcRect (x, y, text), text) { }
  849. /// <summary>
  850. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  851. /// </summary>
  852. /// <remarks>
  853. /// <para>
  854. /// The <see cref="View"/> will be created at the given
  855. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  856. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  857. /// </para>
  858. /// <para>
  859. /// If <c>rect.Height</c> is greater than one, word wrapping is provided.
  860. /// </para>
  861. /// </remarks>
  862. /// <param name="rect">Location.</param>
  863. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  864. public View (Rect rect, ustring text) : this (rect)
  865. {
  866. viewText = new ViewText (this);
  867. this.Text = text;
  868. }
  869. /// <summary>
  870. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  871. /// </summary>
  872. /// <remarks>
  873. /// <para>
  874. /// The <see cref="View"/> will be created using <see cref="LayoutStyle.Computed"/>
  875. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  876. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  877. /// </para>
  878. /// <para>
  879. /// If <c>Height</c> is greater than one, word wrapping is provided.
  880. /// </para>
  881. /// </remarks>
  882. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  883. public View (ustring text) : base ()
  884. {
  885. viewText = new ViewText (this);
  886. this.Text = text;
  887. CanFocus = false;
  888. LayoutStyle = LayoutStyle.Computed;
  889. var r = ViewText.CalcRect (0, 0, text);
  890. x = Pos.At (0);
  891. y = Pos.At (0);
  892. Width = r.Width;
  893. Height = r.Height;
  894. }
  895. /// <summary>
  896. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  897. /// </summary>
  898. public void SetNeedsDisplay ()
  899. {
  900. SetNeedsDisplay (Bounds);
  901. }
  902. internal bool layoutNeeded = true;
  903. internal void SetNeedsLayout ()
  904. {
  905. if (layoutNeeded)
  906. return;
  907. layoutNeeded = true;
  908. if (SuperView == null)
  909. return;
  910. SuperView.SetNeedsLayout ();
  911. viewText.ReFormat ();
  912. }
  913. /// <summary>
  914. /// Flags the view-relative region on this View as needing to be repainted.
  915. /// </summary>
  916. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  917. public void SetNeedsDisplay (Rect region)
  918. {
  919. if (NeedDisplay == null || NeedDisplay.IsEmpty)
  920. NeedDisplay = region;
  921. else {
  922. var x = Math.Min (NeedDisplay.X, region.X);
  923. var y = Math.Min (NeedDisplay.Y, region.Y);
  924. var w = Math.Max (NeedDisplay.Width, region.Width);
  925. var h = Math.Max (NeedDisplay.Height, region.Height);
  926. NeedDisplay = new Rect (x, y, w, h);
  927. }
  928. if (container != null)
  929. container.ChildNeedsDisplay ();
  930. if (subviews == null)
  931. return;
  932. foreach (var view in subviews)
  933. if (view.Frame.IntersectsWith (region)) {
  934. var childRegion = Rect.Intersect (view.Frame, region);
  935. childRegion.X -= view.Frame.X;
  936. childRegion.Y -= view.Frame.Y;
  937. view.SetNeedsDisplay (childRegion);
  938. }
  939. }
  940. internal bool childNeedsDisplay;
  941. /// <summary>
  942. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  943. /// </summary>
  944. public void ChildNeedsDisplay ()
  945. {
  946. childNeedsDisplay = true;
  947. if (container != null)
  948. container.ChildNeedsDisplay ();
  949. }
  950. /// <summary>
  951. /// Adds a subview (child) to this view.
  952. /// </summary>
  953. /// <remarks>
  954. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property. See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  955. /// </remarks>
  956. public virtual void Add (View view)
  957. {
  958. if (view == null)
  959. return;
  960. if (subviews == null)
  961. subviews = new List<View> ();
  962. subviews.Add (view);
  963. view.container = this;
  964. if (view.CanFocus)
  965. CanFocus = true;
  966. SetNeedsLayout ();
  967. SetNeedsDisplay ();
  968. }
  969. /// <summary>
  970. /// Adds the specified views (children) to the view.
  971. /// </summary>
  972. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  973. /// <remarks>
  974. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property. See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  975. /// </remarks>
  976. public void Add (params View [] views)
  977. {
  978. if (views == null)
  979. return;
  980. foreach (var view in views)
  981. Add (view);
  982. }
  983. /// <summary>
  984. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  985. /// </summary>
  986. public virtual void RemoveAll ()
  987. {
  988. if (subviews == null)
  989. return;
  990. while (subviews.Count > 0) {
  991. Remove (subviews [0]);
  992. }
  993. }
  994. /// <summary>
  995. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  996. /// </summary>
  997. /// <remarks>
  998. /// </remarks>
  999. public virtual void Remove (View view)
  1000. {
  1001. if (view == null || subviews == null)
  1002. return;
  1003. SetNeedsLayout ();
  1004. SetNeedsDisplay ();
  1005. var touched = view.Frame;
  1006. subviews.Remove (view);
  1007. view.container = null;
  1008. if (subviews.Count < 1)
  1009. this.CanFocus = false;
  1010. foreach (var v in subviews) {
  1011. if (v.Frame.IntersectsWith (touched))
  1012. view.SetNeedsDisplay ();
  1013. }
  1014. }
  1015. void PerformActionForSubview (View subview, Action<View> action)
  1016. {
  1017. if (subviews.Contains (subview)) {
  1018. action (subview);
  1019. }
  1020. SetNeedsDisplay ();
  1021. subview.SetNeedsDisplay ();
  1022. }
  1023. /// <summary>
  1024. /// Brings the specified subview to the front so it is drawn on top of any other views.
  1025. /// </summary>
  1026. /// <param name="subview">The subview to send to the front</param>
  1027. /// <remarks>
  1028. /// <seealso cref="SendSubviewToBack"/>.
  1029. /// </remarks>
  1030. public void BringSubviewToFront (View subview)
  1031. {
  1032. PerformActionForSubview (subview, x => {
  1033. subviews.Remove (x);
  1034. subviews.Add (x);
  1035. });
  1036. }
  1037. /// <summary>
  1038. /// Sends the specified subview to the front so it is the first view drawn
  1039. /// </summary>
  1040. /// <param name="subview">The subview to send to the front</param>
  1041. /// <remarks>
  1042. /// <seealso cref="BringSubviewToFront(View)"/>.
  1043. /// </remarks>
  1044. public void SendSubviewToBack (View subview)
  1045. {
  1046. PerformActionForSubview (subview, x => {
  1047. subviews.Remove (x);
  1048. subviews.Insert (0, subview);
  1049. });
  1050. }
  1051. /// <summary>
  1052. /// Moves the subview backwards in the hierarchy, only one step
  1053. /// </summary>
  1054. /// <param name="subview">The subview to send backwards</param>
  1055. /// <remarks>
  1056. /// If you want to send the view all the way to the back use SendSubviewToBack.
  1057. /// </remarks>
  1058. public void SendSubviewBackwards (View subview)
  1059. {
  1060. PerformActionForSubview (subview, x => {
  1061. var idx = subviews.IndexOf (x);
  1062. if (idx > 0) {
  1063. subviews.Remove (x);
  1064. subviews.Insert (idx - 1, x);
  1065. }
  1066. });
  1067. }
  1068. /// <summary>
  1069. /// Moves the subview backwards in the hierarchy, only one step
  1070. /// </summary>
  1071. /// <param name="subview">The subview to send backwards</param>
  1072. /// <remarks>
  1073. /// If you want to send the view all the way to the back use SendSubviewToBack.
  1074. /// </remarks>
  1075. public void BringSubviewForward (View subview)
  1076. {
  1077. PerformActionForSubview (subview, x => {
  1078. var idx = subviews.IndexOf (x);
  1079. if (idx + 1 < subviews.Count) {
  1080. subviews.Remove (x);
  1081. subviews.Insert (idx + 1, x);
  1082. }
  1083. });
  1084. }
  1085. /// <summary>
  1086. /// Clears the view region with the current color.
  1087. /// </summary>
  1088. /// <remarks>
  1089. /// <para>
  1090. /// This clears the entire region used by this view.
  1091. /// </para>
  1092. /// </remarks>
  1093. public void Clear ()
  1094. {
  1095. var h = Frame.Height;
  1096. var w = Frame.Width;
  1097. for (int line = 0; line < h; line++) {
  1098. Move (0, line);
  1099. for (int col = 0; col < w; col++)
  1100. Driver.AddRune (' ');
  1101. }
  1102. }
  1103. /// <summary>
  1104. /// Clears the specified region with the current color.
  1105. /// </summary>
  1106. /// <remarks>
  1107. /// </remarks>
  1108. /// <param name="regionScreen">The screen-relative region to clear.</param>
  1109. public void Clear (Rect regionScreen)
  1110. {
  1111. var h = regionScreen.Height;
  1112. var w = regionScreen.Width;
  1113. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  1114. Driver.Move (regionScreen.X, line);
  1115. for (int col = 0; col < w; col++)
  1116. Driver.AddRune (' ');
  1117. }
  1118. }
  1119. /// <summary>
  1120. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  1121. /// </summary>
  1122. /// <param name="col">View-relative column.</param>
  1123. /// <param name="row">View-relative row.</param>
  1124. /// <param name="rcol">Absolute column; screen-relative.</param>
  1125. /// <param name="rrow">Absolute row; screen-relative.</param>
  1126. /// <param name="clipped">Whether to clip the result of the ViewToScreen method, if set to <c>true</c>, the rcol, rrow values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  1127. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  1128. {
  1129. // Computes the real row, col relative to the screen.
  1130. rrow = row + frame.Y;
  1131. rcol = col + frame.X;
  1132. var ccontainer = container;
  1133. while (ccontainer != null) {
  1134. rrow += ccontainer.frame.Y;
  1135. rcol += ccontainer.frame.X;
  1136. ccontainer = ccontainer.container;
  1137. }
  1138. // The following ensures that the cursor is always in the screen boundaries.
  1139. if (clipped) {
  1140. rrow = Math.Min (rrow, Driver.Rows - 1);
  1141. rcol = Math.Min (rcol, Driver.Cols - 1);
  1142. }
  1143. }
  1144. /// <summary>
  1145. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  1146. /// </summary>
  1147. /// <returns>The mapped point.</returns>
  1148. /// <param name="x">X screen-coordinate point.</param>
  1149. /// <param name="y">Y screen-coordinate point.</param>
  1150. public Point ScreenToView (int x, int y)
  1151. {
  1152. if (SuperView == null) {
  1153. return new Point (x - Frame.X, y - frame.Y);
  1154. } else {
  1155. var parent = SuperView.ScreenToView (x, y);
  1156. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1157. }
  1158. }
  1159. /// <summary>
  1160. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  1161. /// </summary>
  1162. internal Rect ViewToScreen (Rect region)
  1163. {
  1164. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  1165. return new Rect (x, y, region.Width, region.Height);
  1166. }
  1167. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  1168. internal Rect ScreenClip (Rect regionScreen)
  1169. {
  1170. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  1171. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  1172. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  1173. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  1174. return new Rect (x, y, w, h);
  1175. }
  1176. /// <summary>
  1177. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  1178. /// </summary>
  1179. /// <returns>The existing driver's clip region, which can be then re-eapplied by setting <c><see cref="Driver"/>.Clip</c> (<see cref="ConsoleDriver.Clip"/>).</returns>
  1180. /// <remarks>
  1181. /// <see cref="Bounds"/> is View-relative.
  1182. /// </remarks>
  1183. public Rect ClipToBounds ()
  1184. {
  1185. return SetClip (Bounds);
  1186. }
  1187. /// <summary>
  1188. /// Sets the clip region to the specified view-relative region.
  1189. /// </summary>
  1190. /// <returns>The previous screen-relative clip region.</returns>
  1191. /// <param name="region">View-relative clip region.</param>
  1192. public Rect SetClip (Rect region)
  1193. {
  1194. var previous = Driver.Clip;
  1195. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  1196. return previous;
  1197. }
  1198. /// <summary>
  1199. /// Draws a frame in the current view, clipped by the boundary of this view
  1200. /// </summary>
  1201. /// <param name="region">View-relative region for the frame to be drawn.</param>
  1202. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  1203. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  1204. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  1205. {
  1206. var scrRect = ViewToScreen (region);
  1207. var savedClip = ClipToBounds ();
  1208. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  1209. Driver.Clip = savedClip;
  1210. }
  1211. /// <summary>
  1212. /// Utility function to draw strings that contain a hotkey.
  1213. /// </summary>
  1214. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  1215. /// <param name="hotColor">Hot color.</param>
  1216. /// <param name="normalColor">Normal color.</param>
  1217. /// <remarks>
  1218. /// The hotkey is any character following an underscore ('_') character.</remarks>
  1219. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  1220. {
  1221. Driver.SetAttribute (normalColor);
  1222. foreach (var rune in text) {
  1223. if (rune == '_') {
  1224. Driver.SetAttribute (hotColor);
  1225. continue;
  1226. }
  1227. Driver.AddRune (rune);
  1228. Driver.SetAttribute (normalColor);
  1229. }
  1230. }
  1231. /// <summary>
  1232. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1233. /// </summary>
  1234. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  1235. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1236. /// <param name="scheme">The color scheme to use.</param>
  1237. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1238. {
  1239. if (focused)
  1240. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1241. else
  1242. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  1243. }
  1244. /// <summary>
  1245. /// This moves the cursor to the specified column and row in the view.
  1246. /// </summary>
  1247. /// <returns>The move.</returns>
  1248. /// <param name="col">Col.</param>
  1249. /// <param name="row">Row.</param>
  1250. public void Move (int col, int row)
  1251. {
  1252. ViewToScreen (col, row, out var rcol, out var rrow);
  1253. Driver.Move (rcol, rrow);
  1254. }
  1255. /// <summary>
  1256. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1257. /// </summary>
  1258. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1259. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1260. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1261. /// the last focused view. Views should make sure that they place the cursor
  1262. /// in a visually sensible place.
  1263. public virtual void PositionCursor ()
  1264. {
  1265. if (focused != null)
  1266. focused.PositionCursor ();
  1267. else {
  1268. if (CanFocus && HasFocus) {
  1269. Move (viewText.HotKeyPos == -1 ? 1 : viewText.HotKeyPos, 0);
  1270. } else {
  1271. Move (frame.X, frame.Y);
  1272. }
  1273. }
  1274. }
  1275. /// <inheritdoc/>
  1276. public override bool HasFocus {
  1277. get {
  1278. return base.HasFocus;
  1279. }
  1280. internal set {
  1281. if (base.HasFocus != value)
  1282. if (value)
  1283. OnEnter ();
  1284. else
  1285. OnLeave ();
  1286. SetNeedsDisplay ();
  1287. base.HasFocus = value;
  1288. // Remove focus down the chain of subviews if focus is removed
  1289. if (!value && focused != null) {
  1290. focused.OnLeave ();
  1291. focused.HasFocus = false;
  1292. focused = null;
  1293. }
  1294. }
  1295. }
  1296. /// <summary>
  1297. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  1298. /// </summary>
  1299. public class FocusEventArgs : EventArgs {
  1300. /// <summary>
  1301. /// Constructs.
  1302. /// </summary>
  1303. public FocusEventArgs () { }
  1304. /// <summary>
  1305. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  1306. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1307. /// </summary>
  1308. public bool Handled { get; set; }
  1309. }
  1310. /// <inheritdoc/>
  1311. public override bool OnEnter ()
  1312. {
  1313. FocusEventArgs args = new FocusEventArgs ();
  1314. Enter?.Invoke (args);
  1315. if (args.Handled)
  1316. return true;
  1317. if (base.OnEnter ())
  1318. return true;
  1319. return false;
  1320. }
  1321. /// <inheritdoc/>
  1322. public override bool OnLeave ()
  1323. {
  1324. FocusEventArgs args = new FocusEventArgs ();
  1325. Leave?.Invoke (args);
  1326. if (args.Handled)
  1327. return true;
  1328. if (base.OnLeave ())
  1329. return true;
  1330. return false;
  1331. }
  1332. /// <summary>
  1333. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1334. /// </summary>
  1335. /// <value>The focused.</value>
  1336. public View Focused => focused;
  1337. /// <summary>
  1338. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1339. /// </summary>
  1340. /// <value>The most focused.</value>
  1341. public View MostFocused {
  1342. get {
  1343. if (Focused == null)
  1344. return null;
  1345. var most = Focused.MostFocused;
  1346. if (most != null)
  1347. return most;
  1348. return Focused;
  1349. }
  1350. }
  1351. /// <summary>
  1352. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1353. /// color scheme.
  1354. /// </summary>
  1355. public ColorScheme ColorScheme {
  1356. get {
  1357. if (colorScheme == null)
  1358. return SuperView?.ColorScheme;
  1359. return colorScheme;
  1360. }
  1361. set {
  1362. colorScheme = value;
  1363. }
  1364. }
  1365. ColorScheme colorScheme;
  1366. /// <summary>
  1367. /// Displays the specified character in the specified column and row of the View.
  1368. /// </summary>
  1369. /// <param name="col">Column (view-relative).</param>
  1370. /// <param name="row">Row (view-relative).</param>
  1371. /// <param name="ch">Ch.</param>
  1372. public void AddRune (int col, int row, Rune ch)
  1373. {
  1374. if (row < 0 || col < 0)
  1375. return;
  1376. if (row > frame.Height - 1 || col > frame.Width - 1)
  1377. return;
  1378. Move (col, row);
  1379. Driver.AddRune (ch);
  1380. }
  1381. /// <summary>
  1382. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  1383. /// </summary>
  1384. protected void ClearNeedsDisplay ()
  1385. {
  1386. NeedDisplay = Rect.Empty;
  1387. childNeedsDisplay = false;
  1388. }
  1389. /// <summary>
  1390. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1391. /// </summary>
  1392. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1393. /// <remarks>
  1394. /// <para>
  1395. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1396. /// </para>
  1397. /// <para>
  1398. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1399. /// the last color that was set globaly on the driver.
  1400. /// </para>
  1401. /// <para>
  1402. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1403. /// larger than the <c>region</c> parameter.
  1404. /// </para>
  1405. /// </remarks>
  1406. public virtual void Redraw (Rect bounds)
  1407. {
  1408. var clipRect = new Rect (Point.Empty, frame.Size);
  1409. Driver.SetAttribute (HasFocus ? ColorScheme.Focus : ColorScheme.Normal);
  1410. // Draw any Text
  1411. // TODO: Figure out if this should go here or after OnDrawContent
  1412. viewText?.ReFormat ();
  1413. viewText?.Draw (bounds);
  1414. // Invoke DrawContentEvent
  1415. OnDrawContent (bounds);
  1416. if (subviews != null) {
  1417. foreach (var view in subviews) {
  1418. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  1419. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1420. // FIXED: optimize this by computing the intersection of region and view.Bounds
  1421. if (view.layoutNeeded)
  1422. view.LayoutSubviews ();
  1423. Application.CurrentView = view;
  1424. // Draw the subview
  1425. // Use the view's bounds (view-relative; Location will always be (0,0) because
  1426. view.Redraw (view.Bounds);
  1427. }
  1428. view.NeedDisplay = Rect.Empty;
  1429. view.childNeedsDisplay = false;
  1430. }
  1431. }
  1432. }
  1433. ClearNeedsDisplay ();
  1434. }
  1435. /// <summary>
  1436. /// Event invoked when the content area of the View is to be drawn.
  1437. /// </summary>
  1438. /// <remarks>
  1439. /// <para>
  1440. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1441. /// </para>
  1442. /// <para>
  1443. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1444. /// </para>
  1445. /// </remarks>
  1446. public Action<Rect> DrawContent;
  1447. /// <summary>
  1448. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1449. /// </summary>
  1450. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1451. /// <remarks>
  1452. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1453. /// </remarks>
  1454. public virtual void OnDrawContent (Rect viewport)
  1455. {
  1456. DrawContent?.Invoke (viewport);
  1457. }
  1458. /// <summary>
  1459. /// Causes the specified subview to have focus.
  1460. /// </summary>
  1461. /// <param name="view">View.</param>
  1462. public void SetFocus (View view)
  1463. {
  1464. if (view == null)
  1465. return;
  1466. //Console.WriteLine ($"Request to focus {view}");
  1467. if (!view.CanFocus)
  1468. return;
  1469. if (focused == view)
  1470. return;
  1471. // Make sure that this view is a subview
  1472. View c;
  1473. for (c = view.container; c != null; c = c.container)
  1474. if (c == this)
  1475. break;
  1476. if (c == null)
  1477. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1478. if (focused != null)
  1479. focused.HasFocus = false;
  1480. focused = view;
  1481. focused.HasFocus = true;
  1482. focused.EnsureFocus ();
  1483. // Send focus upwards
  1484. SuperView?.SetFocus (this);
  1485. }
  1486. /// <summary>
  1487. /// Defines the event arguments for <see cref="KeyEvent"/>
  1488. /// </summary>
  1489. public class KeyEventEventArgs : EventArgs {
  1490. /// <summary>
  1491. /// Constructs.
  1492. /// </summary>
  1493. /// <param name="ke"></param>
  1494. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1495. /// <summary>
  1496. /// The <see cref="KeyEvent"/> for the event.
  1497. /// </summary>
  1498. public KeyEvent KeyEvent { get; set; }
  1499. /// <summary>
  1500. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1501. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1502. /// </summary>
  1503. public bool Handled { get; set; } = false;
  1504. }
  1505. /// <summary>
  1506. /// Invoked when a character key is pressed and occurs after the key up event.
  1507. /// </summary>
  1508. public Action<KeyEventEventArgs> KeyPress;
  1509. /// <inheritdoc/>
  1510. public override bool ProcessKey (KeyEvent keyEvent)
  1511. {
  1512. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1513. KeyPress?.Invoke (args);
  1514. if (args.Handled)
  1515. return true;
  1516. if (Focused?.ProcessKey (keyEvent) == true)
  1517. return true;
  1518. var c = keyEvent.KeyValue;
  1519. if (c == '\n' || c == ' ' || Rune.ToUpper ((uint)c) == HotKey) {
  1520. Clicked?.Invoke ();
  1521. return true;
  1522. }
  1523. return false;
  1524. }
  1525. /// <inheritdoc/>
  1526. public override bool ProcessHotKey (KeyEvent keyEvent)
  1527. {
  1528. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1529. KeyPress?.Invoke (args);
  1530. if (args.Handled)
  1531. return true;
  1532. if (subviews == null || subviews.Count == 0)
  1533. return false;
  1534. foreach (var view in subviews)
  1535. if (view.SuperView.IsCurrentTop && view.ProcessHotKey (keyEvent))
  1536. return true;
  1537. return false;
  1538. }
  1539. /// <inheritdoc/>
  1540. public override bool ProcessColdKey (KeyEvent keyEvent)
  1541. {
  1542. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1543. KeyPress?.Invoke (args);
  1544. if (args.Handled)
  1545. return true;
  1546. if (subviews == null || subviews.Count == 0)
  1547. return false;
  1548. foreach (var view in subviews)
  1549. if (view.SuperView.IsCurrentTop && view.ProcessColdKey (keyEvent))
  1550. return true;
  1551. return false;
  1552. }
  1553. /// <summary>
  1554. /// Invoked when a key is pressed
  1555. /// </summary>
  1556. public Action<KeyEventEventArgs> KeyDown;
  1557. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1558. public override bool OnKeyDown (KeyEvent keyEvent)
  1559. {
  1560. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1561. KeyDown?.Invoke (args);
  1562. if (args.Handled)
  1563. return true;
  1564. if (subviews == null || subviews.Count == 0)
  1565. return false;
  1566. foreach (var view in subviews)
  1567. if (view.SuperView.IsCurrentTop && view.OnKeyDown (keyEvent))
  1568. return true;
  1569. return false;
  1570. }
  1571. /// <summary>
  1572. /// Invoked when a key is released
  1573. /// </summary>
  1574. public Action<KeyEventEventArgs> KeyUp;
  1575. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1576. public override bool OnKeyUp (KeyEvent keyEvent)
  1577. {
  1578. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1579. KeyUp?.Invoke (args);
  1580. if (args.Handled)
  1581. return true;
  1582. if (subviews == null || subviews.Count == 0)
  1583. return false;
  1584. foreach (var view in subviews)
  1585. if (view.SuperView.IsCurrentTop && view.OnKeyUp (keyEvent))
  1586. return true;
  1587. return false;
  1588. }
  1589. /// <summary>
  1590. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1591. /// </summary>
  1592. public void EnsureFocus ()
  1593. {
  1594. if (focused == null)
  1595. if (FocusDirection == Direction.Forward)
  1596. FocusFirst ();
  1597. else
  1598. FocusLast ();
  1599. }
  1600. /// <summary>
  1601. /// Focuses the first focusable subview if one exists.
  1602. /// </summary>
  1603. public void FocusFirst ()
  1604. {
  1605. if (subviews == null) {
  1606. SuperView?.SetFocus (this);
  1607. return;
  1608. }
  1609. foreach (var view in subviews) {
  1610. if (view.CanFocus) {
  1611. SetFocus (view);
  1612. return;
  1613. }
  1614. }
  1615. }
  1616. /// <summary>
  1617. /// Focuses the last focusable subview if one exists.
  1618. /// </summary>
  1619. public void FocusLast ()
  1620. {
  1621. if (subviews == null) {
  1622. SuperView?.SetFocus (this);
  1623. return;
  1624. }
  1625. for (int i = subviews.Count; i > 0;) {
  1626. i--;
  1627. View v = subviews [i];
  1628. if (v.CanFocus) {
  1629. SetFocus (v);
  1630. return;
  1631. }
  1632. }
  1633. }
  1634. /// <summary>
  1635. /// Focuses the previous view.
  1636. /// </summary>
  1637. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1638. public bool FocusPrev ()
  1639. {
  1640. FocusDirection = Direction.Backward;
  1641. if (subviews == null || subviews.Count == 0)
  1642. return false;
  1643. if (focused == null) {
  1644. FocusLast ();
  1645. return focused != null;
  1646. }
  1647. int focused_idx = -1;
  1648. for (int i = subviews.Count; i > 0;) {
  1649. i--;
  1650. View w = subviews [i];
  1651. if (w.HasFocus) {
  1652. if (w.FocusPrev ())
  1653. return true;
  1654. focused_idx = i;
  1655. continue;
  1656. }
  1657. if (w.CanFocus && focused_idx != -1) {
  1658. focused.HasFocus = false;
  1659. if (w != null && w.CanFocus)
  1660. w.FocusLast ();
  1661. SetFocus (w);
  1662. return true;
  1663. }
  1664. }
  1665. if (focused != null) {
  1666. focused.HasFocus = false;
  1667. focused = null;
  1668. }
  1669. return false;
  1670. }
  1671. /// <summary>
  1672. /// Focuses the next view.
  1673. /// </summary>
  1674. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1675. public bool FocusNext ()
  1676. {
  1677. FocusDirection = Direction.Forward;
  1678. if (subviews == null || subviews.Count == 0)
  1679. return false;
  1680. if (focused == null) {
  1681. FocusFirst ();
  1682. return focused != null;
  1683. }
  1684. int n = subviews.Count;
  1685. int focused_idx = -1;
  1686. for (int i = 0; i < n; i++) {
  1687. View w = subviews [i];
  1688. if (w.HasFocus) {
  1689. if (w.FocusNext ())
  1690. return true;
  1691. focused_idx = i;
  1692. continue;
  1693. }
  1694. if (w.CanFocus && focused_idx != -1) {
  1695. focused.HasFocus = false;
  1696. if (w != null && w.CanFocus)
  1697. w.FocusFirst ();
  1698. SetFocus (w);
  1699. return true;
  1700. }
  1701. }
  1702. if (focused != null) {
  1703. focused.HasFocus = false;
  1704. focused = null;
  1705. }
  1706. return false;
  1707. }
  1708. /// <summary>
  1709. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1710. /// </summary>
  1711. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1712. /// <remarks>
  1713. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1714. /// </remarks>
  1715. internal void SetRelativeLayout (Rect hostFrame)
  1716. {
  1717. int w, h, _x, _y;
  1718. if (x is Pos.PosCenter) {
  1719. if (width == null)
  1720. w = hostFrame.Width;
  1721. else
  1722. w = width.Anchor (hostFrame.Width);
  1723. _x = x.Anchor (hostFrame.Width - w);
  1724. } else {
  1725. if (x == null)
  1726. _x = 0;
  1727. else
  1728. _x = x.Anchor (hostFrame.Width);
  1729. if (width == null)
  1730. w = hostFrame.Width;
  1731. else
  1732. w = width.Anchor (hostFrame.Width - _x);
  1733. }
  1734. if (y is Pos.PosCenter) {
  1735. if (height == null)
  1736. h = hostFrame.Height;
  1737. else
  1738. h = height.Anchor (hostFrame.Height);
  1739. _y = y.Anchor (hostFrame.Height - h);
  1740. } else {
  1741. if (y == null)
  1742. _y = 0;
  1743. else
  1744. _y = y.Anchor (hostFrame.Height);
  1745. if (height == null)
  1746. h = hostFrame.Height;
  1747. else
  1748. h = height.Anchor (hostFrame.Height - _y);
  1749. }
  1750. Frame = new Rect (_x, _y, w, h);
  1751. }
  1752. // https://en.wikipedia.org/wiki/Topological_sorting
  1753. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1754. {
  1755. var result = new List<View> ();
  1756. // Set of all nodes with no incoming edges
  1757. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1758. while (S.Any ()) {
  1759. // remove a node n from S
  1760. var n = S.First ();
  1761. S.Remove (n);
  1762. // add n to tail of L
  1763. if (n != this?.SuperView)
  1764. result.Add (n);
  1765. // for each node m with an edge e from n to m do
  1766. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1767. var m = e.To;
  1768. // remove edge e from the graph
  1769. edges.Remove (e);
  1770. // if m has no other incoming edges then
  1771. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1772. // insert m into S
  1773. S.Add (m);
  1774. }
  1775. }
  1776. }
  1777. if (edges.Any ()) {
  1778. if (!object.ReferenceEquals (edges.First ().From, edges.First ().To)) {
  1779. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1780. } else {
  1781. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1782. }
  1783. } else {
  1784. // return L (a topologically sorted order)
  1785. return result;
  1786. }
  1787. }
  1788. /// <summary>
  1789. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1790. /// </summary>
  1791. public class LayoutEventArgs : EventArgs {
  1792. /// <summary>
  1793. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1794. /// </summary>
  1795. public Rect OldBounds { get; set; }
  1796. }
  1797. /// <summary>
  1798. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1799. /// </summary>
  1800. /// <remarks>
  1801. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1802. /// </remarks>
  1803. public Action<LayoutEventArgs> LayoutComplete;
  1804. /// <summary>
  1805. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> after all sub-views have been laid out.
  1806. /// </summary>
  1807. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1808. {
  1809. LayoutComplete?.Invoke (args);
  1810. }
  1811. /// <summary>
  1812. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1813. /// response to the container view or terminal resizing.
  1814. /// </summary>
  1815. /// <remarks>
  1816. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1817. /// </remarks>
  1818. public virtual void LayoutSubviews ()
  1819. {
  1820. if (!layoutNeeded)
  1821. return;
  1822. viewText.TextSize = Bounds.Size;
  1823. viewText.ReFormat ();
  1824. Rect oldBounds = Bounds;
  1825. // Sort out the dependencies of the X, Y, Width, Height properties
  1826. var nodes = new HashSet<View> ();
  1827. var edges = new HashSet<(View, View)> ();
  1828. foreach (var v in InternalSubviews) {
  1829. nodes.Add (v);
  1830. if (v.LayoutStyle == LayoutStyle.Computed) {
  1831. if (v.X is Pos.PosView vX)
  1832. edges.Add ((vX.Target, v));
  1833. if (v.Y is Pos.PosView vY)
  1834. edges.Add ((vY.Target, v));
  1835. if (v.Width is Dim.DimView vWidth)
  1836. edges.Add ((vWidth.Target, v));
  1837. if (v.Height is Dim.DimView vHeight)
  1838. edges.Add ((vHeight.Target, v));
  1839. }
  1840. }
  1841. var ordered = TopologicalSort (nodes, edges);
  1842. foreach (var v in ordered) {
  1843. if (v.LayoutStyle == LayoutStyle.Computed)
  1844. v.SetRelativeLayout (Frame);
  1845. v.LayoutSubviews ();
  1846. v.layoutNeeded = false;
  1847. }
  1848. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1849. SetRelativeLayout (Frame);
  1850. }
  1851. layoutNeeded = false;
  1852. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1853. }
  1854. /// <summary>
  1855. /// The text displayed by the <see cref="View"/>.
  1856. /// </summary>
  1857. /// <remarks>
  1858. /// The text will only be displayed if the View has no subviews.
  1859. /// </remarks>
  1860. public virtual ustring Text {
  1861. get => viewText.Text;
  1862. set {
  1863. viewText.Text = value;
  1864. SetNeedsDisplay ();
  1865. }
  1866. }
  1867. /// <summary>
  1868. /// Controls the text-alignment property of the View. Changing this property will redisplay the <see cref="View"/>.
  1869. /// </summary>
  1870. /// <value>The text alignment.</value>
  1871. public virtual TextAlignment TextAlignment {
  1872. get => viewText.TextAlignment;
  1873. set {
  1874. viewText.TextAlignment = value;
  1875. SetNeedsDisplay ();
  1876. }
  1877. }
  1878. /// <summary>
  1879. /// The color used for the <see cref="Label"/>.
  1880. /// </summary>
  1881. public virtual Attribute TextColor {
  1882. get => viewText.TextColor;
  1883. set {
  1884. viewText.TextColor = value;
  1885. SetNeedsDisplay ();
  1886. }
  1887. }
  1888. /// <summary>
  1889. /// Pretty prints the View
  1890. /// </summary>
  1891. /// <returns></returns>
  1892. public override string ToString ()
  1893. {
  1894. return $"{GetType ().Name}({Id})({Frame})";
  1895. }
  1896. /// <summary>
  1897. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1898. /// </summary>
  1899. public class MouseEventArgs : EventArgs {
  1900. /// <summary>
  1901. /// Constructs.
  1902. /// </summary>
  1903. /// <param name="me"></param>
  1904. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1905. /// <summary>
  1906. /// The <see cref="MouseEvent"/> for the event.
  1907. /// </summary>
  1908. public MouseEvent MouseEvent { get; set; }
  1909. /// <summary>
  1910. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1911. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1912. /// </summary>
  1913. public bool Handled { get; set; }
  1914. }
  1915. /// <inheritdoc/>
  1916. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1917. {
  1918. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1919. MouseEnter?.Invoke (args);
  1920. if (args.Handled)
  1921. return true;
  1922. if (base.OnMouseEnter (mouseEvent))
  1923. return true;
  1924. return false;
  1925. }
  1926. /// <inheritdoc/>
  1927. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1928. {
  1929. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1930. MouseLeave?.Invoke (args);
  1931. if (args.Handled)
  1932. return true;
  1933. if (base.OnMouseLeave (mouseEvent))
  1934. return true;
  1935. return false;
  1936. }
  1937. /// <summary>
  1938. /// Method invoked when a mouse event is generated
  1939. /// </summary>
  1940. /// <param name="mouseEvent"></param>
  1941. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1942. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1943. {
  1944. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1945. MouseClick?.Invoke (args);
  1946. if (args.Handled)
  1947. return true;
  1948. if (MouseEvent (mouseEvent))
  1949. return true;
  1950. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  1951. if (!HasFocus) {
  1952. SuperView.SetFocus (this);
  1953. SetNeedsDisplay ();
  1954. }
  1955. Clicked?.Invoke ();
  1956. return true;
  1957. }
  1958. return false;
  1959. }
  1960. }
  1961. }