TileView.cs 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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.GetTrimmedTitle();
  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 (v,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. return parentTileView == null;
  478. }
  479. /// <summary>
  480. /// Returns the immediate parent <see cref="TileView"/> of this. Note that in case
  481. /// of deep nesting this might not be the root <see cref="TileView"/>. Returns null
  482. /// if this instance is not a nested child (created with
  483. /// <see cref="TrySplitTile(int, int, out TileView)"/>)
  484. /// </summary>
  485. /// <remarks>
  486. /// Use <see cref="IsRootTileView"/> to determine if the returned value is the root.
  487. /// </remarks>
  488. /// <returns></returns>
  489. public TileView GetParentTileView ()
  490. {
  491. return this.parentTileView;
  492. }
  493. private TileView GetRootTileView ()
  494. {
  495. TileView root = this;
  496. while (root.parentTileView != null) {
  497. root = root.parentTileView;
  498. }
  499. return root;
  500. }
  501. private void Setup (Rect bounds)
  502. {
  503. if (bounds.IsEmpty || bounds.Height <= 0 || bounds.Width <= 0) {
  504. return;
  505. }
  506. for (int i = 0; i < splitterLines.Count; i++) {
  507. var line = splitterLines [i];
  508. line.Orientation = Orientation;
  509. line.Width = orientation == Orientation.Vertical
  510. ? 1 : Dim.Fill ();
  511. line.Height = orientation == Orientation.Vertical
  512. ? Dim.Fill () : 1;
  513. line.LineRune = orientation == Orientation.Vertical ?
  514. Driver.VLine : Driver.HLine;
  515. if (orientation == Orientation.Vertical) {
  516. line.X = splitterDistances [i];
  517. line.Y = 0;
  518. } else {
  519. line.Y = splitterDistances [i];
  520. line.X = 0;
  521. }
  522. }
  523. HideSplittersBasedOnTileVisibility ();
  524. var visibleTiles = tiles.Where (t => t.View.Visible).ToArray ();
  525. var visibleSplitterLines = splitterLines.Where (l => l.Visible).ToArray ();
  526. for (int i = 0; i < visibleTiles.Length; i++) {
  527. var tile = visibleTiles [i];
  528. if (Orientation == Orientation.Vertical) {
  529. tile.View.X = i == 0 ? bounds.X : Pos.Right (visibleSplitterLines [i - 1]);
  530. tile.View.Y = bounds.Y;
  531. tile.View.Height = bounds.Height;
  532. tile.View.Width = GetTileWidthOrHeight (i, Bounds.Width, visibleTiles, visibleSplitterLines);
  533. } else {
  534. tile.View.X = bounds.X;
  535. tile.View.Y = i == 0 ? 0 : Pos.Bottom (visibleSplitterLines [i - 1]);
  536. tile.View.Width = bounds.Width;
  537. tile.View.Height = GetTileWidthOrHeight (i, Bounds.Height, visibleTiles, visibleSplitterLines);
  538. }
  539. }
  540. }
  541. private void HideSplittersBasedOnTileVisibility ()
  542. {
  543. if (splitterLines.Count == 0) {
  544. return;
  545. }
  546. foreach (var line in splitterLines) {
  547. line.Visible = true;
  548. }
  549. for (int i = 0; i < tiles.Count; i++) {
  550. if (!tiles [i].View.Visible) {
  551. // when a tile is not visible, prefer hiding
  552. // the splitter on it's left
  553. var candidate = splitterLines [Math.Max (0, i - 1)];
  554. // unless that splitter is already hidden
  555. // e.g. when hiding panels 0 and 1 of a 3 panel
  556. // container
  557. if (candidate.Visible) {
  558. candidate.Visible = false;
  559. } else {
  560. splitterLines [Math.Min (i, splitterLines.Count - 1)].Visible = false;
  561. }
  562. }
  563. }
  564. }
  565. private Dim GetTileWidthOrHeight (int i, int space, Tile [] visibleTiles, TileViewLineView [] visibleSplitterLines)
  566. {
  567. // last tile
  568. if (i + 1 >= visibleTiles.Length) {
  569. return Dim.Fill (HasBorder () ? 1 : 0);
  570. }
  571. var nextSplitter = visibleSplitterLines [i];
  572. var nextSplitterPos = Orientation == Orientation.Vertical ?
  573. nextSplitter.X : nextSplitter.Y;
  574. var nextSplitterDistance = nextSplitterPos.Anchor (space);
  575. var lastSplitter = i >= 1 ? visibleSplitterLines [i - 1] : null;
  576. var lastSplitterPos = Orientation == Orientation.Vertical ?
  577. lastSplitter?.X : lastSplitter?.Y;
  578. var lastSplitterDistance = lastSplitterPos?.Anchor (space) ?? 0;
  579. var distance = nextSplitterDistance - lastSplitterDistance;
  580. if (i > 0) {
  581. return distance - 1;
  582. }
  583. return distance - (HasBorder () ? 1 : 0);
  584. }
  585. private class TileTitleToRender {
  586. public TileView Parent { get; }
  587. public Tile Tile { get; }
  588. public int Depth { get; }
  589. public TileTitleToRender (TileView parent, Tile tile, int depth)
  590. {
  591. Parent = parent;
  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. internal string GetTrimmedTitle ()
  606. {
  607. Dim spaceDim = Tile.View.Width;
  608. var spaceAbs = spaceDim.Anchor (Parent.Bounds.Width);
  609. var title = Tile.Title;
  610. if(title.Length > spaceAbs) {
  611. return title.Substring (0, spaceAbs);
  612. }
  613. return title;
  614. }
  615. }
  616. private class TileViewLineView : LineView {
  617. public TileView Parent { get; private set; }
  618. public int Idx { get; }
  619. Point? dragPosition;
  620. Pos dragOrignalPos;
  621. public Point? moveRuneRenderLocation;
  622. public TileViewLineView (TileView parent, int idx)
  623. {
  624. CanFocus = true;
  625. TabStop = true;
  626. this.Parent = parent;
  627. Idx = idx;
  628. base.AddCommand (Command.Right, () => {
  629. return MoveSplitter (1, 0);
  630. });
  631. base.AddCommand (Command.Left, () => {
  632. return MoveSplitter (-1, 0);
  633. });
  634. base.AddCommand (Command.LineUp, () => {
  635. return MoveSplitter (0, -1);
  636. });
  637. base.AddCommand (Command.LineDown, () => {
  638. return MoveSplitter (0, 1);
  639. });
  640. AddKeyBinding (Key.CursorRight, Command.Right);
  641. AddKeyBinding (Key.CursorLeft, Command.Left);
  642. AddKeyBinding (Key.CursorUp, Command.LineUp);
  643. AddKeyBinding (Key.CursorDown, Command.LineDown);
  644. }
  645. public override bool ProcessKey (KeyEvent kb)
  646. {
  647. if (!CanFocus || !HasFocus) {
  648. return base.ProcessKey (kb);
  649. }
  650. var result = InvokeKeybindings (kb);
  651. if (result != null)
  652. return (bool)result;
  653. return base.ProcessKey (kb);
  654. }
  655. public override void PositionCursor ()
  656. {
  657. base.PositionCursor ();
  658. var location = moveRuneRenderLocation ??
  659. new Point (Bounds.Width / 2, Bounds.Height / 2);
  660. Move (location.X, location.Y);
  661. }
  662. public override bool OnEnter (View view)
  663. {
  664. Driver.SetCursorVisibility (CursorVisibility.Default);
  665. PositionCursor ();
  666. return base.OnEnter (view);
  667. }
  668. public override void Redraw (Rect bounds)
  669. {
  670. base.Redraw (bounds);
  671. DrawSplitterSymbol ();
  672. }
  673. public void DrawSplitterSymbol ()
  674. {
  675. if (CanFocus && HasFocus) {
  676. var location = moveRuneRenderLocation ??
  677. new Point (Bounds.Width / 2, Bounds.Height / 2);
  678. AddRune (location.X, location.Y, Driver.Diamond);
  679. }
  680. }
  681. public override bool MouseEvent (MouseEvent mouseEvent)
  682. {
  683. if (!CanFocus) {
  684. return true;
  685. }
  686. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed)) {
  687. // Start a Drag
  688. SetFocus ();
  689. Application.EnsuresTopOnFront ();
  690. if (mouseEvent.Flags == MouseFlags.Button1Pressed) {
  691. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  692. dragOrignalPos = Orientation == Orientation.Horizontal ? Y : X;
  693. Application.GrabMouse (this);
  694. if (Orientation == Orientation.Horizontal) {
  695. } else {
  696. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  697. }
  698. }
  699. return true;
  700. } else if (
  701. dragPosition.HasValue &&
  702. (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  703. // Continue Drag
  704. // how far has user dragged from original location?
  705. if (Orientation == Orientation.Horizontal) {
  706. int dy = mouseEvent.Y - dragPosition.Value.Y;
  707. Parent.SetSplitterPos (Idx, Offset (Y, dy));
  708. moveRuneRenderLocation = new Point (mouseEvent.X, 0);
  709. } else {
  710. int dx = mouseEvent.X - dragPosition.Value.X;
  711. Parent.SetSplitterPos (Idx, Offset (X, dx));
  712. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  713. }
  714. Parent.SetNeedsDisplay ();
  715. return true;
  716. }
  717. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  718. // End Drag
  719. Application.UngrabMouse ();
  720. Driver.UncookMouse ();
  721. FinalisePosition (
  722. dragOrignalPos,
  723. Orientation == Orientation.Horizontal ? Y : X);
  724. dragPosition = null;
  725. moveRuneRenderLocation = null;
  726. }
  727. return false;
  728. }
  729. private bool MoveSplitter (int distanceX, int distanceY)
  730. {
  731. if (Orientation == Orientation.Vertical) {
  732. // Cannot move in this direction
  733. if (distanceX == 0) {
  734. return false;
  735. }
  736. var oldX = X;
  737. return FinalisePosition (oldX, Offset (X, distanceX));
  738. } else {
  739. // Cannot move in this direction
  740. if (distanceY == 0) {
  741. return false;
  742. }
  743. var oldY = Y;
  744. return FinalisePosition (oldY, (Pos)Offset (Y, distanceY));
  745. }
  746. }
  747. private Pos Offset (Pos pos, int delta)
  748. {
  749. var posAbsolute = pos.Anchor (Orientation == Orientation.Horizontal ?
  750. Parent.Bounds.Height : Parent.Bounds.Width);
  751. return posAbsolute + delta;
  752. }
  753. /// <summary>
  754. /// <para>
  755. /// Moves <see cref="Parent"/> <see cref="TileView.SplitterDistances"/> to
  756. /// <see cref="Pos"/> <paramref name="newValue"/> preserving <see cref="Pos"/> format
  757. /// (absolute / relative) that <paramref name="oldValue"/> had.
  758. /// </para>
  759. /// <remarks>This ensures that if splitter location was e.g. 50% before and you move it
  760. /// to absolute 5 then you end up with 10% (assuming a parent had 50 width). </remarks>
  761. /// </summary>
  762. /// <param name="oldValue"></param>
  763. /// <param name="newValue"></param>
  764. private bool FinalisePosition (Pos oldValue, Pos newValue)
  765. {
  766. if (oldValue is Pos.PosFactor) {
  767. if (Orientation == Orientation.Horizontal) {
  768. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Height));
  769. } else {
  770. return Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Width));
  771. }
  772. } else {
  773. return Parent.SetSplitterPos (Idx, newValue);
  774. }
  775. }
  776. /// <summary>
  777. /// <para>
  778. /// Determines the absolute position of <paramref name="p"/> and
  779. /// returns a <see cref="Pos.PosFactor"/> that describes the percentage of that.
  780. /// </para>
  781. /// <para>Effectively turning any <see cref="Pos"/> into a <see cref="Pos.PosFactor"/>
  782. /// (as if created with <see cref="Pos.Percent(float)"/>)</para>
  783. /// </summary>
  784. /// <param name="p">The <see cref="Pos"/> to convert to <see cref="Pos.Percent(float)"/></param>
  785. /// <param name="parentLength">The Height/Width that <paramref name="p"/> lies within</param>
  786. /// <returns></returns>
  787. private Pos ConvertToPosFactor (Pos p, int parentLength)
  788. {
  789. // calculate position in the 'middle' of the cell at p distance along parentLength
  790. float position = p.Anchor (parentLength) + 0.5f;
  791. return new Pos.PosFactor (position / parentLength);
  792. }
  793. }
  794. private bool HasBorder ()
  795. {
  796. return IntegratedBorder != BorderStyle.None;
  797. }
  798. }
  799. /// <summary>
  800. /// Provides data for <see cref="TileView"/> events.
  801. /// </summary>
  802. public class SplitterEventArgs : EventArgs {
  803. /// <summary>
  804. /// Creates a new instance of the <see cref="SplitterEventArgs"/> class.
  805. /// </summary>
  806. /// <param name="tileView"><see cref="TileView"/> in which splitter is being moved.</param>
  807. /// <param name="idx">Index of the splitter being moved in <see cref="TileView.SplitterDistances"/>.</param>
  808. /// <param name="splitterDistance">The new <see cref="Pos"/> of the splitter line.</param>
  809. public SplitterEventArgs (TileView tileView, int idx, Pos splitterDistance)
  810. {
  811. SplitterDistance = splitterDistance;
  812. TileView = tileView;
  813. Idx = idx;
  814. }
  815. /// <summary>
  816. /// New position of the splitter line (see <see cref="TileView.SplitterDistances"/>).
  817. /// </summary>
  818. public Pos SplitterDistance { get; }
  819. /// <summary>
  820. /// Container (sender) of the event.
  821. /// </summary>
  822. public TileView TileView { get; }
  823. /// <summary>
  824. /// Gets the index of the splitter that is being moved. This can be
  825. /// used to index <see cref="TileView.SplitterDistances"/>
  826. /// </summary>
  827. public int Idx { get; }
  828. }
  829. /// <summary>
  830. /// Represents a method that will handle splitter events.
  831. /// </summary>
  832. public delegate void SplitterEventHandler (object sender, SplitterEventArgs e);
  833. }