TileView.cs 30 KB

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