TileView.cs 34 KB

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