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