TileView.cs 28 KB

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