TileView.cs 34 KB

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