TileView.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. using NStack;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Terminal.Gui.Graphs;
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// A <see cref="View"/> consisting of a moveable bar that divides
  9. /// the display area into resizeable <see cref="Tiles"/>.
  10. /// </summary>
  11. public class TileView : View {
  12. TileView parentTileView;
  13. /// <summary>
  14. /// A single <see cref="ContentView"/> presented in a <see cref="TileView"/>. To create
  15. /// new instances use <see cref="TileView.RebuildForTileCount(int)"/>
  16. /// or <see cref="TileView.InsertTile(int)"/>.
  17. /// </summary>
  18. public class Tile {
  19. /// <summary>
  20. /// The <see cref="ContentView"/> that is contained in this <see cref="TileView"/>.
  21. /// Add new child views to this member for multiple
  22. /// <see cref="ContentView"/>s within the <see cref="Tile"/>.
  23. /// </summary>
  24. public View ContentView { get; internal set; }
  25. /// <summary>
  26. /// Gets or Sets the minimum size you to allow when splitter resizing along
  27. /// parent <see cref="TileView.Orientation"/> direction.
  28. /// </summary>
  29. public int MinSize { get; set; }
  30. /// <summary>
  31. /// The text that should be displayed above the <see cref="ContentView"/>. This
  32. /// will appear over the splitter line or border (above the view client area).
  33. /// </summary>
  34. /// <remarks>
  35. /// Title are not rendered for root level tiles
  36. /// <see cref="Border.BorderStyle"/> is <see cref="BorderStyle.None"/>.
  37. ///</remarks>
  38. public string Title {
  39. get => _title;
  40. set {
  41. if (!OnTitleChanging (_title, value)) {
  42. var old = _title;
  43. _title = value;
  44. OnTitleChanged (old, _title);
  45. return;
  46. }
  47. _title = value;
  48. }
  49. }
  50. private string _title = string.Empty;
  51. /// <summary>
  52. /// An <see cref="EventArgs"/> which allows passing a cancelable new <see cref="Title"/> value event.
  53. /// </summary>
  54. public class TitleEventArgs : EventArgs {
  55. /// <summary>
  56. /// The new Window Title.
  57. /// </summary>
  58. public ustring NewTitle { get; set; }
  59. /// <summary>
  60. /// The old Window Title.
  61. /// </summary>
  62. public ustring OldTitle { get; set; }
  63. /// <summary>
  64. /// Flag which allows cancelling the Title change.
  65. /// </summary>
  66. public bool Cancel { get; set; }
  67. /// <summary>
  68. /// Initializes a new instance of <see cref="TitleEventArgs"/>
  69. /// </summary>
  70. /// <param name="oldTitle">The <see cref="Title"/> that is/has been replaced.</param>
  71. /// <param name="newTitle">The new <see cref="Title"/> to be replaced.</param>
  72. public TitleEventArgs (ustring oldTitle, ustring newTitle)
  73. {
  74. OldTitle = oldTitle;
  75. NewTitle = newTitle;
  76. }
  77. }
  78. /// <summary>
  79. /// Called before the <see cref="Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can be cancelled.
  80. /// </summary>
  81. /// <param name="oldTitle">The <see cref="Title"/> that is/has been replaced.</param>
  82. /// <param name="newTitle">The new <see cref="Title"/> to be replaced.</param>
  83. /// <returns><c>true</c> if an event handler cancelled the Title change.</returns>
  84. public virtual bool OnTitleChanging (ustring oldTitle, ustring newTitle)
  85. {
  86. var args = new TitleEventArgs (oldTitle, newTitle);
  87. TitleChanging?.Invoke (args);
  88. return args.Cancel;
  89. }
  90. /// <summary>
  91. /// Event fired when the <see cref="Title"/> is changing. Set <see cref="TitleEventArgs.Cancel"/> to
  92. /// <c>true</c> to cancel the Title change.
  93. /// </summary>
  94. public event Action<TitleEventArgs> TitleChanging;
  95. /// <summary>
  96. /// Called when the <see cref="Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.
  97. /// </summary>
  98. /// <param name="oldTitle">The <see cref="Title"/> that is/has been replaced.</param>
  99. /// <param name="newTitle">The new <see cref="Title"/> to be replaced.</param>
  100. public virtual void OnTitleChanged (ustring oldTitle, ustring newTitle)
  101. {
  102. var args = new TitleEventArgs (oldTitle, newTitle);
  103. TitleChanged?.Invoke (args);
  104. }
  105. /// <summary>
  106. /// Event fired after the <see cref="Title"/> has been changed.
  107. /// </summary>
  108. public event Action<TitleEventArgs> TitleChanged;
  109. /// <summary>
  110. /// Creates a new instance of the <see cref="Tile"/> class.
  111. /// </summary>
  112. public Tile ()
  113. {
  114. ContentView = new View () { Width = Dim.Fill (), Height = Dim.Fill () };
  115. #if DEBUG_IDISPOSABLE
  116. ContentView.Data = "Tile.ContentView";
  117. #endif
  118. Title = string.Empty;
  119. MinSize = 0;
  120. }
  121. }
  122. List<Tile> tiles;
  123. private List<Pos> splitterDistances;
  124. private List<TileViewLineView> splitterLines;
  125. /// <summary>
  126. /// The sub sections hosted by the view
  127. /// </summary>
  128. public IReadOnlyCollection<Tile> Tiles => tiles.AsReadOnly ();
  129. /// <summary>
  130. /// The splitter locations. Note that there will be N-1 splitters where
  131. /// N is the number of <see cref="Tiles"/>.
  132. /// </summary>
  133. public IReadOnlyCollection<Pos> SplitterDistances => splitterDistances.AsReadOnly ();
  134. private Orientation orientation = Orientation.Vertical;
  135. /// <summary>
  136. /// Creates a new instance of the <see cref="TileView"/> class with
  137. /// 2 tiles (i.e. left and right).
  138. /// </summary>
  139. public TileView () : this (2)
  140. {
  141. }
  142. /// <summary>
  143. /// Creates a new instance of the <see cref="TileView"/> class with
  144. /// <paramref name="tiles"/> number of tiles.
  145. /// </summary>
  146. /// <param name="tiles"></param>
  147. public TileView (int tiles)
  148. {
  149. CanFocus = true;
  150. RebuildForTileCount (tiles);
  151. IgnoreBorderPropertyOnRedraw = true;
  152. Border = new Border () {
  153. BorderStyle = BorderStyle.None
  154. };
  155. }
  156. /// <summary>
  157. /// Invoked when any of the <see cref="SplitterDistances"/> is changed.
  158. /// </summary>
  159. public event SplitterEventHandler SplitterMoved;
  160. /// <summary>
  161. /// Raises the <see cref="SplitterMoved"/> event
  162. /// </summary>
  163. protected virtual void OnSplitterMoved (int idx)
  164. {
  165. SplitterMoved?.Invoke (this, new SplitterEventArgs (this, idx, splitterDistances [idx]));
  166. }
  167. /// <summary>
  168. /// Scraps all <see cref="Tiles"/> and creates <paramref name="count"/> new tiles
  169. /// in orientation <see cref="Orientation"/>
  170. /// </summary>
  171. /// <param name="count"></param>
  172. public void RebuildForTileCount (int count)
  173. {
  174. tiles = new List<Tile> ();
  175. splitterDistances = new List<Pos> ();
  176. if (splitterLines != null) {
  177. foreach (var sl in splitterLines) {
  178. sl.Dispose ();
  179. }
  180. }
  181. splitterLines = new List<TileViewLineView> ();
  182. RemoveAll ();
  183. foreach (var tile in tiles) {
  184. tile.ContentView.Dispose ();
  185. tile.ContentView = null;
  186. }
  187. tiles.Clear ();
  188. splitterDistances.Clear ();
  189. if (count == 0) {
  190. return;
  191. }
  192. for (int i = 0; i < count; i++) {
  193. if (i > 0) {
  194. var currentPos = Pos.Percent ((100 / count) * i);
  195. splitterDistances.Add (currentPos);
  196. var line = new TileViewLineView (this, i - 1);
  197. Add (line);
  198. splitterLines.Add (line);
  199. }
  200. var tile = new Tile ();
  201. tiles.Add (tile);
  202. Add (tile.ContentView);
  203. tile.TitleChanged += (e) => SetNeedsDisplay ();
  204. }
  205. LayoutSubviews ();
  206. }
  207. /// <summary>
  208. /// Adds a new <see cref="Tile"/> to the collection at <paramref name="idx"/>.
  209. /// This will also add another splitter line
  210. /// </summary>
  211. /// <param name="idx"></param>
  212. public Tile InsertTile (int idx)
  213. {
  214. var oldTiles = Tiles.ToArray ();
  215. RebuildForTileCount (oldTiles.Length + 1);
  216. Tile toReturn = null;
  217. for (int i = 0; i < tiles.Count; i++) {
  218. if (i != idx) {
  219. var oldTile = oldTiles [i > idx ? i - 1 : i];
  220. // remove the new empty View
  221. Remove (tiles [i].ContentView);
  222. tiles [i].ContentView.Dispose ();
  223. tiles [i].ContentView = null;
  224. // restore old Tile and View
  225. tiles [i] = oldTile;
  226. Add (tiles [i].ContentView);
  227. } else {
  228. toReturn = tiles [i];
  229. }
  230. }
  231. SetNeedsDisplay ();
  232. LayoutSubviews ();
  233. return toReturn;
  234. }
  235. /// <summary>
  236. /// Removes a <see cref="Tiles"/> at the provided <paramref name="idx"/> from
  237. /// the view. Returns the removed tile or null if already empty.
  238. /// </summary>
  239. /// <param name="idx"></param>
  240. /// <returns></returns>
  241. public Tile RemoveTile (int idx)
  242. {
  243. var oldTiles = Tiles.ToArray ();
  244. if (idx < 0 || idx >= oldTiles.Length) {
  245. return null;
  246. }
  247. var removed = Tiles.ElementAt (idx);
  248. RebuildForTileCount (oldTiles.Length - 1);
  249. for (int i = 0; i < tiles.Count; i++) {
  250. int oldIdx = i >= idx ? i + 1 : i;
  251. var oldTile = oldTiles [oldIdx];
  252. // remove the new empty View
  253. Remove (tiles [i].ContentView);
  254. tiles [i].ContentView.Dispose ();
  255. tiles [i].ContentView = null;
  256. // restore old Tile and View
  257. tiles [i] = oldTile;
  258. Add (tiles [i].ContentView);
  259. }
  260. SetNeedsDisplay ();
  261. LayoutSubviews ();
  262. return removed;
  263. }
  264. ///<summary>
  265. /// Returns the index of the first <see cref="Tile"/> in
  266. /// <see cref="Tiles"/> which contains <paramref name="toFind"/>.
  267. ///</summary>
  268. public int IndexOf (View toFind, bool recursive = false)
  269. {
  270. for (int i = 0; i < tiles.Count; i++) {
  271. var v = tiles [i].ContentView;
  272. if (v == toFind) {
  273. return i;
  274. }
  275. if (v.Subviews.Contains (toFind)) {
  276. return i;
  277. }
  278. if (recursive) {
  279. if (RecursiveContains (v.Subviews, toFind)) {
  280. return i;
  281. }
  282. }
  283. }
  284. return -1;
  285. }
  286. private bool RecursiveContains (IEnumerable<View> haystack, View needle)
  287. {
  288. foreach (var v in haystack) {
  289. if (v == needle) {
  290. return true;
  291. }
  292. if (RecursiveContains (v.Subviews, needle)) {
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. /// <summary>
  299. /// Orientation of the dividing line (Horizontal or Vertical).
  300. /// </summary>
  301. public Orientation Orientation {
  302. get { return orientation; }
  303. set {
  304. orientation = value;
  305. LayoutSubviews ();
  306. }
  307. }
  308. /// <inheritdoc/>
  309. public override void LayoutSubviews ()
  310. {
  311. var contentArea = Bounds;
  312. if (HasBorder ()) {
  313. contentArea = new Rect (
  314. contentArea.X + 1,
  315. contentArea.Y + 1,
  316. Math.Max (0, contentArea.Width - 2),
  317. Math.Max (0, contentArea.Height - 2));
  318. }
  319. Setup (contentArea);
  320. base.LayoutSubviews ();
  321. }
  322. /// <summary>
  323. /// <para>Attempts to update the <see cref="splitterDistances"/> of line at <paramref name="idx"/>
  324. /// to the new <paramref name="value"/>. Returns false if the new position is not allowed because of
  325. /// <see cref="Tile.MinSize"/>, location of other splitters etc.
  326. /// </para>
  327. /// <para>Only absolute values (e.g. 10) and percent values (i.e. <see cref="Pos.Percent(float)"/>)
  328. /// are supported for this property.</para>
  329. /// </summary>
  330. public bool SetSplitterPos (int idx, Pos value)
  331. {
  332. if (!(value is Pos.PosAbsolute) && !(value is Pos.PosFactor)) {
  333. throw new ArgumentException ($"Only Percent and Absolute values are supported. Passed value was {value.GetType ().Name}");
  334. }
  335. var fullSpace = orientation == Orientation.Vertical ? Bounds.Width : Bounds.Height;
  336. if (fullSpace != 0 && !IsValidNewSplitterPos (idx, value, fullSpace)) {
  337. return false;
  338. }
  339. splitterDistances [idx] = value;
  340. GetRootTileView ().LayoutSubviews ();
  341. OnSplitterMoved (idx);
  342. return true;
  343. }
  344. /// <inheritdoc/>
  345. public override bool OnEnter (View view)
  346. {
  347. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  348. if (!Tiles.Where (t => t.ContentView.HasFocus).Any ()) {
  349. Tiles.FirstOrDefault ()?.ContentView.SetFocus ();
  350. }
  351. return base.OnEnter (view);
  352. }
  353. /// <inheritdoc/>
  354. public override void Redraw (Rect bounds)
  355. {
  356. Driver.SetAttribute (ColorScheme.Normal);
  357. Clear ();
  358. base.Redraw (bounds);
  359. var lc = new LineCanvas ();
  360. var allLines = GetAllLineViewsRecursively (this);
  361. var allTitlesToRender = GetAllTitlesToRenderRecursively (this);
  362. if (IsRootTileView ()) {
  363. if (HasBorder ()) {
  364. lc.AddLine (new Point (0, 0), bounds.Width - 1, Orientation.Horizontal, Border.BorderStyle);
  365. lc.AddLine (new Point (0, 0), bounds.Height - 1, Orientation.Vertical, Border.BorderStyle);
  366. lc.AddLine (new Point (bounds.Width - 1, bounds.Height - 1), -bounds.Width + 1, Orientation.Horizontal, Border.BorderStyle);
  367. lc.AddLine (new Point (bounds.Width - 1, bounds.Height - 1), -bounds.Height + 1, Orientation.Vertical, Border.BorderStyle);
  368. }
  369. foreach (var line in allLines) {
  370. bool isRoot = splitterLines.Contains (line);
  371. line.ViewToScreen (0, 0, out var x1, out var y1);
  372. var origin = ScreenToView (x1, y1);
  373. var length = line.Orientation == Orientation.Horizontal ?
  374. line.Frame.Width - 1 :
  375. line.Frame.Height - 1;
  376. if (!isRoot) {
  377. if (line.Orientation == Orientation.Horizontal) {
  378. origin.X -= 1;
  379. } else {
  380. origin.Y -= 1;
  381. }
  382. length += 2;
  383. }
  384. lc.AddLine (origin, length, line.Orientation, Border.BorderStyle);
  385. }
  386. }
  387. Driver.SetAttribute (ColorScheme.Normal);
  388. foreach (var p in lc.GenerateImage (bounds)) {
  389. this.AddRune (p.Key.X, p.Key.Y, p.Value);
  390. }
  391. // Redraw the lines so that focus/drag symbol renders
  392. foreach (var line in allLines) {
  393. line.DrawSplitterSymbol ();
  394. }
  395. // Draw Titles over Border
  396. foreach (var titleToRender in allTitlesToRender) {
  397. var renderAt = titleToRender.GetLocalCoordinateForTitle (this);
  398. if (renderAt.Y < 0) {
  399. // If we have no border then root level tiles
  400. // have nowhere to render their titles.
  401. continue;
  402. }
  403. // TODO: Render with focus color if focused
  404. var title = titleToRender.GetTrimmedTitle ();
  405. for (int i = 0; i < title.Length; i++) {
  406. AddRune (renderAt.X + i, renderAt.Y, title [i]);
  407. }
  408. }
  409. }
  410. /// <summary>
  411. /// Converts of <see cref="Tiles"/> element <paramref name="idx"/>
  412. /// from a regular <see cref="View"/> to a new nested <see cref="TileView"/>
  413. /// the specified <paramref name="numberOfPanels"/>.
  414. /// Returns false if the element already contains a nested view.
  415. /// </summary>
  416. /// <remarks>After successful splitting, the old contents will be moved to the
  417. /// <paramref name="result"/> <see cref="TileView"/>'s first tile.</remarks>
  418. /// <param name="idx">The element of <see cref="Tiles"/> that is to be subdivided.</param>
  419. /// <param name="numberOfPanels">The number of panels that the <see cref="Tile"/> should be split into</param>
  420. /// <param name="result">The new nested <see cref="TileView"/>.</param>
  421. /// <returns><see langword="true"/> if a <see cref="View"/> was converted to a new nested
  422. /// <see cref="TileView"/>. <see langword="false"/> if it was already a nested
  423. /// <see cref="TileView"/></returns>
  424. public bool TrySplitTile (int idx, int numberOfPanels, out TileView result)
  425. {
  426. // when splitting a view into 2 sub views we will need to migrate
  427. // the title too
  428. var tile = tiles [idx];
  429. var title = tile.Title;
  430. View toMove = tile.ContentView;
  431. if (toMove is TileView existing) {
  432. result = existing;
  433. return false;
  434. }
  435. var newContainer = new TileView (numberOfPanels) {
  436. Width = Dim.Fill (),
  437. Height = Dim.Fill (),
  438. parentTileView = this,
  439. };
  440. // Take everything out of the View we are moving
  441. var childViews = toMove.Subviews.ToArray ();
  442. toMove.RemoveAll ();
  443. // Remove the view itself and replace it with the new TileView
  444. Remove (toMove);
  445. toMove.Dispose ();
  446. toMove = null;
  447. Add (newContainer);
  448. tile.ContentView = newContainer;
  449. var newTileView1 = newContainer.tiles [0].ContentView;
  450. // Add the original content into the first view of the new container
  451. foreach (var childView in childViews) {
  452. newTileView1.Add (childView);
  453. }
  454. // Move the title across too
  455. newContainer.tiles [0].Title = title;
  456. tile.Title = string.Empty;
  457. result = newContainer;
  458. return true;
  459. }
  460. private bool IsValidNewSplitterPos (int idx, Pos value, int fullSpace)
  461. {
  462. int newSize = value.Anchor (fullSpace);
  463. bool isGettingBigger = newSize > splitterDistances [idx].Anchor (fullSpace);
  464. int lastSplitterOrBorder = HasBorder () ? 1 : 0;
  465. int nextSplitterOrBorder = HasBorder () ? fullSpace - 1 : fullSpace;
  466. // Cannot move off screen right
  467. if (newSize >= fullSpace - (HasBorder () ? 1 : 0)) {
  468. if (isGettingBigger) {
  469. return false;
  470. }
  471. }
  472. // Cannot move off screen left
  473. if (newSize < (HasBorder () ? 1 : 0)) {
  474. if (!isGettingBigger) {
  475. return false;
  476. }
  477. }
  478. // Do not allow splitter to move left of the one before
  479. if (idx > 0) {
  480. int posLeft = splitterDistances [idx - 1].Anchor (fullSpace);
  481. if (newSize <= posLeft) {
  482. return false;
  483. }
  484. lastSplitterOrBorder = posLeft;
  485. }
  486. // Do not allow splitter to move right of the one after
  487. if (idx + 1 < splitterDistances.Count) {
  488. int posRight = splitterDistances [idx + 1].Anchor (fullSpace);
  489. if (newSize >= posRight) {
  490. return false;
  491. }
  492. nextSplitterOrBorder = posRight;
  493. }
  494. if (isGettingBigger) {
  495. var spaceForNext = nextSplitterOrBorder - newSize;
  496. // space required for the last line itself
  497. if (idx > 0) {
  498. spaceForNext--;
  499. }
  500. // don't grow if it would take us below min size of right panel
  501. if (spaceForNext < tiles [idx + 1].MinSize) {
  502. return false;
  503. }
  504. } else {
  505. var spaceForLast = newSize - lastSplitterOrBorder;
  506. // space required for the line itself
  507. if (idx > 0) {
  508. spaceForLast--;
  509. }
  510. // don't shrink if it would take us below min size of left panel
  511. if (spaceForLast < tiles [idx].MinSize) {
  512. return false;
  513. }
  514. }
  515. return true;
  516. }
  517. private List<TileViewLineView> GetAllLineViewsRecursively (View v)
  518. {
  519. var lines = new List<TileViewLineView> ();
  520. foreach (var sub in v.Subviews) {
  521. if (sub is TileViewLineView s) {
  522. if (s.Visible && s.Parent.GetRootTileView () == this) {
  523. lines.Add (s);
  524. }
  525. } else {
  526. if (sub.Visible) {
  527. lines.AddRange (GetAllLineViewsRecursively (sub));
  528. }
  529. }
  530. }
  531. return lines;
  532. }
  533. private List<TileTitleToRender> GetAllTitlesToRenderRecursively (TileView v, int depth = 0)
  534. {
  535. var titles = new List<TileTitleToRender> ();
  536. foreach (var sub in v.Tiles) {
  537. // Don't render titles for invisible stuff!
  538. if (!sub.ContentView.Visible) {
  539. continue;
  540. }
  541. if (sub.ContentView is TileView subTileView) {
  542. // Panels with sub split tiles in them can never
  543. // have their Titles rendered. Instead we dive in
  544. // and pull up their children as titles
  545. titles.AddRange (GetAllTitlesToRenderRecursively (subTileView, depth + 1));
  546. } else {
  547. if (sub.Title.Length > 0) {
  548. titles.Add (new TileTitleToRender (v, sub, depth));
  549. }
  550. }
  551. }
  552. return titles;
  553. }
  554. /// <summary>
  555. /// <para>
  556. /// <see langword="true"/> if <see cref="TileView"/> is nested within a parent <see cref="TileView"/>
  557. /// e.g. via the <see cref="TrySplitTile"/>. <see langword="false"/> if it is a root level <see cref="TileView"/>.
  558. /// </para>
  559. /// </summary>
  560. /// <remarks>Note that manually adding one <see cref="TileView"/> to another will not result in a parent/child
  561. /// relationship and both will still be considered 'root' containers. Always use
  562. /// <see cref="TrySplitTile(int, int, out TileView)"/> if you want to subdivide a <see cref="TileView"/>.</remarks>
  563. /// <returns></returns>
  564. public bool IsRootTileView ()
  565. {
  566. return parentTileView == null;
  567. }
  568. /// <summary>
  569. /// Returns the immediate parent <see cref="TileView"/> of this. Note that in case
  570. /// of deep nesting this might not be the root <see cref="TileView"/>. Returns null
  571. /// if this instance is not a nested child (created with
  572. /// <see cref="TrySplitTile(int, int, out TileView)"/>)
  573. /// </summary>
  574. /// <remarks>
  575. /// Use <see cref="IsRootTileView"/> to determine if the returned value is the root.
  576. /// </remarks>
  577. /// <returns></returns>
  578. public TileView GetParentTileView ()
  579. {
  580. return this.parentTileView;
  581. }
  582. private TileView GetRootTileView ()
  583. {
  584. TileView root = this;
  585. while (root.parentTileView != null) {
  586. root = root.parentTileView;
  587. }
  588. return root;
  589. }
  590. private void Setup (Rect bounds)
  591. {
  592. if (bounds.IsEmpty || bounds.Height <= 0 || bounds.Width <= 0) {
  593. return;
  594. }
  595. for (int i = 0; i < splitterLines.Count; i++) {
  596. var line = splitterLines [i];
  597. line.Orientation = Orientation;
  598. line.Width = orientation == Orientation.Vertical
  599. ? 1 : Dim.Fill ();
  600. line.Height = orientation == Orientation.Vertical
  601. ? Dim.Fill () : 1;
  602. line.LineRune = orientation == Orientation.Vertical ?
  603. Driver.VLine : Driver.HLine;
  604. if (orientation == Orientation.Vertical) {
  605. line.X = splitterDistances [i];
  606. line.Y = 0;
  607. } else {
  608. line.Y = splitterDistances [i];
  609. line.X = 0;
  610. }
  611. }
  612. HideSplittersBasedOnTileVisibility ();
  613. var visibleTiles = tiles.Where (t => t.ContentView.Visible).ToArray ();
  614. var visibleSplitterLines = splitterLines.Where (l => l.Visible).ToArray ();
  615. for (int i = 0; i < visibleTiles.Length; i++) {
  616. var tile = visibleTiles [i];
  617. if (Orientation == Orientation.Vertical) {
  618. tile.ContentView.X = i == 0 ? bounds.X : Pos.Right (visibleSplitterLines [i - 1]);
  619. tile.ContentView.Y = bounds.Y;
  620. tile.ContentView.Height = bounds.Height;
  621. tile.ContentView.Width = GetTileWidthOrHeight (i, Bounds.Width, visibleTiles, visibleSplitterLines);
  622. } else {
  623. tile.ContentView.X = bounds.X;
  624. tile.ContentView.Y = i == 0 ? 0 : Pos.Bottom (visibleSplitterLines [i - 1]);
  625. tile.ContentView.Width = bounds.Width;
  626. tile.ContentView.Height = GetTileWidthOrHeight (i, Bounds.Height, visibleTiles, visibleSplitterLines);
  627. }
  628. }
  629. }
  630. private void HideSplittersBasedOnTileVisibility ()
  631. {
  632. if (splitterLines.Count == 0) {
  633. return;
  634. }
  635. foreach (var line in splitterLines) {
  636. line.Visible = true;
  637. }
  638. for (int i = 0; i < tiles.Count; i++) {
  639. if (!tiles [i].ContentView.Visible) {
  640. // when a tile is not visible, prefer hiding
  641. // the splitter on it's left
  642. var candidate = splitterLines [Math.Max (0, i - 1)];
  643. // unless that splitter is already hidden
  644. // e.g. when hiding panels 0 and 1 of a 3 panel
  645. // container
  646. if (candidate.Visible) {
  647. candidate.Visible = false;
  648. } else {
  649. splitterLines [Math.Min (i, splitterLines.Count - 1)].Visible = false;
  650. }
  651. }
  652. }
  653. }
  654. private Dim GetTileWidthOrHeight (int i, int space, Tile [] visibleTiles, TileViewLineView [] visibleSplitterLines)
  655. {
  656. // last tile
  657. if (i + 1 >= visibleTiles.Length) {
  658. return Dim.Fill (HasBorder () ? 1 : 0);
  659. }
  660. var nextSplitter = visibleSplitterLines [i];
  661. var nextSplitterPos = Orientation == Orientation.Vertical ?
  662. nextSplitter.X : nextSplitter.Y;
  663. var nextSplitterDistance = nextSplitterPos.Anchor (space);
  664. var lastSplitter = i >= 1 ? visibleSplitterLines [i - 1] : null;
  665. var lastSplitterPos = Orientation == Orientation.Vertical ?
  666. lastSplitter?.X : lastSplitter?.Y;
  667. var lastSplitterDistance = lastSplitterPos?.Anchor (space) ?? 0;
  668. var distance = nextSplitterDistance - lastSplitterDistance;
  669. if (i > 0) {
  670. return distance - 1;
  671. }
  672. return distance - (HasBorder () ? 1 : 0);
  673. }
  674. private class TileTitleToRender {
  675. public TileView Parent { get; }
  676. public Tile Tile { get; }
  677. public int Depth { get; }
  678. public TileTitleToRender (TileView parent, Tile tile, int depth)
  679. {
  680. Parent = parent;
  681. Tile = tile;
  682. Depth = depth;
  683. }
  684. /// <summary>
  685. /// Translates the <see cref="Tile"/> title location from its local
  686. /// coordinate space <paramref name="intoCoordinateSpace"/>.
  687. /// </summary>
  688. public Point GetLocalCoordinateForTitle (TileView intoCoordinateSpace)
  689. {
  690. Tile.ContentView.ViewToScreen (0, 0, out var screenCol, out var screenRow);
  691. screenRow--;
  692. return intoCoordinateSpace.ScreenToView (screenCol, screenRow);
  693. }
  694. internal string GetTrimmedTitle ()
  695. {
  696. Dim spaceDim = Tile.ContentView.Width;
  697. var spaceAbs = spaceDim.Anchor (Parent.Bounds.Width);
  698. var title = $" {Tile.Title} ";
  699. if (title.Length > spaceAbs) {
  700. return title.Substring (0, spaceAbs);
  701. }
  702. return title;
  703. }
  704. }
  705. private class TileViewLineView : LineView {
  706. public TileView Parent { get; private set; }
  707. public int Idx { get; }
  708. Point? dragPosition;
  709. Pos dragOrignalPos;
  710. public Point? moveRuneRenderLocation;
  711. public TileViewLineView (TileView parent, int idx)
  712. {
  713. CanFocus = true;
  714. TabStop = true;
  715. this.Parent = parent;
  716. Idx = idx;
  717. base.AddCommand (Command.Right, () => {
  718. return MoveSplitter (1, 0);
  719. });
  720. base.AddCommand (Command.Left, () => {
  721. return MoveSplitter (-1, 0);
  722. });
  723. base.AddCommand (Command.LineUp, () => {
  724. return MoveSplitter (0, -1);
  725. });
  726. base.AddCommand (Command.LineDown, () => {
  727. return MoveSplitter (0, 1);
  728. });
  729. AddKeyBinding (Key.CursorRight, Command.Right);
  730. AddKeyBinding (Key.CursorLeft, Command.Left);
  731. AddKeyBinding (Key.CursorUp, Command.LineUp);
  732. AddKeyBinding (Key.CursorDown, Command.LineDown);
  733. }
  734. public override bool ProcessKey (KeyEvent kb)
  735. {
  736. if (!CanFocus || !HasFocus) {
  737. return base.ProcessKey (kb);
  738. }
  739. var result = InvokeKeybindings (kb);
  740. if (result != null)
  741. return (bool)result;
  742. return base.ProcessKey (kb);
  743. }
  744. public override void PositionCursor ()
  745. {
  746. base.PositionCursor ();
  747. var location = moveRuneRenderLocation ??
  748. new Point (Bounds.Width / 2, Bounds.Height / 2);
  749. Move (location.X, location.Y);
  750. }
  751. public override bool OnEnter (View view)
  752. {
  753. Driver.SetCursorVisibility (CursorVisibility.Default);
  754. PositionCursor ();
  755. return base.OnEnter (view);
  756. }
  757. public override void Redraw (Rect bounds)
  758. {
  759. base.Redraw (bounds);
  760. DrawSplitterSymbol ();
  761. }
  762. public void DrawSplitterSymbol ()
  763. {
  764. if (CanFocus && HasFocus) {
  765. var location = moveRuneRenderLocation ??
  766. new Point (Bounds.Width / 2, Bounds.Height / 2);
  767. AddRune (location.X, location.Y, Driver.Diamond);
  768. }
  769. }
  770. public override bool MouseEvent (MouseEvent mouseEvent)
  771. {
  772. if (!CanFocus) {
  773. return true;
  774. }
  775. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed)) {
  776. // Start a Drag
  777. SetFocus ();
  778. Application.EnsuresTopOnFront ();
  779. if (mouseEvent.Flags == MouseFlags.Button1Pressed) {
  780. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  781. dragOrignalPos = Orientation == Orientation.Horizontal ? Y : X;
  782. Application.GrabMouse (this);
  783. if (Orientation == Orientation.Horizontal) {
  784. } else {
  785. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  786. }
  787. }
  788. return true;
  789. } else if (
  790. dragPosition.HasValue &&
  791. (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  792. // Continue Drag
  793. // how far has user dragged from original location?
  794. if (Orientation == Orientation.Horizontal) {
  795. int dy = mouseEvent.Y - dragPosition.Value.Y;
  796. Parent.SetSplitterPos (Idx, Offset (Y, dy));
  797. moveRuneRenderLocation = new Point (mouseEvent.X, 0);
  798. } else {
  799. int dx = mouseEvent.X - dragPosition.Value.X;
  800. Parent.SetSplitterPos (Idx, Offset (X, dx));
  801. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  802. }
  803. Parent.SetNeedsDisplay ();
  804. return true;
  805. }
  806. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  807. // End Drag
  808. Application.UngrabMouse ();
  809. Driver.UncookMouse ();
  810. FinalisePosition (
  811. dragOrignalPos,
  812. Orientation == Orientation.Horizontal ? Y : X);
  813. dragPosition = null;
  814. moveRuneRenderLocation = null;
  815. }
  816. return false;
  817. }
  818. private bool MoveSplitter (int distanceX, int distanceY)
  819. {
  820. if (Orientation == Orientation.Vertical) {
  821. // Cannot move in this direction
  822. if (distanceX == 0) {
  823. return false;
  824. }
  825. var oldX = X;
  826. return FinalisePosition (oldX, Offset (X, distanceX));
  827. } else {
  828. // Cannot move in this direction
  829. if (distanceY == 0) {
  830. return false;
  831. }
  832. var oldY = Y;
  833. return FinalisePosition (oldY, (Pos)Offset (Y, distanceY));
  834. }
  835. }
  836. private Pos Offset (Pos pos, int delta)
  837. {
  838. var posAbsolute = pos.Anchor (Orientation == Orientation.Horizontal ?
  839. Parent.Bounds.Height : Parent.Bounds.Width);
  840. return posAbsolute + delta;
  841. }
  842. /// <summary>
  843. /// <para>
  844. /// Moves <see cref="Parent"/> <see cref="TileView.SplitterDistances"/> to
  845. /// <see cref="Pos"/> <paramref name="newValue"/> preserving <see cref="Pos"/> format
  846. /// (absolute / relative) that <paramref name="oldValue"/> had.
  847. /// </para>
  848. /// <remarks>This ensures that if splitter location was e.g. 50% before and you move it
  849. /// to absolute 5 then you end up with 10% (assuming a parent had 50 width). </remarks>
  850. /// </summary>
  851. /// <param name="oldValue"></param>
  852. /// <param name="newValue"></param>
  853. private bool FinalisePosition (Pos oldValue, Pos newValue)
  854. {
  855. if (oldValue is Pos.PosFactor) {
  856. if (Orientation == Orientation.Horizontal) {
  857. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Height));
  858. } else {
  859. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Width));
  860. }
  861. } else {
  862. return Parent.SetSplitterPos (Idx, newValue);
  863. }
  864. }
  865. /// <summary>
  866. /// <para>
  867. /// Determines the absolute position of <paramref name="p"/> and
  868. /// returns a <see cref="Pos.PosFactor"/> that describes the percentage of that.
  869. /// </para>
  870. /// <para>Effectively turning any <see cref="Pos"/> into a <see cref="Pos.PosFactor"/>
  871. /// (as if created with <see cref="Pos.Percent(float)"/>)</para>
  872. /// </summary>
  873. /// <param name="p">The <see cref="Pos"/> to convert to <see cref="Pos.Percent(float)"/></param>
  874. /// <param name="parentLength">The Height/Width that <paramref name="p"/> lies within</param>
  875. /// <returns></returns>
  876. private Pos ConvertToPosFactor (Pos p, int parentLength)
  877. {
  878. // calculate position in the 'middle' of the cell at p distance along parentLength
  879. float position = p.Anchor (parentLength) + 0.5f;
  880. return new Pos.PosFactor (position / parentLength);
  881. }
  882. }
  883. private bool HasBorder ()
  884. {
  885. return Border?.BorderStyle != BorderStyle.None;
  886. }
  887. /// <inheritdoc/>
  888. protected override void Dispose (bool disposing)
  889. {
  890. foreach (var tile in Tiles) {
  891. Remove (tile.ContentView);
  892. tile.ContentView.Dispose ();
  893. }
  894. base.Dispose (disposing);
  895. }
  896. }
  897. /// <summary>
  898. /// Provides data for <see cref="TileView"/> events.
  899. /// </summary>
  900. public class SplitterEventArgs : EventArgs {
  901. /// <summary>
  902. /// Creates a new instance of the <see cref="SplitterEventArgs"/> class.
  903. /// </summary>
  904. /// <param name="tileView"><see cref="TileView"/> in which splitter is being moved.</param>
  905. /// <param name="idx">Index of the splitter being moved in <see cref="TileView.SplitterDistances"/>.</param>
  906. /// <param name="splitterDistance">The new <see cref="Pos"/> of the splitter line.</param>
  907. public SplitterEventArgs (TileView tileView, int idx, Pos splitterDistance)
  908. {
  909. SplitterDistance = splitterDistance;
  910. TileView = tileView;
  911. Idx = idx;
  912. }
  913. /// <summary>
  914. /// New position of the splitter line (see <see cref="TileView.SplitterDistances"/>).
  915. /// </summary>
  916. public Pos SplitterDistance { get; }
  917. /// <summary>
  918. /// Container (sender) of the event.
  919. /// </summary>
  920. public TileView TileView { get; }
  921. /// <summary>
  922. /// Gets the index of the splitter that is being moved. This can be
  923. /// used to index <see cref="TileView.SplitterDistances"/>
  924. /// </summary>
  925. public int Idx { get; }
  926. }
  927. /// <summary>
  928. /// Represents a method that will handle splitter events.
  929. /// </summary>
  930. public delegate void SplitterEventHandler (object sender, SplitterEventArgs e);
  931. }