TileView.cs 34 KB

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