TileView.cs 28 KB

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