TileView.cs 34 KB

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