TileView.cs 30 KB

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