TileView.cs 32 KB

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