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