TileView.cs 27 KB

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