TileView.cs 30 KB

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