TileView.cs 34 KB

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