TileView.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. /// <summary>Creates a new instance of the <see cref="TileView"/> class with <paramref name="tiles"/> number of tiles.</summary>
  16. /// <param name="tiles"></param>
  17. public TileView (int tiles) { RebuildForTileCount (tiles); }
  18. /// <summary>The line style to use when drawing the splitter lines.</summary>
  19. public LineStyle LineStyle { get; set; } = LineStyle.None;
  20. /// <summary>Orientation of the dividing line (Horizontal or Vertical).</summary>
  21. public Orientation Orientation
  22. {
  23. get => _orientation;
  24. set
  25. {
  26. _orientation = value;
  27. if (IsInitialized)
  28. {
  29. LayoutSubviews ();
  30. }
  31. }
  32. }
  33. /// <summary>The splitter locations. Note that there will be N-1 splitters where N is the number of <see cref="Tiles"/>.</summary>
  34. public IReadOnlyCollection<Pos> SplitterDistances => _splitterDistances.AsReadOnly ();
  35. /// <summary>The sub sections hosted by the view</summary>
  36. public IReadOnlyCollection<Tile> Tiles => _tiles.AsReadOnly ();
  37. // TODO: Update to use Key instead of KeyCode
  38. /// <summary>
  39. /// The keyboard key that the user can press to toggle resizing of splitter lines. Mouse drag splitting is always
  40. /// enabled.
  41. /// </summary>
  42. public KeyCode ToggleResizable { get; set; } = KeyCode.CtrlMask | KeyCode.F10;
  43. /// <summary>
  44. /// Returns the immediate parent <see cref="TileView"/> of this. Note that in case of deep nesting this might not
  45. /// be the root <see cref="TileView"/>. Returns null if this instance is not a nested child (created with
  46. /// <see cref="TrySplitTile(int, int, out TileView)"/>)
  47. /// </summary>
  48. /// <remarks>Use <see cref="IsRootTileView"/> to determine if the returned value is the root.</remarks>
  49. /// <returns></returns>
  50. public TileView GetParentTileView () { return parentTileView; }
  51. /// <summary>
  52. /// Returns the index of the first <see cref="Tile"/> in <see cref="Tiles"/> which contains
  53. /// <paramref name="toFind"/>.
  54. /// </summary>
  55. public int IndexOf (View toFind, bool recursive = false)
  56. {
  57. for (var i = 0; i < _tiles.Count; i++)
  58. {
  59. View v = _tiles [i].ContentView;
  60. if (v == toFind)
  61. {
  62. return i;
  63. }
  64. if (v.Subviews.Contains (toFind))
  65. {
  66. return i;
  67. }
  68. if (recursive)
  69. {
  70. if (RecursiveContains (v.Subviews, toFind))
  71. {
  72. return i;
  73. }
  74. }
  75. }
  76. return -1;
  77. }
  78. /// <summary>
  79. /// Adds a new <see cref="Tile"/> to the collection at <paramref name="idx"/>. This will also add another splitter
  80. /// line
  81. /// </summary>
  82. /// <param name="idx"></param>
  83. public Tile InsertTile (int idx)
  84. {
  85. Tile [] oldTiles = Tiles.ToArray ();
  86. RebuildForTileCount (oldTiles.Length + 1);
  87. Tile toReturn = null;
  88. for (var i = 0; i < _tiles.Count; i++)
  89. {
  90. if (i != idx)
  91. {
  92. Tile oldTile = oldTiles [i > idx ? i - 1 : i];
  93. // remove the new empty View
  94. Remove (_tiles [i].ContentView);
  95. _tiles [i].ContentView.Dispose ();
  96. _tiles [i].ContentView = null;
  97. // restore old Tile and View
  98. _tiles [i] = oldTile;
  99. Add (_tiles [i].ContentView);
  100. }
  101. else
  102. {
  103. toReturn = _tiles [i];
  104. }
  105. }
  106. SetNeedsDisplay ();
  107. if (IsInitialized)
  108. {
  109. LayoutSubviews ();
  110. }
  111. return toReturn;
  112. }
  113. /// <summary>
  114. /// <para>
  115. /// <see langword="true"/> if <see cref="TileView"/> is nested within a parent <see cref="TileView"/> e.g. via
  116. /// the <see cref="TrySplitTile"/>. <see langword="false"/> if it is a root level <see cref="TileView"/>.
  117. /// </para>
  118. /// </summary>
  119. /// <remarks>
  120. /// Note that manually adding one <see cref="TileView"/> to another will not result in a parent/child relationship
  121. /// and both will still be considered 'root' containers. Always use <see cref="TrySplitTile(int, int, out TileView)"/>
  122. /// if you want to subdivide a <see cref="TileView"/>.
  123. /// </remarks>
  124. /// <returns></returns>
  125. public bool IsRootTileView () { return parentTileView == null; }
  126. /// <inheritdoc/>
  127. public override void LayoutSubviews ()
  128. {
  129. if (!IsInitialized)
  130. {
  131. return;
  132. }
  133. Rectangle viewport = Viewport;
  134. if (HasBorder ())
  135. {
  136. viewport = new (
  137. viewport.X + 1,
  138. viewport.Y + 1,
  139. Math.Max (0, viewport.Width - 2),
  140. Math.Max (0, viewport.Height - 2)
  141. );
  142. }
  143. Setup (viewport);
  144. base.LayoutSubviews ();
  145. }
  146. // BUG: v2 fix this hack
  147. // QUESTION: Does this need to be fixed before events are refactored?
  148. /// <summary>Overridden so no Frames get drawn</summary>
  149. /// <returns></returns>
  150. public override bool OnDrawAdornments () { return false; }
  151. /// <inheritdoc/>
  152. public override void OnDrawContent (Rectangle viewport)
  153. {
  154. Driver.SetAttribute (ColorScheme.Normal);
  155. Clear ();
  156. base.OnDrawContent (viewport);
  157. var lc = new LineCanvas ();
  158. List<TileViewLineView> allLines = GetAllLineViewsRecursively (this);
  159. List<TileTitleToRender> allTitlesToRender = GetAllTitlesToRenderRecursively (this);
  160. if (IsRootTileView ())
  161. {
  162. if (HasBorder ())
  163. {
  164. lc.AddLine (Point.Empty, Viewport.Width, Orientation.Horizontal, LineStyle);
  165. lc.AddLine (Point.Empty, Viewport.Height, Orientation.Vertical, LineStyle);
  166. lc.AddLine (
  167. new Point (Viewport.Width - 1, Viewport.Height - 1),
  168. -Viewport.Width,
  169. Orientation.Horizontal,
  170. LineStyle
  171. );
  172. lc.AddLine (
  173. new Point (Viewport.Width - 1, Viewport.Height - 1),
  174. -Viewport.Height,
  175. Orientation.Vertical,
  176. LineStyle
  177. );
  178. }
  179. foreach (TileViewLineView line in allLines)
  180. {
  181. bool isRoot = _splitterLines.Contains (line);
  182. Rectangle screen = line.ViewportToScreen (Rectangle.Empty);
  183. Point origin = ScreenToFrame (screen.X, screen.Y);
  184. int length = line.Orientation == Orientation.Horizontal ? line.Frame.Width : line.Frame.Height;
  185. if (!isRoot)
  186. {
  187. if (line.Orientation == Orientation.Horizontal)
  188. {
  189. origin.X -= 1;
  190. }
  191. else
  192. {
  193. origin.Y -= 1;
  194. }
  195. length += 2;
  196. }
  197. lc.AddLine (origin, length, line.Orientation, LineStyle);
  198. }
  199. }
  200. Driver.SetAttribute (ColorScheme.Normal);
  201. foreach (KeyValuePair<Point, Rune> p in lc.GetMap (Viewport))
  202. {
  203. AddRune (p.Key.X, p.Key.Y, p.Value);
  204. }
  205. // Redraw the lines so that focus/drag symbol renders
  206. foreach (TileViewLineView line in allLines)
  207. {
  208. line.DrawSplitterSymbol ();
  209. }
  210. // Draw Titles over Border
  211. foreach (TileTitleToRender titleToRender in allTitlesToRender)
  212. {
  213. Point renderAt = titleToRender.GetLocalCoordinateForTitle (this);
  214. if (renderAt.Y < 0)
  215. {
  216. // If we have no border then root level tiles
  217. // have nowhere to render their titles.
  218. continue;
  219. }
  220. // TODO: Render with focus color if focused
  221. string title = titleToRender.GetTrimmedTitle ();
  222. for (var i = 0; i < title.Length; i++)
  223. {
  224. AddRune (renderAt.X + i, renderAt.Y, (Rune)title [i]);
  225. }
  226. }
  227. }
  228. //// BUGBUG: Why is this not handled by a key binding???
  229. /// <inheritdoc/>
  230. public override bool OnProcessKeyDown (Key keyEvent)
  231. {
  232. var focusMoved = false;
  233. if (keyEvent.KeyCode == ToggleResizable)
  234. {
  235. foreach (TileViewLineView l in _splitterLines)
  236. {
  237. bool iniBefore = l.IsInitialized;
  238. l.IsInitialized = false;
  239. l.CanFocus = !l.CanFocus;
  240. l.IsInitialized = iniBefore;
  241. if (l.CanFocus && !focusMoved)
  242. {
  243. l.SetFocus ();
  244. focusMoved = true;
  245. }
  246. }
  247. return true;
  248. }
  249. return false;
  250. }
  251. /// <summary>
  252. /// Scraps all <see cref="Tiles"/> and creates <paramref name="count"/> new tiles in orientation
  253. /// <see cref="Orientation"/>
  254. /// </summary>
  255. /// <param name="count"></param>
  256. public void RebuildForTileCount (int count)
  257. {
  258. _tiles = new List<Tile> ();
  259. _splitterDistances = new List<Pos> ();
  260. if (_splitterLines is { })
  261. {
  262. foreach (TileViewLineView sl in _splitterLines)
  263. {
  264. sl.Dispose ();
  265. }
  266. }
  267. _splitterLines = new List<TileViewLineView> ();
  268. RemoveAll ();
  269. foreach (Tile tile in _tiles)
  270. {
  271. tile.ContentView.Dispose ();
  272. tile.ContentView = null;
  273. }
  274. _tiles.Clear ();
  275. _splitterDistances.Clear ();
  276. if (count == 0)
  277. {
  278. return;
  279. }
  280. for (var i = 0; i < count; i++)
  281. {
  282. if (i > 0)
  283. {
  284. Pos currentPos = Pos.Percent (100 / count * i);
  285. _splitterDistances.Add (currentPos);
  286. var line = new TileViewLineView (this, i - 1);
  287. Add (line);
  288. _splitterLines.Add (line);
  289. }
  290. var tile = new Tile ();
  291. _tiles.Add (tile);
  292. Add (tile.ContentView);
  293. tile.TitleChanged += (s, e) => SetNeedsDisplay ();
  294. }
  295. if (IsInitialized)
  296. {
  297. LayoutSubviews ();
  298. }
  299. }
  300. /// <summary>
  301. /// Removes a <see cref="Tiles"/> at the provided <paramref name="idx"/> from the view. Returns the removed tile
  302. /// or null if already empty.
  303. /// </summary>
  304. /// <param name="idx"></param>
  305. /// <returns></returns>
  306. public Tile RemoveTile (int idx)
  307. {
  308. Tile [] oldTiles = Tiles.ToArray ();
  309. if (idx < 0 || idx >= oldTiles.Length)
  310. {
  311. return null;
  312. }
  313. Tile removed = Tiles.ElementAt (idx);
  314. RebuildForTileCount (oldTiles.Length - 1);
  315. for (var i = 0; i < _tiles.Count; i++)
  316. {
  317. int oldIdx = i >= idx ? i + 1 : i;
  318. Tile oldTile = oldTiles [oldIdx];
  319. // remove the new empty View
  320. Remove (_tiles [i].ContentView);
  321. _tiles [i].ContentView.Dispose ();
  322. _tiles [i].ContentView = null;
  323. // restore old Tile and View
  324. _tiles [i] = oldTile;
  325. Add (_tiles [i].ContentView);
  326. }
  327. SetNeedsDisplay ();
  328. LayoutSubviews ();
  329. return removed;
  330. }
  331. /// <summary>
  332. /// <para>
  333. /// Attempts to update the <see cref="SplitterDistances"/> of line at <paramref name="idx"/> to the new
  334. /// <paramref name="value"/>. Returns false if the new position is not allowed because of
  335. /// <see cref="Tile.MinSize"/>, location of other splitters etc.
  336. /// </para>
  337. /// <para>
  338. /// Only absolute values (e.g. 10) and percent values (i.e. <see cref="Pos.Percent(float)"/>) are supported for
  339. /// this property.
  340. /// </para>
  341. /// </summary>
  342. public bool SetSplitterPos (int idx, Pos value)
  343. {
  344. // BUGBUG: PosAbsolute & PosFactor are internal API. TileView should not be using it and should do something different to get the value.
  345. if (!(value is Pos.PosAbsolute) && !(value is Pos.PosFactor))
  346. {
  347. throw new ArgumentException (
  348. $"Only Percent and Absolute values are supported. Passed value was {value.GetType ().Name}"
  349. );
  350. }
  351. int fullSpace = _orientation == Orientation.Vertical ? Viewport.Width : Viewport.Height;
  352. if (fullSpace != 0 && !IsValidNewSplitterPos (idx, value, fullSpace))
  353. {
  354. return false;
  355. }
  356. _splitterDistances [idx] = value;
  357. GetRootTileView ().LayoutSubviews ();
  358. OnSplitterMoved (idx);
  359. return true;
  360. }
  361. /// <summary>Invoked when any of the <see cref="SplitterDistances"/> is changed.</summary>
  362. public event SplitterEventHandler SplitterMoved;
  363. /// <summary>
  364. /// Converts of <see cref="Tiles"/> element <paramref name="idx"/> from a regular <see cref="View"/> to a new
  365. /// nested <see cref="TileView"/> the specified <paramref name="numberOfPanels"/>. Returns false if the element already
  366. /// contains a nested view.
  367. /// </summary>
  368. /// <remarks>
  369. /// After successful splitting, the old contents will be moved to the <paramref name="result"/>
  370. /// <see cref="TileView"/> 's first tile.
  371. /// </remarks>
  372. /// <param name="idx">The element of <see cref="Tiles"/> that is to be subdivided.</param>
  373. /// <param name="numberOfPanels">The number of panels that the <see cref="Tile"/> should be split into</param>
  374. /// <param name="result">The new nested <see cref="TileView"/>.</param>
  375. /// <returns>
  376. /// <see langword="true"/> if a <see cref="View"/> was converted to a new nested <see cref="TileView"/>.
  377. /// <see langword="false"/> if it was already a nested <see cref="TileView"/>
  378. /// </returns>
  379. public bool TrySplitTile (int idx, int numberOfPanels, out TileView result)
  380. {
  381. // when splitting a view into 2 sub views we will need to migrate
  382. // the title too
  383. Tile tile = _tiles [idx];
  384. string title = tile.Title;
  385. View toMove = tile.ContentView;
  386. if (toMove is TileView existing)
  387. {
  388. result = existing;
  389. return false;
  390. }
  391. var newContainer = new TileView (numberOfPanels)
  392. {
  393. Width = Dim.Fill (), Height = Dim.Fill (), parentTileView = this
  394. };
  395. // Take everything out of the View we are moving
  396. View [] childViews = toMove.Subviews.ToArray ();
  397. toMove.RemoveAll ();
  398. // Remove the view itself and replace it with the new TileView
  399. Remove (toMove);
  400. toMove.Dispose ();
  401. toMove = null;
  402. Add (newContainer);
  403. tile.ContentView = newContainer;
  404. View newTileView1 = newContainer._tiles [0].ContentView;
  405. // Add the original content into the first view of the new container
  406. foreach (View childView in childViews)
  407. {
  408. newTileView1.Add (childView);
  409. }
  410. // Move the title across too
  411. newContainer._tiles [0].Title = title;
  412. tile.Title = string.Empty;
  413. result = newContainer;
  414. return true;
  415. }
  416. /// <inheritdoc/>
  417. protected override void Dispose (bool disposing)
  418. {
  419. foreach (Tile tile in Tiles)
  420. {
  421. Remove (tile.ContentView);
  422. tile.ContentView.Dispose ();
  423. }
  424. base.Dispose (disposing);
  425. }
  426. /// <summary>Raises the <see cref="SplitterMoved"/> event</summary>
  427. protected virtual void OnSplitterMoved (int idx) { SplitterMoved?.Invoke (this, new SplitterEventArgs (this, idx, _splitterDistances [idx])); }
  428. private List<TileViewLineView> GetAllLineViewsRecursively (View v)
  429. {
  430. List<TileViewLineView> lines = new ();
  431. foreach (View sub in v.Subviews)
  432. {
  433. if (sub is TileViewLineView s)
  434. {
  435. if (s.Visible && s.Parent.GetRootTileView () == this)
  436. {
  437. lines.Add (s);
  438. }
  439. }
  440. else
  441. {
  442. if (sub.Visible)
  443. {
  444. lines.AddRange (GetAllLineViewsRecursively (sub));
  445. }
  446. }
  447. }
  448. return lines;
  449. }
  450. private List<TileTitleToRender> GetAllTitlesToRenderRecursively (TileView v, int depth = 0)
  451. {
  452. List<TileTitleToRender> titles = new ();
  453. foreach (Tile sub in v.Tiles)
  454. {
  455. // Don't render titles for invisible stuff!
  456. if (!sub.ContentView.Visible)
  457. {
  458. continue;
  459. }
  460. if (sub.ContentView is TileView subTileView)
  461. {
  462. // Panels with sub split tiles in them can never
  463. // have their Titles rendered. Instead we dive in
  464. // and pull up their children as titles
  465. titles.AddRange (GetAllTitlesToRenderRecursively (subTileView, depth + 1));
  466. }
  467. else
  468. {
  469. if (sub.Title.Length > 0)
  470. {
  471. titles.Add (new TileTitleToRender (v, sub, depth));
  472. }
  473. }
  474. }
  475. return titles;
  476. }
  477. private TileView GetRootTileView ()
  478. {
  479. TileView root = this;
  480. while (root.parentTileView is { })
  481. {
  482. root = root.parentTileView;
  483. }
  484. return root;
  485. }
  486. private Dim GetTileWidthOrHeight (int i, int space, Tile [] visibleTiles, TileViewLineView [] visibleSplitterLines)
  487. {
  488. // last tile
  489. if (i + 1 >= visibleTiles.Length)
  490. {
  491. return Dim.Fill (HasBorder () ? 1 : 0);
  492. }
  493. TileViewLineView nextSplitter = visibleSplitterLines [i];
  494. Pos nextSplitterPos = Orientation == Orientation.Vertical ? nextSplitter.X : nextSplitter.Y;
  495. // BUGBUG: Pos.Anchor is an internal API. TileView should not be using it and should do something different to get the value.
  496. int nextSplitterDistance = nextSplitterPos.Anchor (space);
  497. TileViewLineView lastSplitter = i >= 1 ? visibleSplitterLines [i - 1] : null;
  498. Pos lastSplitterPos = Orientation == Orientation.Vertical ? lastSplitter?.X : lastSplitter?.Y;
  499. // BUGBUG: Pos.Anchor is an internal API. TileView should not be using it and should do something different to get the value.
  500. int lastSplitterDistance = lastSplitterPos?.Anchor (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.Anchor (fullSpace);
  543. bool isGettingBigger = newSize > _splitterDistances [idx].Anchor (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].Anchor (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].Anchor (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 (screen.X, screen.Y - 1);
  698. }
  699. internal string GetTrimmedTitle ()
  700. {
  701. Dim spaceDim = Tile.ContentView.Width;
  702. // BUGBUG: Dim.Anchor is internal. This should do something else to get the width.
  703. int spaceAbs = spaceDim.Anchor (Parent.Viewport.Width);
  704. var title = $" {Tile.Title} ";
  705. if (title.Length > spaceAbs)
  706. {
  707. return title.Substring (0, spaceAbs);
  708. }
  709. return title;
  710. }
  711. }
  712. private class TileViewLineView : LineView
  713. {
  714. public Point? moveRuneRenderLocation;
  715. private Pos dragOrignalPos;
  716. private Point? dragPosition;
  717. public TileViewLineView (TileView parent, int idx)
  718. {
  719. CanFocus = false;
  720. TabStop = true;
  721. Parent = parent;
  722. Idx = idx;
  723. AddCommand (Command.Right, () => { return MoveSplitter (1, 0); });
  724. AddCommand (Command.Left, () => { return MoveSplitter (-1, 0); });
  725. AddCommand (Command.LineUp, () => { return MoveSplitter (0, -1); });
  726. AddCommand (Command.LineDown, () => { return MoveSplitter (0, 1); });
  727. KeyBindings.Add (Key.CursorRight, Command.Right);
  728. KeyBindings.Add (Key.CursorLeft, Command.Left);
  729. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  730. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  731. }
  732. public int Idx { get; }
  733. public TileView Parent { get; }
  734. public void DrawSplitterSymbol ()
  735. {
  736. if (dragPosition is { } || CanFocus)
  737. {
  738. Point location = moveRuneRenderLocation ?? new Point (Viewport.Width / 2, Viewport.Height / 2);
  739. AddRune (location.X, location.Y, Glyphs.Diamond);
  740. }
  741. }
  742. protected internal override bool OnMouseEvent (MouseEvent mouseEvent)
  743. {
  744. if (!dragPosition.HasValue && mouseEvent.Flags == MouseFlags.Button1Pressed)
  745. {
  746. // Start a Drag
  747. SetFocus ();
  748. Application.BringOverlappedTopToFront ();
  749. if (mouseEvent.Flags == MouseFlags.Button1Pressed)
  750. {
  751. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  752. dragOrignalPos = Orientation == Orientation.Horizontal ? Y : X;
  753. Application.GrabMouse (this);
  754. if (Orientation == Orientation.Horizontal)
  755. { }
  756. else
  757. {
  758. moveRuneRenderLocation = new Point (
  759. 0,
  760. Math.Max (1, Math.Min (Viewport.Height - 2, mouseEvent.Y))
  761. );
  762. }
  763. }
  764. return true;
  765. }
  766. if (
  767. dragPosition.HasValue && mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  768. {
  769. // Continue Drag
  770. // how far has user dragged from original location?
  771. if (Orientation == Orientation.Horizontal)
  772. {
  773. int dy = mouseEvent.Y - dragPosition.Value.Y;
  774. Parent.SetSplitterPos (Idx, Offset (Y, dy));
  775. moveRuneRenderLocation = new Point (mouseEvent.X, 0);
  776. }
  777. else
  778. {
  779. int dx = mouseEvent.X - dragPosition.Value.X;
  780. Parent.SetSplitterPos (Idx, Offset (X, dx));
  781. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Viewport.Height - 2, mouseEvent.Y)));
  782. }
  783. Parent.SetNeedsDisplay ();
  784. return true;
  785. }
  786. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue)
  787. {
  788. // End Drag
  789. Application.UngrabMouse ();
  790. //Driver.UncookMouse ();
  791. FinalisePosition (
  792. dragOrignalPos,
  793. Orientation == Orientation.Horizontal ? Y : X
  794. );
  795. dragPosition = null;
  796. moveRuneRenderLocation = null;
  797. }
  798. return false;
  799. }
  800. public override void OnDrawContent (Rectangle viewport)
  801. {
  802. base.OnDrawContent (viewport);
  803. DrawSplitterSymbol ();
  804. }
  805. public override Point? PositionCursor ()
  806. {
  807. base.PositionCursor ();
  808. Point location = moveRuneRenderLocation ?? new Point (Viewport.Width / 2, Viewport.Height / 2);
  809. Move (location.X, location.Y);
  810. return null; // Hide cursor
  811. }
  812. /// <summary>
  813. /// <para>
  814. /// Determines the absolute position of <paramref name="p"/> and returns a <see cref="Pos.PosFactor"/> that
  815. /// describes the percentage of that.
  816. /// </para>
  817. /// <para>
  818. /// Effectively turning any <see cref="Pos"/> into a <see cref="Pos.PosFactor"/> (as if created with
  819. /// <see cref="Pos.Percent(float)"/>)
  820. /// </para>
  821. /// </summary>
  822. /// <param name="p">The <see cref="Pos"/> to convert to <see cref="Pos.Percent(float)"/></param>
  823. /// <param name="parentLength">The Height/Width that <paramref name="p"/> lies within</param>
  824. /// <returns></returns>
  825. private Pos ConvertToPosFactor (Pos p, int parentLength)
  826. {
  827. // calculate position in the 'middle' of the cell at p distance along parentLength
  828. float position = p.Anchor (parentLength) + 0.5f;
  829. return new Pos.PosFactor (position / parentLength);
  830. }
  831. /// <summary>
  832. /// <para>
  833. /// Moves <see cref="Parent"/> <see cref="TileView.SplitterDistances"/> to <see cref="Pos"/>
  834. /// <paramref name="newValue"/> preserving <see cref="Pos"/> format (absolute / relative) that
  835. /// <paramref name="oldValue"/> had.
  836. /// </para>
  837. /// <remarks>
  838. /// This ensures that if splitter location was e.g. 50% before and you move it to absolute 5 then you end up
  839. /// with 10% (assuming a parent had 50 width).
  840. /// </remarks>
  841. /// </summary>
  842. /// <param name="oldValue"></param>
  843. /// <param name="newValue"></param>
  844. private bool FinalisePosition (Pos oldValue, Pos newValue)
  845. {
  846. if (oldValue is Pos.PosFactor)
  847. {
  848. if (Orientation == Orientation.Horizontal)
  849. {
  850. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Viewport.Height));
  851. }
  852. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Viewport.Width));
  853. }
  854. return Parent.SetSplitterPos (Idx, newValue);
  855. }
  856. private bool MoveSplitter (int distanceX, int distanceY)
  857. {
  858. if (Orientation == Orientation.Vertical)
  859. {
  860. // Cannot move in this direction
  861. if (distanceX == 0)
  862. {
  863. return false;
  864. }
  865. Pos oldX = X;
  866. return FinalisePosition (oldX, Offset (X, distanceX));
  867. }
  868. // Cannot move in this direction
  869. if (distanceY == 0)
  870. {
  871. return false;
  872. }
  873. Pos oldY = Y;
  874. return FinalisePosition (oldY, Offset (Y, distanceY));
  875. }
  876. private Pos Offset (Pos pos, int delta)
  877. {
  878. int posAbsolute = pos.Anchor (
  879. Orientation == Orientation.Horizontal
  880. ? Parent.Viewport.Height
  881. : Parent.Viewport.Width
  882. );
  883. return posAbsolute + delta;
  884. }
  885. }
  886. }
  887. /// <summary>Represents a method that will handle splitter events.</summary>
  888. public delegate void SplitterEventHandler (object sender, SplitterEventArgs e);