TileView.cs 34 KB

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