TileView.cs 28 KB

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