TileView.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. #nullable enable
  2. namespace Terminal.Gui.Views;
  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. /// <summary>Overridden so no Frames get drawn</summary>
  146. /// <returns></returns>
  147. protected override bool OnDrawingAdornments () { return true; }
  148. /// <inheritdoc/>
  149. protected override bool OnRenderingLineCanvas () { return false; }
  150. /// <inheritdoc/>
  151. protected override void OnDrawComplete (DrawContext? context)
  152. {
  153. SetAttributeForRole (Enabled ? VisualRole.Normal : VisualRole.Disabled);
  154. var lc = new LineCanvas ();
  155. List<TileViewLineView> allLines = GetAllLineViewsRecursively (this);
  156. List<TileTitleToRender> allTitlesToRender = GetAllTitlesToRenderRecursively (this);
  157. if (IsRootTileView ())
  158. {
  159. if (HasBorder ())
  160. {
  161. lc.AddLine (Point.Empty, Viewport.Width, Orientation.Horizontal, LineStyle);
  162. lc.AddLine (Point.Empty, Viewport.Height, Orientation.Vertical, LineStyle);
  163. lc.AddLine (
  164. new (Viewport.Width - 1, Viewport.Height - 1),
  165. -Viewport.Width,
  166. Orientation.Horizontal,
  167. LineStyle
  168. );
  169. lc.AddLine (
  170. new (Viewport.Width - 1, Viewport.Height - 1),
  171. -Viewport.Height,
  172. Orientation.Vertical,
  173. LineStyle
  174. );
  175. }
  176. foreach (TileViewLineView line in allLines)
  177. {
  178. bool isRoot = _splitterLines!.Contains (line);
  179. Rectangle screen = line.ViewportToScreen (Rectangle.Empty);
  180. Point origin = ScreenToFrame (screen.Location);
  181. int length = line.Orientation == Orientation.Horizontal ? line.Frame.Width : line.Frame.Height;
  182. if (!isRoot)
  183. {
  184. if (line.Orientation == Orientation.Horizontal)
  185. {
  186. origin.X -= 1;
  187. }
  188. else
  189. {
  190. origin.Y -= 1;
  191. }
  192. length += 2;
  193. }
  194. lc.AddLine (origin, length, line.Orientation, LineStyle);
  195. }
  196. }
  197. SetAttributeForRole (Enabled ? VisualRole.Normal : VisualRole.Disabled);
  198. foreach (KeyValuePair<Point, Rune> p in lc.GetMap (Viewport))
  199. {
  200. AddRune (p.Key.X, p.Key.Y, p.Value);
  201. }
  202. // Redraw the lines so that focus/drag symbol renders
  203. foreach (TileViewLineView line in allLines)
  204. {
  205. line.DrawSplitterSymbol ();
  206. }
  207. // Draw Titles over Border
  208. foreach (TileTitleToRender titleToRender in allTitlesToRender)
  209. {
  210. Point renderAt = titleToRender.GetLocalCoordinateForTitle (this);
  211. if (renderAt.Y < 0)
  212. {
  213. // If we have no border then root level tiles
  214. // have nowhere to render their titles.
  215. continue;
  216. }
  217. // TODO: Render with focus color if focused
  218. string title = titleToRender.GetTrimmedTitle ();
  219. for (var i = 0; i < title.Length; i++)
  220. {
  221. AddRune (renderAt.X + i, renderAt.Y, (Rune)title [i]);
  222. }
  223. }
  224. return;
  225. }
  226. //// BUGBUG: Why is this not handled by a key binding???
  227. /// <inheritdoc/>
  228. protected override bool OnKeyDownNotHandled (Key key)
  229. {
  230. var focusMoved = false;
  231. if (key.KeyCode == ToggleResizable)
  232. {
  233. foreach (TileViewLineView l in _splitterLines!)
  234. {
  235. bool iniBefore = l.IsInitialized;
  236. l.IsInitialized = false;
  237. l.CanFocus = !l.CanFocus;
  238. l.IsInitialized = iniBefore;
  239. if (l.CanFocus && !focusMoved)
  240. {
  241. l.SetFocus ();
  242. focusMoved = true;
  243. }
  244. }
  245. return true;
  246. }
  247. return false;
  248. }
  249. /// <summary>
  250. /// Scraps all <see cref="Tiles"/> and creates <paramref name="count"/> new tiles in orientation
  251. /// <see cref="Orientation"/>
  252. /// </summary>
  253. /// <param name="count"></param>
  254. public void RebuildForTileCount (int count)
  255. {
  256. _tiles = new ();
  257. _splitterDistances = new ();
  258. if (_splitterLines is { })
  259. {
  260. foreach (TileViewLineView sl in _splitterLines)
  261. {
  262. sl.Dispose ();
  263. }
  264. }
  265. _splitterLines = new ();
  266. RemoveAll ();
  267. foreach (Tile tile in _tiles)
  268. {
  269. tile.ContentView?.Dispose ();
  270. tile.ContentView = null;
  271. }
  272. _tiles.Clear ();
  273. _splitterDistances.Clear ();
  274. if (count == 0)
  275. {
  276. return;
  277. }
  278. for (var i = 0; i < count; i++)
  279. {
  280. if (i > 0)
  281. {
  282. Pos currentPos = Pos.Percent (100 / count * i);
  283. _splitterDistances.Add (currentPos);
  284. var line = new TileViewLineView (this, i - 1);
  285. Add (line);
  286. _splitterLines.Add (line);
  287. }
  288. var tile = new Tile ();
  289. _tiles.Add (tile);
  290. tile.ContentView!.Id = $"Tile.ContentView {i}";
  291. Add (tile.ContentView);
  292. // BUGBUG: This should not be needed:
  293. tile.TitleChanged += (s, e) => SetNeedsLayout ();
  294. }
  295. SetNeedsLayout ();
  296. }
  297. /// <summary>
  298. /// Removes a <see cref="Tiles"/> at the provided <paramref name="idx"/> from the view. Returns the removed tile
  299. /// or null if already empty.
  300. /// </summary>
  301. /// <param name="idx"></param>
  302. /// <returns></returns>
  303. public Tile? RemoveTile (int idx)
  304. {
  305. Tile [] oldTiles = Tiles.ToArray ();
  306. if (idx < 0 || idx >= oldTiles.Length)
  307. {
  308. return null;
  309. }
  310. Tile removed = Tiles.ElementAt (idx);
  311. RebuildForTileCount (oldTiles.Length - 1);
  312. for (var i = 0; i < _tiles?.Count; i++)
  313. {
  314. int oldIdx = i >= idx ? i + 1 : i;
  315. Tile oldTile = oldTiles [oldIdx];
  316. // remove the new empty View
  317. Remove (_tiles [i].ContentView);
  318. _tiles [i].ContentView?.Dispose ();
  319. _tiles [i].ContentView = null;
  320. // restore old Tile and View
  321. _tiles [i] = oldTile;
  322. Add (_tiles [i].ContentView);
  323. }
  324. return removed;
  325. }
  326. /// <summary>
  327. /// <para>
  328. /// Attempts to update the <see cref="SplitterDistances"/> of line at <paramref name="idx"/> to the new
  329. /// <paramref name="value"/>. Returns false if the new position is not allowed because of
  330. /// <see cref="Tile.MinSize"/>, location of other splitters etc.
  331. /// </para>
  332. /// <para>
  333. /// Only absolute values (e.g. 10) and percent values (i.e. <see cref="Pos.Percent(int)"/>) are supported for
  334. /// this property.
  335. /// </para>
  336. /// </summary>
  337. public bool SetSplitterPos (int idx, Pos value)
  338. {
  339. if (!(value is PosAbsolute) && !(value is PosPercent))
  340. {
  341. throw new ArgumentException (
  342. $"Only Percent and Absolute values are supported. Passed value was {value.GetType ().Name}"
  343. );
  344. }
  345. int fullSpace = _orientation == Orientation.Vertical ? Viewport.Width : Viewport.Height;
  346. if (fullSpace != 0 && !IsValidNewSplitterPos (idx, value, fullSpace))
  347. {
  348. return false;
  349. }
  350. if (_splitterDistances is { })
  351. {
  352. _splitterDistances [idx] = value;
  353. }
  354. OnSplitterMoved (idx);
  355. SetNeedsDraw ();
  356. SetNeedsLayout ();
  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 (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 (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.GetAnchor (space);
  494. TileViewLineView? lastSplitter = i >= 1 ? visibleSplitterLines [i - 1] : null;
  495. Pos? lastSplitterPos = Orientation == Orientation.Vertical ? lastSplitter?.X : lastSplitter?.Y;
  496. int lastSplitterDistance = lastSplitterPos?.GetAnchor (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 is { 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.GetAnchor (fullSpace);
  539. bool isGettingBigger = newSize > _splitterDistances! [idx].GetAnchor (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].GetAnchor (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].GetAnchor (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. // BUGBUG: This should not be needed. If any of the pos/dim setters above actually changed values, NeedsDisplay should have already been set.
  672. tile.ContentView.SetNeedsDraw ();
  673. }
  674. }
  675. private class TileTitleToRender
  676. {
  677. public TileTitleToRender (TileView? parent, Tile tile, int depth)
  678. {
  679. Parent = parent;
  680. Tile = tile;
  681. Depth = depth;
  682. }
  683. public int Depth { get; }
  684. public TileView? Parent { get; }
  685. public Tile? Tile { get; }
  686. /// <summary>
  687. /// Translates the <see cref="Tile"/> title location from its local coordinate space
  688. /// <paramref name="intoCoordinateSpace"/>.
  689. /// </summary>
  690. public Point GetLocalCoordinateForTitle (TileView intoCoordinateSpace)
  691. {
  692. Rectangle screen = Tile!.ContentView!.ViewportToScreen (Rectangle.Empty);
  693. return intoCoordinateSpace.ScreenToFrame (new (screen.X, screen.Y - 1));
  694. }
  695. internal string GetTrimmedTitle ()
  696. {
  697. Dim? spaceDim = Tile?.ContentView?.Width;
  698. int spaceAbs = spaceDim!.GetAnchor (Parent!.Viewport.Width);
  699. var title = $" {Tile!.Title} ";
  700. if (title.Length > spaceAbs)
  701. {
  702. return title!.Substring (0, spaceAbs);
  703. }
  704. return title;
  705. }
  706. }
  707. private class TileViewLineView : LineView
  708. {
  709. public Point? moveRuneRenderLocation;
  710. private Pos? dragOrignalPos;
  711. private Point? dragPosition;
  712. public TileViewLineView (TileView parent, int idx)
  713. {
  714. CanFocus = false;
  715. TabStop = TabBehavior.TabStop;
  716. Parent = parent;
  717. Idx = idx;
  718. AddCommand (Command.Right, () => MoveSplitter (1, 0));
  719. AddCommand (Command.Left, () => MoveSplitter (-1, 0));
  720. AddCommand (Command.Up, () => MoveSplitter (0, -1));
  721. AddCommand (Command.Down, () => MoveSplitter (0, 1));
  722. KeyBindings.Add (Key.CursorRight, Command.Right);
  723. KeyBindings.Add (Key.CursorLeft, Command.Left);
  724. KeyBindings.Add (Key.CursorUp, Command.Up);
  725. KeyBindings.Add (Key.CursorDown, Command.Down);
  726. }
  727. public int Idx { get; }
  728. public TileView Parent { get; }
  729. public void DrawSplitterSymbol ()
  730. {
  731. if (dragPosition is { } || CanFocus)
  732. {
  733. Point location = moveRuneRenderLocation ?? new Point (Viewport.Width / 2, Viewport.Height / 2);
  734. AddRune (location.X, location.Y, Glyphs.Diamond);
  735. }
  736. }
  737. protected override bool OnMouseEvent (MouseEventArgs mouseEvent)
  738. {
  739. if (!dragPosition.HasValue && mouseEvent.Flags == MouseFlags.Button1Pressed)
  740. {
  741. // Start a Drag
  742. SetFocus ();
  743. if (mouseEvent.Flags == MouseFlags.Button1Pressed)
  744. {
  745. dragPosition = mouseEvent.Position;
  746. dragOrignalPos = Orientation == Orientation.Horizontal ? Y : X;
  747. Application.MouseGrabHandler.GrabMouse (this);
  748. if (Orientation == Orientation.Horizontal)
  749. { }
  750. else
  751. {
  752. moveRuneRenderLocation = new Point (
  753. 0,
  754. Math.Max (1, Math.Min (Viewport.Height - 2, mouseEvent.Position.Y))
  755. );
  756. }
  757. }
  758. return true;
  759. }
  760. if (
  761. dragPosition.HasValue && mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  762. {
  763. // Continue Drag
  764. // how far has user dragged from original location?
  765. if (Orientation == Orientation.Horizontal)
  766. {
  767. int dy = mouseEvent.Position.Y - dragPosition.Value.Y;
  768. Parent.SetSplitterPos (Idx, Offset (Y, dy));
  769. moveRuneRenderLocation = new Point (mouseEvent.Position.X, 0);
  770. }
  771. else
  772. {
  773. int dx = mouseEvent.Position.X - dragPosition.Value.X;
  774. Parent.SetSplitterPos (Idx, Offset (X, dx));
  775. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Viewport.Height - 2, mouseEvent.Position.Y)));
  776. }
  777. Parent.SetNeedsLayout ();
  778. return true;
  779. }
  780. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue)
  781. {
  782. // End Drag
  783. Application.MouseGrabHandler.UngrabMouse ();
  784. //Driver.UncookMouse ();
  785. FinalisePosition (
  786. dragOrignalPos!,
  787. Orientation == Orientation.Horizontal ? Y : X
  788. );
  789. dragPosition = null;
  790. moveRuneRenderLocation = null;
  791. }
  792. return false;
  793. }
  794. /// <inheritdoc/>
  795. protected override bool OnClearingViewport () { return true; }
  796. protected override bool OnDrawingContent ()
  797. {
  798. DrawSplitterSymbol ();
  799. return true;
  800. }
  801. public override Point? PositionCursor ()
  802. {
  803. base.PositionCursor ();
  804. Point location = moveRuneRenderLocation ?? new Point (Viewport.Width / 2, Viewport.Height / 2);
  805. Move (location.X, location.Y);
  806. return null; // Hide cursor
  807. }
  808. /// <summary>
  809. /// <para>
  810. /// Determines the absolute position of <paramref name="p"/> and returns a <see cref="PosPercent"/> that
  811. /// describes the percentage of that.
  812. /// </para>
  813. /// <para>
  814. /// Effectively turning any <see cref="Pos"/> into a <see cref="PosPercent"/> (as if created with
  815. /// <see cref="Pos.Percent(int)"/>)
  816. /// </para>
  817. /// </summary>
  818. /// <param name="p">The <see cref="Pos"/> to convert to <see cref="Pos.Percent(int)"/></param>
  819. /// <param name="parentLength">The Height/Width that <paramref name="p"/> lies within</param>
  820. /// <returns></returns>
  821. private Pos ConvertToPosPercent (Pos p, int parentLength)
  822. {
  823. // Calculate position in the 'middle' of the cell at p distance along parentLength
  824. float position = p.GetAnchor (parentLength) + 0.5f;
  825. // Calculate the percentage
  826. var percent = (int)Math.Round (position / parentLength * 100);
  827. // Return a new PosPercent object
  828. return Pos.Percent (percent);
  829. }
  830. /// <summary>
  831. /// <para>
  832. /// Moves <see cref="Parent"/> <see cref="TileView.SplitterDistances"/> to <see cref="Pos"/>
  833. /// <paramref name="newValue"/> preserving <see cref="Pos"/> format (absolute / relative) that
  834. /// <paramref name="oldValue"/> had.
  835. /// </para>
  836. /// <remarks>
  837. /// This ensures that if splitter location was e.g. 50% before and you move it to absolute 5 then you end up
  838. /// with 10% (assuming a parent had 50 width).
  839. /// </remarks>
  840. /// </summary>
  841. /// <param name="oldValue"></param>
  842. /// <param name="newValue"></param>
  843. private bool FinalisePosition (Pos oldValue, Pos newValue)
  844. {
  845. SetNeedsDraw ();
  846. SetNeedsLayout ();
  847. if (oldValue is PosPercent)
  848. {
  849. if (Orientation == Orientation.Horizontal)
  850. {
  851. return Parent.SetSplitterPos (Idx, ConvertToPosPercent (newValue, Parent.Viewport.Height));
  852. }
  853. return Parent.SetSplitterPos (Idx, ConvertToPosPercent (newValue, Parent.Viewport.Width));
  854. }
  855. return Parent.SetSplitterPos (Idx, newValue);
  856. }
  857. private bool MoveSplitter (int distanceX, int distanceY)
  858. {
  859. if (Orientation == Orientation.Vertical)
  860. {
  861. // Cannot move in this direction
  862. if (distanceX == 0)
  863. {
  864. return false;
  865. }
  866. Pos oldX = X;
  867. return FinalisePosition (oldX, Offset (X, distanceX));
  868. }
  869. // Cannot move in this direction
  870. if (distanceY == 0)
  871. {
  872. return false;
  873. }
  874. Pos oldY = Y;
  875. return FinalisePosition (oldY, Offset (Y, distanceY));
  876. }
  877. private Pos Offset (Pos pos, int delta)
  878. {
  879. int posAbsolute = pos.GetAnchor (
  880. Orientation == Orientation.Horizontal
  881. ? Parent.Viewport.Height
  882. : Parent.Viewport.Width
  883. );
  884. return posAbsolute + delta;
  885. }
  886. }
  887. }
  888. /// <summary>Represents a method that will handle splitter events.</summary>
  889. public delegate void SplitterEventHandler (object? sender, SplitterEventArgs e);