TileView.cs 34 KB

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