TileView.cs 34 KB

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