TileView.cs 28 KB

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