TileView.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Terminal.Gui.Graphs;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// A <see cref="View"/> consisting of a moveable bar that divides
  8. /// the display area into resizeable <see cref="Tiles"/>.
  9. /// </summary>
  10. public class TileView : View {
  11. TileView parentTileView;
  12. /// <summary>
  13. /// Use this field instead of Border to create an integrated
  14. /// Border in which lines connect with subviews and splitters
  15. /// seamlessly
  16. /// </summary>
  17. public BorderStyle IntegratedBorder { get; set; }
  18. /// <summary>
  19. /// A single <see cref="View"/> 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="View"/> that is showing in this <see cref="TileView"/>.
  26. /// You should add new child views to this member if you want multiple
  27. /// <see cref="View"/> within the <see cref="Tile"/>.
  28. /// </summary>
  29. public View View { 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="View"/>. 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 if there is no
  41. /// <see cref="TileView.IntegratedBorder"/> to render into.
  42. ///</remarks>
  43. public string Title { get; set; }
  44. /// <summary>
  45. /// Creates a new instance of the <see cref="Tile"/> class.
  46. /// </summary>
  47. internal Tile ()
  48. {
  49. View = new View () { Width = Dim.Fill (), Height = Dim.Fill () };
  50. Title = string.Empty;
  51. MinSize = 0;
  52. }
  53. }
  54. List<Tile> tiles;
  55. private List<Pos> splitterDistances;
  56. private List<TileViewLineView> splitterLines;
  57. /// <summary>
  58. /// The sub sections hosted by the view
  59. /// </summary>
  60. public IReadOnlyCollection<Tile> Tiles => tiles.AsReadOnly ();
  61. /// <summary>
  62. /// The splitter locations. Note that there will be N-1 splitters where
  63. /// N is the number of <see cref="Tiles"/>.
  64. /// </summary>
  65. public IReadOnlyCollection<Pos> SplitterDistances => splitterDistances.AsReadOnly ();
  66. private Orientation orientation = Orientation.Vertical;
  67. /// <summary>
  68. /// Creates a new instance of the <see cref="TileView"/> class with
  69. /// 2 tiles (i.e. left and right).
  70. /// </summary>
  71. public TileView () : this (2)
  72. {
  73. }
  74. /// <summary>
  75. /// Creates a new instance of the <see cref="TileView"/> class with
  76. /// <paramref name="tiles"/> number of tiles.
  77. /// </summary>
  78. /// <param name="tiles"></param>
  79. public TileView (int tiles)
  80. {
  81. CanFocus = true;
  82. RebuildForTileCount (tiles);
  83. }
  84. /// <summary>
  85. /// Invoked when any of the <see cref="SplitterDistances"/> is changed.
  86. /// </summary>
  87. public event SplitterEventHandler SplitterMoved;
  88. /// <summary>
  89. /// Raises the <see cref="SplitterMoved"/> event
  90. /// </summary>
  91. protected virtual void OnSplitterMoved (int idx)
  92. {
  93. SplitterMoved?.Invoke (this, new SplitterEventArgs (this, idx, splitterDistances [idx]));
  94. }
  95. /// <summary>
  96. /// Scraps all <see cref="Tiles"/> and creates <paramref name="count"/> new tiles
  97. /// in orientation <see cref="Orientation"/>
  98. /// </summary>
  99. /// <param name="count"></param>
  100. public void RebuildForTileCount (int count)
  101. {
  102. tiles = new List<Tile> ();
  103. splitterDistances = new List<Pos> ();
  104. splitterLines = new List<TileViewLineView> ();
  105. RemoveAll ();
  106. tiles.Clear ();
  107. splitterDistances.Clear ();
  108. if (count == 0) {
  109. return;
  110. }
  111. for (int i = 0; i < count; i++) {
  112. if (i > 0) {
  113. var currentPos = Pos.Percent ((100 / count) * i);
  114. splitterDistances.Add (currentPos);
  115. var line = new TileViewLineView (this, i - 1);
  116. Add (line);
  117. splitterLines.Add (line);
  118. }
  119. var tile = new Tile ();
  120. tiles.Add (tile);
  121. Add (tile.View);
  122. }
  123. LayoutSubviews ();
  124. }
  125. /// <summary>
  126. /// Adds a new <see cref="Tile"/> to the collection at <paramref name="idx"/>.
  127. /// This will also add another splitter line
  128. /// </summary>
  129. /// <param name="idx"></param>
  130. /// <exception cref="NotImplementedException"></exception>
  131. public Tile InsertTile (int idx)
  132. {
  133. var oldTiles = Tiles.ToArray ();
  134. RebuildForTileCount (oldTiles.Length + 1);
  135. Tile toReturn = null;
  136. for(int i=0;i<tiles.Count;i++) {
  137. if(i != idx) {
  138. var oldTile = oldTiles [i > idx ? i - 1 : i];
  139. // remove the new empty View
  140. Remove (tiles [i].View);
  141. // restore old Tile and View
  142. tiles [i] = oldTile;
  143. Add (tiles [i].View);
  144. }
  145. else
  146. {
  147. toReturn = tiles[i];
  148. }
  149. }
  150. SetNeedsDisplay ();
  151. LayoutSubviews ();
  152. return toReturn;
  153. }
  154. /// <summary>
  155. /// Removes a <see cref="Tiles"/> at the provided <paramref name="idx"/> from
  156. /// the view. Returns the removed tile or null if already empty.
  157. /// </summary>
  158. /// <param name="idx"></param>
  159. /// <returns></returns>
  160. public Tile RemoveTile (int idx)
  161. {
  162. var oldTiles = Tiles.ToArray ();
  163. if (idx < 0 || idx >= oldTiles.Length) {
  164. return null;
  165. }
  166. var removed = Tiles.ElementAt (idx);
  167. RebuildForTileCount (oldTiles.Length - 1);
  168. for (int i = 0; i < tiles.Count; i++) {
  169. int oldIdx = i >= idx ? i + 1: i;
  170. var oldTile = oldTiles [oldIdx];
  171. // remove the new empty View
  172. Remove (tiles [i].View);
  173. // restore old Tile and View
  174. tiles [i] = oldTile;
  175. Add (tiles [i].View);
  176. }
  177. SetNeedsDisplay ();
  178. LayoutSubviews ();
  179. return removed;
  180. }
  181. ///<summary>
  182. /// Returns the index of the first <see cref="Tile"/> in
  183. /// <see cref="Tiles"/> which contains <paramref name="toFind"/>.
  184. ///</summary>
  185. public int IndexOf(View toFind, bool recursive = false)
  186. {
  187. for(int i = 0 ;i < tiles.Count; i++)
  188. {
  189. var v = tiles[i].View;
  190. if(v == toFind)
  191. {
  192. return i;
  193. }
  194. if(v.Subviews.Contains(toFind))
  195. {
  196. return i;
  197. }
  198. if(recursive)
  199. {
  200. if(RecursiveContains(v.Subviews,toFind))
  201. {
  202. return i;
  203. }
  204. }
  205. }
  206. return -1;
  207. }
  208. private bool RecursiveContains (IEnumerable<View> haystack, View needle)
  209. {
  210. foreach(var v in haystack)
  211. {
  212. if(v == needle)
  213. {
  214. return true;
  215. }
  216. if(RecursiveContains(v.Subviews,needle))
  217. {
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. /// <summary>
  224. /// Orientation of the dividing line (Horizontal or Vertical).
  225. /// </summary>
  226. public Orientation Orientation {
  227. get { return orientation; }
  228. set {
  229. orientation = value;
  230. LayoutSubviews ();
  231. }
  232. }
  233. /// <inheritdoc/>
  234. public override void LayoutSubviews ()
  235. {
  236. var contentArea = Bounds;
  237. if (HasBorder ()) {
  238. // TODO: Bound with Max/Min
  239. contentArea = new Rect (
  240. contentArea.X + 1,
  241. contentArea.Y + 1,
  242. Math.Max (0, contentArea.Width - 2),
  243. Math.Max (0, contentArea.Height - 2));
  244. }
  245. Setup (contentArea);
  246. base.LayoutSubviews ();
  247. }
  248. /// <summary>
  249. /// <para>Distance Horizontally or Vertically to the splitter line when
  250. /// neither view is collapsed.
  251. /// </para>
  252. /// <para>Only absolute values (e.g. 10) and percent values (i.e. <see cref="Pos.Percent(float)"/>)
  253. /// are supported for this property.</para>
  254. /// </summary>
  255. public void SetSplitterPos (int idx, Pos value)
  256. {
  257. if (!(value is Pos.PosAbsolute) && !(value is Pos.PosFactor)) {
  258. throw new ArgumentException ($"Only Percent and Absolute values are supported. Passed value was {value.GetType ().Name}");
  259. }
  260. splitterDistances [idx] = value;
  261. GetRootTileView ().LayoutSubviews ();
  262. OnSplitterMoved (idx);
  263. }
  264. /// <inheritdoc/>
  265. public override bool OnEnter (View view)
  266. {
  267. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  268. return base.OnEnter (view);
  269. }
  270. /// <inheritdoc/>
  271. public override void Redraw (Rect bounds)
  272. {
  273. // TODO: We are getting passed stale bounds, does this only happen in TileView
  274. // or is it a larger problem? This line should not be required right?
  275. bounds = Bounds;
  276. Driver.SetAttribute (ColorScheme.Normal);
  277. Clear ();
  278. base.Redraw (bounds);
  279. var lc = new LineCanvas ();
  280. var allLines = GetAllLineViewsRecursively (this);
  281. var allTitlesToRender = GetAllTitlesToRenderRecursively(this);
  282. if (IsRootTileView ()) {
  283. if (HasBorder ()) {
  284. lc.AddLine (new Point (0, 0), bounds.Width - 1, Orientation.Horizontal, IntegratedBorder);
  285. lc.AddLine (new Point (0, 0), bounds.Height - 1, Orientation.Vertical, IntegratedBorder);
  286. lc.AddLine (new Point (bounds.Width - 1, bounds.Height - 1), -bounds.Width + 1, Orientation.Horizontal, IntegratedBorder);
  287. lc.AddLine (new Point (bounds.Width - 1, bounds.Height - 1), -bounds.Height + 1, Orientation.Vertical, IntegratedBorder);
  288. }
  289. foreach (var line in allLines.Where (l => l.Visible)) {
  290. bool isRoot = splitterLines.Contains (line);
  291. line.ViewToScreen (0, 0, out var x1, out var y1);
  292. var origin = ScreenToView (x1, y1);
  293. var length = line.Orientation == Orientation.Horizontal ?
  294. line.Frame.Width - 1 :
  295. line.Frame.Height - 1;
  296. if (!isRoot) {
  297. if (line.Orientation == Orientation.Horizontal) {
  298. origin.X -= 1;
  299. } else {
  300. origin.Y -= 1;
  301. }
  302. length += 2;
  303. }
  304. lc.AddLine (origin, length, line.Orientation, IntegratedBorder);
  305. }
  306. }
  307. Driver.SetAttribute (ColorScheme.Normal);
  308. lc.Draw (this, bounds);
  309. // Redraw the lines so that focus/drag symbol renders
  310. foreach (var line in allLines) {
  311. line.DrawSplitterSymbol ();
  312. }
  313. // Draw Titles over Border
  314. foreach(var titleToRender in allTitlesToRender)
  315. {
  316. var renderAt = titleToRender.GetLocalCoordinateForTitle(this);
  317. if(renderAt.Y < 0)
  318. {
  319. // If we have no border then root level tiles
  320. // have nowhere to render their titles.
  321. continue;
  322. }
  323. // TODO: Render with focus color if focused
  324. var title = titleToRender.Tile.Title;
  325. for(int i=0;i<title.Length;i++)
  326. {
  327. AddRune(renderAt.X+i,renderAt.Y,title[i]);
  328. }
  329. }
  330. }
  331. /// <summary>
  332. /// Converts <see cref="Tile.View"/> of <see cref="Tiles"/> element <paramref name="idx"/>
  333. /// from a regular <see cref="View"/> to a new nested <see cref="TileView"/> with <paramref name="panels"/>
  334. /// number of panels. Returns false if the element already contains a nested view.
  335. /// </summary>
  336. /// <remarks>After successful splitting, the <paramref name="result"/> <see cref="TileView"/>
  337. /// will contain the previous (replaced) <see cref="Tile.View"/> at element 0.</remarks>
  338. /// <param name="idx">The element of <see cref="Tiles"/> that is to be subdivided.</param>
  339. /// <param name="panels">The number of panels that the <see cref="Tile"/> should be split into</param>
  340. /// <param name="result">The new nested <see cref="TileView"/>.</param>
  341. /// <returns><see langword="true"/> if a <see cref="View"/> was converted to a new nested
  342. /// <see cref="TileView"/>. <see langword="false"/> if it was already a nested
  343. /// <see cref="TileView"/></returns>
  344. public bool TrySplitTile(int idx, int panels, out TileView result)
  345. {
  346. // when splitting a view into 2 sub views we will need to migrate
  347. // the title too
  348. var tile = tiles [idx];
  349. // TODO: migrate the title too right?
  350. var title = tile.Title;
  351. View toMove = tile.View;
  352. if (toMove is TileView existing) {
  353. result = existing;
  354. return false;
  355. }
  356. var newContainer = new TileView(panels) {
  357. Width = Dim.Fill (),
  358. Height = Dim.Fill (),
  359. parentTileView = this,
  360. };
  361. // Take everything out of the View we are moving
  362. var childViews = toMove.Subviews.ToArray();
  363. toMove.RemoveAll ();
  364. // Remove the view itself and replace it with the new TileView
  365. Remove (toMove);
  366. Add (newContainer);
  367. tile.View = newContainer;
  368. var newTileView1 = newContainer.tiles [0].View;
  369. // Add the original content into the first view of the new container
  370. foreach (var childView in childViews) {
  371. newTileView1.Add (childView);
  372. }
  373. result = newContainer;
  374. return true;
  375. }
  376. private List<TileViewLineView> GetAllLineViewsRecursively (View v)
  377. {
  378. var lines = new List<TileViewLineView> ();
  379. foreach (var sub in v.Subviews) {
  380. if (sub is TileViewLineView s) {
  381. if (s.Parent.GetRootTileView () == this) {
  382. lines.Add (s);
  383. }
  384. } else {
  385. lines.AddRange (GetAllLineViewsRecursively (sub));
  386. }
  387. }
  388. return lines;
  389. }
  390. private List<TileTitleToRender> GetAllTitlesToRenderRecursively (TileView v, int depth = 0)
  391. {
  392. var titles = new List<TileTitleToRender> ();
  393. foreach (var sub in v.Tiles) {
  394. // Don't render titles for invisible stuff!
  395. if(!sub.View.Visible)
  396. {
  397. continue;
  398. }
  399. if(sub.View is TileView subTileView)
  400. {
  401. // Panels with sub split tiles in them can never
  402. // have their Titles rendered. Instead we dive in
  403. // and pull up their children as titles
  404. titles.AddRange (GetAllTitlesToRenderRecursively (subTileView,depth+1));
  405. }
  406. else
  407. {
  408. if(sub.Title.Length > 0)
  409. {
  410. titles.Add(new TileTitleToRender(sub,depth));
  411. }
  412. }
  413. }
  414. return titles;
  415. }
  416. /// <summary>
  417. /// <para>
  418. /// <see langword="true"/> if <see cref="TileView"/> is nested within a parent <see cref="TileView"/>
  419. /// e.g. via the <see cref="TrySplitTile"/>. <see langword="false"/> if it is a root level <see cref="TileView"/>.
  420. /// </para>
  421. /// </summary>
  422. /// <remarks>Note that manually adding one <see cref="TileView"/> to another will not result in a parent/child
  423. /// relationship and both will still be considered 'root' containers. Always use
  424. /// <see cref="TrySplitTile(int, int, out TileView)"/> if you want to subdivide a <see cref="TileView"/>.</remarks>
  425. /// <returns></returns>
  426. public bool IsRootTileView ()
  427. {
  428. // TODO: don't want to layout subviews since the parent recursively lays them all out
  429. return parentTileView == null;
  430. }
  431. /// <summary>
  432. /// Returns the immediate parent <see cref="TileView"/> of this. Note that in case
  433. /// of deep nesting this might not be the root <see cref="TileView"/>. Returns null
  434. /// if this instance is not a nested child (created with
  435. /// <see cref="TrySplitTile(int, int, out TileView)"/>)
  436. /// </summary>
  437. /// <remarks>
  438. /// Use <see cref="IsRootTileView"/> to determine if the returned value is the root.
  439. /// </remarks>
  440. /// <returns></returns>
  441. public TileView GetParentTileView ()
  442. {
  443. return this.parentTileView;
  444. }
  445. private TileView GetRootTileView ()
  446. {
  447. TileView root = this;
  448. while (root.parentTileView != null) {
  449. root = root.parentTileView;
  450. }
  451. return root;
  452. }
  453. private void Setup (Rect bounds)
  454. {
  455. if (bounds.IsEmpty || bounds.Height <= 0 || bounds.Width <= 0) {
  456. return;
  457. }
  458. RespectMinimumTileSizes ();
  459. for (int i = 0; i < splitterLines.Count; i++) {
  460. var line = splitterLines[i];
  461. line.Orientation = Orientation;
  462. line.Width = orientation == Orientation.Vertical
  463. ? 1 : Dim.Fill ();
  464. line.Height = orientation == Orientation.Vertical
  465. ? Dim.Fill () : 1;
  466. line.LineRune = orientation == Orientation.Vertical ?
  467. Driver.VLine : Driver.HLine;
  468. if (orientation == Orientation.Vertical) {
  469. line.X = splitterDistances [i];
  470. line.Y = 0;
  471. }
  472. else {
  473. line.Y = splitterDistances [i];
  474. line.X = 0;
  475. }
  476. }
  477. for (int i = 0; i < tiles.Count; i++) {
  478. var tile = tiles [i];
  479. // TODO: Deal with lines being Visibility false
  480. if (Orientation == Orientation.Vertical) {
  481. tile.View.X = i == 0 ? bounds.X : Pos.Right (splitterLines [i - 1]);
  482. tile.View.Y = bounds.Y;
  483. tile.View.Height = bounds.Height;
  484. tile.View.Width = GetTileWidthOrHeight(i, Bounds.Width);
  485. } else {
  486. tile.View.X = bounds.X;
  487. tile.View.Y = i == 0 ? 0 : Pos.Bottom (splitterLines [i - 1]);
  488. tile.View.Width = bounds.Width;
  489. tile.View.Height = GetTileWidthOrHeight(i, Bounds.Height);
  490. }
  491. }
  492. }
  493. private Dim GetTileWidthOrHeight (int i, int space)
  494. {
  495. // last tile
  496. if(i + 1 >= tiles.Count)
  497. {
  498. return Dim.Fill (HasBorder () ? 1 : 0);
  499. }
  500. var nextSplitter = splitterDistances [i].Anchor (space);
  501. var lastSplitter = i >= 1 ? splitterDistances [i-1].Anchor (space) : 0;
  502. var distance = nextSplitter - lastSplitter;
  503. if(i>0) {
  504. return distance - 1;
  505. }
  506. return distance - (HasBorder() ? 1 : 0);
  507. }
  508. private void RespectMinimumTileSizes ()
  509. {
  510. // if we are not yet initialized then we don't know
  511. // how big we are and therefore cannot sensibly calculate
  512. // how big the views will be with a given SplitterDistance
  513. if (!IsInitialized) {
  514. return;
  515. }
  516. // how much space is there?
  517. var availableSpace = Orientation == Orientation.Horizontal
  518. ? this.Bounds.Height
  519. : this.Bounds.Width;
  520. var fullSpace = availableSpace;
  521. var lastSplitterLocation = 0;
  522. for(int i=0;i< splitterDistances.Count; i++) {
  523. var splitterLocation = splitterDistances [i].Anchor(fullSpace);
  524. var availableLeft = splitterLocation - lastSplitterLocation;
  525. // Border steals space
  526. availableLeft -= HasBorder () && i == 0 ? 1 : 0;
  527. var availableRight = fullSpace - splitterLocation;
  528. // Border steals space
  529. availableRight -= HasBorder () && i == 0 ? 1 : 0;
  530. // Splitter line steals space
  531. availableRight--;
  532. // TODO: Test 3+ panel max/mins because this calculation is probably wrong
  533. var requiredLeft = tiles [i].MinSize;
  534. var requiredRight = tiles [i+1].MinSize;
  535. if (availableLeft < requiredLeft) {
  536. // There is not enough space for panel on left
  537. var insteadTake = requiredLeft + (HasBorder() ? 1 :0);
  538. // Don't take more than the available space in view
  539. insteadTake = Math.Max(0,Math.Min (fullSpace, insteadTake));
  540. splitterDistances [i] = insteadTake;
  541. splitterLocation = insteadTake;
  542. }
  543. else if (availableRight < requiredRight) {
  544. // There is not enough space for panel on right
  545. var insteadTake = fullSpace - (requiredRight + (HasBorder()?1:0));
  546. // leave 1 space for the splitter
  547. insteadTake --;
  548. insteadTake = Math.Max (0, Math.Min (fullSpace, insteadTake));
  549. splitterDistances [i] = insteadTake;
  550. splitterLocation = insteadTake;
  551. }
  552. availableSpace -= splitterLocation;
  553. lastSplitterLocation = splitterLocation;
  554. }
  555. }
  556. private class TileTitleToRender
  557. {
  558. public Tile Tile {get;}
  559. public int Depth {get;}
  560. public TileTitleToRender(Tile tile, int depth)
  561. {
  562. Tile = tile;
  563. Depth = depth;
  564. }
  565. /// <summary>
  566. /// Translates the <see cref="Tile"/> title location from its local
  567. /// coordinate space <paramref name="intoCoordinateSpace"/>.
  568. /// </summary>
  569. public Point GetLocalCoordinateForTitle(TileView intoCoordinateSpace)
  570. {
  571. Tile.View.ViewToScreen(0,0, out var screenCol, out var screenRow);
  572. screenRow--;
  573. return intoCoordinateSpace.ScreenToView(screenCol,screenRow);
  574. }
  575. }
  576. private class TileViewLineView : LineView {
  577. public TileView Parent { get; private set; }
  578. public int Idx { get; }
  579. Point? dragPosition;
  580. Pos dragOrignalPos;
  581. public Point? moveRuneRenderLocation;
  582. public TileViewLineView (TileView parent, int idx)
  583. {
  584. CanFocus = true;
  585. TabStop = true;
  586. this.Parent = parent;
  587. Idx = idx;
  588. base.AddCommand (Command.Right, () => {
  589. return MoveSplitter (1, 0);
  590. });
  591. base.AddCommand (Command.Left, () => {
  592. return MoveSplitter (-1, 0);
  593. });
  594. base.AddCommand (Command.LineUp, () => {
  595. return MoveSplitter (0, -1);
  596. });
  597. base.AddCommand (Command.LineDown, () => {
  598. return MoveSplitter (0, 1);
  599. });
  600. AddKeyBinding (Key.CursorRight, Command.Right);
  601. AddKeyBinding (Key.CursorLeft, Command.Left);
  602. AddKeyBinding (Key.CursorUp, Command.LineUp);
  603. AddKeyBinding (Key.CursorDown, Command.LineDown);
  604. }
  605. public override bool ProcessKey (KeyEvent kb)
  606. {
  607. if (!CanFocus || !HasFocus) {
  608. return base.ProcessKey (kb);
  609. }
  610. var result = InvokeKeybindings (kb);
  611. if (result != null)
  612. return (bool)result;
  613. return base.ProcessKey (kb);
  614. }
  615. public override void PositionCursor ()
  616. {
  617. base.PositionCursor ();
  618. var location = moveRuneRenderLocation ??
  619. new Point (Bounds.Width / 2, Bounds.Height / 2);
  620. Move (location.X, location.Y);
  621. }
  622. public override bool OnEnter (View view)
  623. {
  624. Driver.SetCursorVisibility (CursorVisibility.Default);
  625. PositionCursor ();
  626. return base.OnEnter (view);
  627. }
  628. public override void Redraw (Rect bounds)
  629. {
  630. base.Redraw (bounds);
  631. DrawSplitterSymbol ();
  632. }
  633. public void DrawSplitterSymbol ()
  634. {
  635. if (CanFocus && HasFocus) {
  636. var location = moveRuneRenderLocation ??
  637. new Point (Bounds.Width / 2, Bounds.Height / 2);
  638. AddRune (location.X, location.Y, Driver.Diamond);
  639. }
  640. }
  641. public override bool MouseEvent (MouseEvent mouseEvent)
  642. {
  643. if (!CanFocus) {
  644. return true;
  645. }
  646. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed)) {
  647. // Start a Drag
  648. SetFocus ();
  649. Application.EnsuresTopOnFront ();
  650. if (mouseEvent.Flags == MouseFlags.Button1Pressed) {
  651. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  652. dragOrignalPos = Orientation == Orientation.Horizontal ? Y : X;
  653. Application.GrabMouse (this);
  654. if (Orientation == Orientation.Horizontal) {
  655. } else {
  656. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  657. }
  658. }
  659. return true;
  660. } else if (
  661. dragPosition.HasValue &&
  662. (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))) {
  663. // Continue Drag
  664. // how far has user dragged from original location?
  665. if (Orientation == Orientation.Horizontal) {
  666. int dy = mouseEvent.Y - dragPosition.Value.Y;
  667. Parent.splitterDistances [Idx] = Offset (Y, dy);
  668. moveRuneRenderLocation = new Point (mouseEvent.X, 0);
  669. } else {
  670. int dx = mouseEvent.X - dragPosition.Value.X;
  671. Parent.splitterDistances [Idx] = Offset (X, dx);
  672. moveRuneRenderLocation = new Point (0, Math.Max (1, Math.Min (Bounds.Height - 2, mouseEvent.Y)));
  673. }
  674. Parent.SetNeedsDisplay ();
  675. return true;
  676. }
  677. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  678. // End Drag
  679. Application.UngrabMouse ();
  680. Driver.UncookMouse ();
  681. FinalisePosition (
  682. dragOrignalPos,
  683. Orientation == Orientation.Horizontal ? Y : X);
  684. dragPosition = null;
  685. moveRuneRenderLocation = null;
  686. }
  687. return false;
  688. }
  689. private bool MoveSplitter (int distanceX, int distanceY)
  690. {
  691. if (Orientation == Orientation.Vertical) {
  692. // Cannot move in this direction
  693. if (distanceX == 0) {
  694. return false;
  695. }
  696. var oldX = X;
  697. FinalisePosition (oldX, (Pos)Offset (X, distanceX));
  698. return true;
  699. } else {
  700. // Cannot move in this direction
  701. if (distanceY == 0) {
  702. return false;
  703. }
  704. var oldY = Y;
  705. FinalisePosition (oldY, (Pos)Offset (Y, distanceY));
  706. return true;
  707. }
  708. }
  709. private Pos Offset (Pos pos, int delta)
  710. {
  711. var posAbsolute = pos.Anchor (Orientation == Orientation.Horizontal ?
  712. Parent.Bounds.Height : Parent.Bounds.Width);
  713. return posAbsolute + delta;
  714. }
  715. /// <summary>
  716. /// <para>
  717. /// Moves <see cref="Parent"/> <see cref="TileView.SplitterDistances"/> to
  718. /// <see cref="Pos"/> <paramref name="newValue"/> preserving <see cref="Pos"/> format
  719. /// (absolute / relative) that <paramref name="oldValue"/> had.
  720. /// </para>
  721. /// <remarks>This ensures that if splitter location was e.g. 50% before and you move it
  722. /// to absolute 5 then you end up with 10% (assuming a parent had 50 width). </remarks>
  723. /// </summary>
  724. /// <param name="oldValue"></param>
  725. /// <param name="newValue"></param>
  726. private void FinalisePosition (Pos oldValue, Pos newValue)
  727. {
  728. if (oldValue is Pos.PosFactor) {
  729. if (Orientation == Orientation.Horizontal) {
  730. Parent.SetSplitterPos(Idx, ConvertToPosFactor (newValue, Parent.Bounds.Height));
  731. } else {
  732. Parent.SetSplitterPos (Idx, ConvertToPosFactor (newValue, Parent.Bounds.Width));
  733. }
  734. } else {
  735. Parent.SetSplitterPos (Idx, newValue);
  736. }
  737. }
  738. /// <summary>
  739. /// <para>
  740. /// Determines the absolute position of <paramref name="p"/> and
  741. /// returns a <see cref="Pos.PosFactor"/> that describes the percentage of that.
  742. /// </para>
  743. /// <para>Effectively turning any <see cref="Pos"/> into a <see cref="Pos.PosFactor"/>
  744. /// (as if created with <see cref="Pos.Percent(float)"/>)</para>
  745. /// </summary>
  746. /// <param name="p">The <see cref="Pos"/> to convert to <see cref="Pos.Percent(float)"/></param>
  747. /// <param name="parentLength">The Height/Width that <paramref name="p"/> lies within</param>
  748. /// <returns></returns>
  749. private Pos ConvertToPosFactor (Pos p, int parentLength)
  750. {
  751. // calculate position in the 'middle' of the cell at p distance along parentLength
  752. float position = p.Anchor (parentLength) + 0.5f;
  753. return new Pos.PosFactor (position / parentLength);
  754. }
  755. }
  756. private bool HasBorder ()
  757. {
  758. return IntegratedBorder != BorderStyle.None;
  759. }
  760. }
  761. /// <summary>
  762. /// Provides data for <see cref="TileView"/> events.
  763. /// </summary>
  764. public class SplitterEventArgs : EventArgs {
  765. /// <summary>
  766. /// Creates a new instance of the <see cref="SplitterEventArgs"/> class.
  767. /// </summary>
  768. /// <param name="tileView"><see cref="TileView"/> in which splitter is being moved.</param>
  769. /// <param name="idx">Index of the splitter being moved in <see cref="TileView.SplitterDistances"/>.</param>
  770. /// <param name="splitterDistance">The new <see cref="Pos"/> of the splitter line.</param>
  771. public SplitterEventArgs (TileView tileView, int idx, Pos splitterDistance)
  772. {
  773. SplitterDistance = splitterDistance;
  774. TileView = tileView;
  775. Idx = idx;
  776. }
  777. /// <summary>
  778. /// New position of the splitter line (see <see cref="TileView.SplitterDistances"/>).
  779. /// </summary>
  780. public Pos SplitterDistance { get; }
  781. /// <summary>
  782. /// Container (sender) of the event.
  783. /// </summary>
  784. public TileView TileView { get; }
  785. /// <summary>
  786. /// Gets the index of the splitter that is being moved. This can be
  787. /// used to index <see cref="TileView.SplitterDistances"/>
  788. /// </summary>
  789. public int Idx { get; }
  790. }
  791. /// <summary>
  792. /// Represents a method that will handle splitter events.
  793. /// </summary>
  794. public delegate void SplitterEventHandler (object sender, SplitterEventArgs e);
  795. }