TileView.cs 34 KB

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