TileView.cs 26 KB

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