2
0

TileView.cs 30 KB

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