TileView.cs 34 KB

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