TileView.cs 35 KB

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