TileView.cs 27 KB

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