TileView.cs 30 KB

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