TileView.cs 34 KB

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