TileView.cs 34 KB

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