TileView.cs 35 KB

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