TileView.cs 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. // TODO: Bound with Max/Min
  229. contentArea = new Rect (
  230. contentArea.X + 1,
  231. contentArea.Y + 1,
  232. Math.Max (0, contentArea.Width - 2),
  233. Math.Max (0, contentArea.Height - 2));
  234. }
  235. Setup (contentArea);
  236. base.LayoutSubviews ();
  237. }
  238. /// <summary>
  239. /// <para>Distance Horizontally or Vertically to the splitter line when
  240. /// neither view is collapsed.
  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 <see cref="Tile.View"/> of <see cref="Tiles"/> element <paramref name="idx"/>
  325. /// from a regular <see cref="View"/> to a new nested <see cref="TileView"/> with <paramref name="panels"/>
  326. /// number of panels. Returns false if the element already contains a nested view.
  327. /// </summary>
  328. /// <remarks>After successful splitting, the <paramref name="result"/> <see cref="TileView"/>
  329. /// will contain the previous (replaced) <see cref="Tile.View"/> at element 0.</remarks>
  330. /// <param name="idx">The element of <see cref="Tiles"/> that is to be subdivided.</param>
  331. /// <param name="panels">The number of panels that the <see cref="Tile"/> should be split into</param>
  332. /// <param name="result">The new nested <see cref="TileView"/>.</param>
  333. /// <returns><see langword="true"/> if a <see cref="View"/> was converted to a new nested
  334. /// <see cref="TileView"/>. <see langword="false"/> if it was already a nested
  335. /// <see cref="TileView"/></returns>
  336. public bool TrySplitTile (int idx, int panels, out TileView result)
  337. {
  338. // when splitting a view into 2 sub views we will need to migrate
  339. // the title too
  340. var tile = tiles [idx];
  341. // TODO: migrate the title too right?
  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 (panels) {
  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. result = newContainer;
  366. return true;
  367. }
  368. private bool IsValidNewSplitterPos (int idx, Pos value, int fullSpace)
  369. {
  370. int newSize = value.Anchor (fullSpace);
  371. bool isGettingBigger = newSize > splitterDistances [idx].Anchor (fullSpace);
  372. int lastSplitterOrBorder = HasBorder () ? 1 : 0;
  373. int nextSplitterOrBorder = HasBorder () ? fullSpace - 1 : fullSpace;
  374. // Cannot move off screen right
  375. if (newSize >= fullSpace - (HasBorder () ? 1 : 0)) {
  376. if (isGettingBigger) {
  377. return false;
  378. }
  379. }
  380. // Cannot move off screen left
  381. if (newSize < (HasBorder () ? 1 : 0)) {
  382. if (!isGettingBigger) {
  383. return false;
  384. }
  385. }
  386. // Do not allow splitter to move left of the one before
  387. if (idx > 0) {
  388. int posLeft = splitterDistances [idx - 1].Anchor (fullSpace);
  389. if (newSize <= posLeft) {
  390. return false;
  391. }
  392. lastSplitterOrBorder = posLeft;
  393. }
  394. // Do not allow splitter to move right of the one after
  395. if (idx + 1 < splitterDistances.Count) {
  396. int posRight = splitterDistances [idx + 1].Anchor (fullSpace);
  397. if (newSize >= posRight) {
  398. return false;
  399. }
  400. nextSplitterOrBorder = posRight;
  401. }
  402. if (isGettingBigger) {
  403. var spaceForNext = nextSplitterOrBorder - newSize;
  404. // don't grow if it would take us below min size of right panel
  405. if (spaceForNext < tiles [idx + 1].MinSize) {
  406. return false;
  407. }
  408. } else {
  409. var spaceForLast = newSize - lastSplitterOrBorder;
  410. // space required for the line itself
  411. if(idx > 0) {
  412. spaceForLast--;
  413. }
  414. // don't shrink if it would take us below min size of left panel
  415. if (spaceForLast < tiles [idx].MinSize) {
  416. return false;
  417. }
  418. }
  419. return true;
  420. }
  421. private List<TileViewLineView> GetAllLineViewsRecursively (View v)
  422. {
  423. var lines = new List<TileViewLineView> ();
  424. foreach (var sub in v.Subviews) {
  425. if (sub is TileViewLineView s) {
  426. if (s.Visible && s.Parent.GetRootTileView () == this) {
  427. lines.Add (s);
  428. }
  429. } else {
  430. if (sub.Visible) {
  431. lines.AddRange (GetAllLineViewsRecursively (sub));
  432. }
  433. }
  434. }
  435. return lines;
  436. }
  437. private List<TileTitleToRender> GetAllTitlesToRenderRecursively (TileView v, int depth = 0)
  438. {
  439. var titles = new List<TileTitleToRender> ();
  440. foreach (var sub in v.Tiles) {
  441. // Don't render titles for invisible stuff!
  442. if (!sub.View.Visible) {
  443. continue;
  444. }
  445. if (sub.View is TileView subTileView) {
  446. // Panels with sub split tiles in them can never
  447. // have their Titles rendered. Instead we dive in
  448. // and pull up their children as titles
  449. titles.AddRange (GetAllTitlesToRenderRecursively (subTileView, depth + 1));
  450. } else {
  451. if (sub.Title.Length > 0) {
  452. titles.Add (new TileTitleToRender (sub, depth));
  453. }
  454. }
  455. }
  456. return titles;
  457. }
  458. /// <summary>
  459. /// <para>
  460. /// <see langword="true"/> if <see cref="TileView"/> is nested within a parent <see cref="TileView"/>
  461. /// e.g. via the <see cref="TrySplitTile"/>. <see langword="false"/> if it is a root level <see cref="TileView"/>.
  462. /// </para>
  463. /// </summary>
  464. /// <remarks>Note that manually adding one <see cref="TileView"/> to another will not result in a parent/child
  465. /// relationship and both will still be considered 'root' containers. Always use
  466. /// <see cref="TrySplitTile(int, int, out TileView)"/> if you want to subdivide a <see cref="TileView"/>.</remarks>
  467. /// <returns></returns>
  468. public bool IsRootTileView ()
  469. {
  470. // TODO: don't want to layout subviews since the parent recursively lays them all out
  471. return parentTileView == null;
  472. }
  473. /// <summary>
  474. /// Returns the immediate parent <see cref="TileView"/> of this. Note that in case
  475. /// of deep nesting this might not be the root <see cref="TileView"/>. Returns null
  476. /// if this instance is not a nested child (created with
  477. /// <see cref="TrySplitTile(int, int, out TileView)"/>)
  478. /// </summary>
  479. /// <remarks>
  480. /// Use <see cref="IsRootTileView"/> to determine if the returned value is the root.
  481. /// </remarks>
  482. /// <returns></returns>
  483. public TileView GetParentTileView ()
  484. {
  485. return this.parentTileView;
  486. }
  487. private TileView GetRootTileView ()
  488. {
  489. TileView root = this;
  490. while (root.parentTileView != null) {
  491. root = root.parentTileView;
  492. }
  493. return root;
  494. }
  495. private void Setup (Rect bounds)
  496. {
  497. if (bounds.IsEmpty || bounds.Height <= 0 || bounds.Width <= 0) {
  498. return;
  499. }
  500. for (int i = 0; i < splitterLines.Count; i++) {
  501. var line = splitterLines [i];
  502. line.Orientation = Orientation;
  503. line.Width = orientation == Orientation.Vertical
  504. ? 1 : Dim.Fill ();
  505. line.Height = orientation == Orientation.Vertical
  506. ? Dim.Fill () : 1;
  507. line.LineRune = orientation == Orientation.Vertical ?
  508. Driver.VLine : Driver.HLine;
  509. if (orientation == Orientation.Vertical) {
  510. line.X = splitterDistances [i];
  511. line.Y = 0;
  512. } else {
  513. line.Y = splitterDistances [i];
  514. line.X = 0;
  515. }
  516. }
  517. HideSplittersBasedOnTileVisibility ();
  518. var visibleTiles = tiles.Where (t => t.View.Visible).ToArray ();
  519. var visibleSplitterLines = splitterLines.Where (l => l.Visible).ToArray ();
  520. for (int i = 0; i < visibleTiles.Length; i++) {
  521. var tile = visibleTiles [i];
  522. // TODO: Deal with lines being Visibility false
  523. if (Orientation == Orientation.Vertical) {
  524. tile.View.X = i == 0 ? bounds.X : Pos.Right (visibleSplitterLines [i - 1]);
  525. tile.View.Y = bounds.Y;
  526. tile.View.Height = bounds.Height;
  527. tile.View.Width = GetTileWidthOrHeight (i, Bounds.Width, visibleTiles, visibleSplitterLines);
  528. } else {
  529. tile.View.X = bounds.X;
  530. tile.View.Y = i == 0 ? 0 : Pos.Bottom (visibleSplitterLines [i - 1]);
  531. tile.View.Width = bounds.Width;
  532. tile.View.Height = GetTileWidthOrHeight (i, Bounds.Height, visibleTiles, visibleSplitterLines);
  533. }
  534. }
  535. }
  536. private void HideSplittersBasedOnTileVisibility ()
  537. {
  538. if (splitterLines.Count == 0) {
  539. return;
  540. }
  541. foreach (var line in splitterLines) {
  542. line.Visible = true;
  543. }
  544. for (int i = 0; i < tiles.Count; i++) {
  545. if (!tiles [i].View.Visible) {
  546. // when a tile is not visible, prefer hiding
  547. // the splitter on it's left
  548. var candidate = splitterLines [Math.Max (0, i - 1)];
  549. // unless that splitter is already hidden
  550. // e.g. when hiding panels 0 and 1 of a 3 panel
  551. // container
  552. if (candidate.Visible) {
  553. candidate.Visible = false;
  554. } else {
  555. splitterLines [Math.Min (i, splitterLines.Count - 1)].Visible = false;
  556. }
  557. }
  558. }
  559. }
  560. private Dim GetTileWidthOrHeight (int i, int space, Tile [] visibleTiles, TileViewLineView [] visibleSplitterLines)
  561. {
  562. // last tile
  563. if (i + 1 >= visibleTiles.Length) {
  564. return Dim.Fill (HasBorder () ? 1 : 0);
  565. }
  566. var nextSplitter = visibleSplitterLines [i];
  567. var nextSplitterPos = Orientation == Orientation.Vertical ?
  568. nextSplitter.X : nextSplitter.Y;
  569. var nextSplitterDistance = nextSplitterPos.Anchor (space);
  570. var lastSplitter = i >= 1 ? visibleSplitterLines [i - 1] : null;
  571. var lastSplitterPos = Orientation == Orientation.Vertical ?
  572. lastSplitter?.X : lastSplitter?.Y;
  573. var lastSplitterDistance = lastSplitterPos?.Anchor (space) ?? 0;
  574. var distance = nextSplitterDistance - lastSplitterDistance;
  575. if (i > 0) {
  576. return distance - 1;
  577. }
  578. return distance - (HasBorder () ? 1 : 0);
  579. }
  580. private class TileTitleToRender {
  581. public Tile Tile { get; }
  582. public int Depth { get; }
  583. public TileTitleToRender (Tile tile, int depth)
  584. {
  585. Tile = tile;
  586. Depth = depth;
  587. }
  588. /// <summary>
  589. /// Translates the <see cref="Tile"/> title location from its local
  590. /// coordinate space <paramref name="intoCoordinateSpace"/>.
  591. /// </summary>
  592. public Point GetLocalCoordinateForTitle (TileView intoCoordinateSpace)
  593. {
  594. Tile.View.ViewToScreen (0, 0, out var screenCol, out var screenRow);
  595. screenRow--;
  596. return intoCoordinateSpace.ScreenToView (screenCol, screenRow);
  597. }
  598. }
  599. private class TileViewLineView : LineView {
  600. public TileView Parent { get; private set; }
  601. public int Idx { get; }
  602. Point? dragPosition;
  603. Pos dragOrignalPos;
  604. public Point? moveRuneRenderLocation;
  605. public TileViewLineView (TileView parent, int idx)
  606. {
  607. CanFocus = true;
  608. TabStop = true;
  609. this.Parent = parent;
  610. Idx = idx;
  611. base.AddCommand (Command.Right, () => {
  612. return MoveSplitter (1, 0);
  613. });
  614. base.AddCommand (Command.Left, () => {
  615. return MoveSplitter (-1, 0);
  616. });
  617. base.AddCommand (Command.LineUp, () => {
  618. return MoveSplitter (0, -1);
  619. });
  620. base.AddCommand (Command.LineDown, () => {
  621. return MoveSplitter (0, 1);
  622. });
  623. AddKeyBinding (Key.CursorRight, Command.Right);
  624. AddKeyBinding (Key.CursorLeft, Command.Left);
  625. AddKeyBinding (Key.CursorUp, Command.LineUp);
  626. AddKeyBinding (Key.CursorDown, Command.LineDown);
  627. }
  628. public override bool ProcessKey (KeyEvent kb)
  629. {
  630. if (!CanFocus || !HasFocus) {
  631. return base.ProcessKey (kb);
  632. }
  633. var result = InvokeKeybindings (kb);
  634. if (result != null)
  635. return (bool)result;
  636. return base.ProcessKey (kb);
  637. }
  638. public override void PositionCursor ()
  639. {
  640. base.PositionCursor ();
  641. var location = moveRuneRenderLocation ??
  642. new Point (Bounds.Width / 2, Bounds.Height / 2);
  643. Move (location.X, location.Y);
  644. }
  645. public override bool OnEnter (View view)
  646. {
  647. Driver.SetCursorVisibility (CursorVisibility.Default);
  648. PositionCursor ();
  649. return base.OnEnter (view);
  650. }
  651. public override void Redraw (Rect bounds)
  652. {
  653. base.Redraw (bounds);
  654. DrawSplitterSymbol ();
  655. }
  656. public void DrawSplitterSymbol ()
  657. {
  658. if (CanFocus && HasFocus) {
  659. var location = moveRuneRenderLocation ??
  660. new Point (Bounds.Width / 2, Bounds.Height / 2);
  661. AddRune (location.X, location.Y, Driver.Diamond);
  662. }
  663. }
  664. public override bool MouseEvent (MouseEvent mouseEvent)
  665. {
  666. if (!CanFocus) {
  667. return true;
  668. }
  669. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed)) {
  670. // Start a Drag
  671. SetFocus ();
  672. Application.EnsuresTopOnFront ();
  673. if (mouseEvent.Flags == MouseFlags.Button1Pressed) {
  674. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  675. dragOrignalPos = Orientation == Orientation.Horizontal ? Y : X;
  676. Application.GrabMouse (this);
  677. if (Orientation == Orientation.Horizontal) {
  678. } else {
  679. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  680. }
  681. }
  682. return true;
  683. } else if (
  684. dragPosition.HasValue &&
  685. (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  686. // Continue Drag
  687. // how far has user dragged from original location?
  688. if (Orientation == Orientation.Horizontal) {
  689. int dy = mouseEvent.Y - dragPosition.Value.Y;
  690. Parent.SetSplitterPos (Idx, Offset (Y, dy));
  691. moveRuneRenderLocation = new Point (mouseEvent.X, 0);
  692. } else {
  693. int dx = mouseEvent.X - dragPosition.Value.X;
  694. Parent.SetSplitterPos (Idx, Offset (X, dx));
  695. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  696. }
  697. Parent.SetNeedsDisplay ();
  698. return true;
  699. }
  700. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  701. // End Drag
  702. Application.UngrabMouse ();
  703. Driver.UncookMouse ();
  704. FinalisePosition (
  705. dragOrignalPos,
  706. Orientation == Orientation.Horizontal ? Y : X);
  707. dragPosition = null;
  708. moveRuneRenderLocation = null;
  709. }
  710. return false;
  711. }
  712. private bool MoveSplitter (int distanceX, int distanceY)
  713. {
  714. if (Orientation == Orientation.Vertical) {
  715. // Cannot move in this direction
  716. if (distanceX == 0) {
  717. return false;
  718. }
  719. var oldX = X;
  720. return FinalisePosition (oldX, Offset (X, distanceX));
  721. } else {
  722. // Cannot move in this direction
  723. if (distanceY == 0) {
  724. return false;
  725. }
  726. var oldY = Y;
  727. return FinalisePosition (oldY, (Pos)Offset (Y, distanceY));
  728. }
  729. }
  730. private Pos Offset (Pos pos, int delta)
  731. {
  732. var posAbsolute = pos.Anchor (Orientation == Orientation.Horizontal ?
  733. Parent.Bounds.Height : Parent.Bounds.Width);
  734. return posAbsolute + delta;
  735. }
  736. /// <summary>
  737. /// <para>
  738. /// Moves <see cref="Parent"/> <see cref="TileView.SplitterDistances"/> to
  739. /// <see cref="Pos"/> <paramref name="newValue"/> preserving <see cref="Pos"/> format
  740. /// (absolute / relative) that <paramref name="oldValue"/> had.
  741. /// </para>
  742. /// <remarks>This ensures that if splitter location was e.g. 50% before and you move it
  743. /// to absolute 5 then you end up with 10% (assuming a parent had 50 width). </remarks>
  744. /// </summary>
  745. /// <param name="oldValue"></param>
  746. /// <param name="newValue"></param>
  747. private bool FinalisePosition (Pos oldValue, Pos newValue)
  748. {
  749. if (oldValue is Pos.PosFactor) {
  750. if (Orientation == Orientation.Horizontal) {
  751. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Height));
  752. } else {
  753. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Width));
  754. }
  755. } else {
  756. return Parent.SetSplitterPos (Idx, newValue);
  757. }
  758. }
  759. /// <summary>
  760. /// <para>
  761. /// Determines the absolute position of <paramref name="p"/> and
  762. /// returns a <see cref="Pos.PosFactor"/> that describes the percentage of that.
  763. /// </para>
  764. /// <para>Effectively turning any <see cref="Pos"/> into a <see cref="Pos.PosFactor"/>
  765. /// (as if created with <see cref="Pos.Percent(float)"/>)</para>
  766. /// </summary>
  767. /// <param name="p">The <see cref="Pos"/> to convert to <see cref="Pos.Percent(float)"/></param>
  768. /// <param name="parentLength">The Height/Width that <paramref name="p"/> lies within</param>
  769. /// <returns></returns>
  770. private Pos ConvertToPosFactor (Pos p, int parentLength)
  771. {
  772. // calculate position in the 'middle' of the cell at p distance along parentLength
  773. float position = p.Anchor (parentLength) + 0.5f;
  774. return new Pos.PosFactor (position / parentLength);
  775. }
  776. }
  777. private bool HasBorder ()
  778. {
  779. return IntegratedBorder != BorderStyle.None;
  780. }
  781. }
  782. /// <summary>
  783. /// Provides data for <see cref="TileView"/> events.
  784. /// </summary>
  785. public class SplitterEventArgs : EventArgs {
  786. /// <summary>
  787. /// Creates a new instance of the <see cref="SplitterEventArgs"/> class.
  788. /// </summary>
  789. /// <param name="tileView"><see cref="TileView"/> in which splitter is being moved.</param>
  790. /// <param name="idx">Index of the splitter being moved in <see cref="TileView.SplitterDistances"/>.</param>
  791. /// <param name="splitterDistance">The new <see cref="Pos"/> of the splitter line.</param>
  792. public SplitterEventArgs (TileView tileView, int idx, Pos splitterDistance)
  793. {
  794. SplitterDistance = splitterDistance;
  795. TileView = tileView;
  796. Idx = idx;
  797. }
  798. /// <summary>
  799. /// New position of the splitter line (see <see cref="TileView.SplitterDistances"/>).
  800. /// </summary>
  801. public Pos SplitterDistance { get; }
  802. /// <summary>
  803. /// Container (sender) of the event.
  804. /// </summary>
  805. public TileView TileView { get; }
  806. /// <summary>
  807. /// Gets the index of the splitter that is being moved. This can be
  808. /// used to index <see cref="TileView.SplitterDistances"/>
  809. /// </summary>
  810. public int Idx { get; }
  811. }
  812. /// <summary>
  813. /// Represents a method that will handle splitter events.
  814. /// </summary>
  815. public delegate void SplitterEventHandler (object sender, SplitterEventArgs e);
  816. }