TileView.cs 30 KB

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