TableView.cs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  1. using System.Data;
  2. namespace Terminal.Gui;
  3. /// <summary>Delegate for providing color to <see cref="TableView"/> cells based on the value being rendered</summary>
  4. /// <param name="args">Contains information about the cell for which color is needed</param>
  5. /// <returns></returns>
  6. public delegate ColorScheme CellColorGetterDelegate (CellColorGetterArgs args);
  7. /// <summary>Delegate for providing color for a whole row of a <see cref="TableView"/></summary>
  8. /// <param name="args"></param>
  9. /// <returns></returns>
  10. public delegate ColorScheme RowColorGetterDelegate (RowColorGetterArgs args);
  11. /// <summary>
  12. /// View for tabular data based on a <see cref="ITableSource"/>.
  13. /// <a href="../docs/tableview.md">See TableView Deep Dive for more information</a>.
  14. /// </summary>
  15. public class TableView : View
  16. {
  17. /// <summary>
  18. /// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
  19. /// </summary>
  20. public const int DefaultMaxCellWidth = 100;
  21. /// <summary>The default minimum cell width for <see cref="ColumnStyle.MinAcceptableWidth"/></summary>
  22. public const int DefaultMinAcceptableWidth = 100;
  23. // TODO: Update to use Key instead of KeyCode
  24. private KeyCode cellActivationKey = KeyCode.Enter;
  25. private int columnOffset;
  26. private int rowOffset;
  27. private Point? scrollLeftPoint;
  28. private Point? scrollRightPoint;
  29. private int selectedColumn;
  30. private int selectedRow;
  31. private TableStyle style = new ();
  32. private ITableSource table;
  33. /// <summary>Initializes a <see cref="TableView"/> class.</summary>
  34. /// <param name="table">The table to display in the control</param>
  35. public TableView (ITableSource table) : this () { Table = table; }
  36. /// <summary>
  37. /// Initializes a <see cref="TableView"/> class. Set the
  38. /// <see cref="Table"/> property to begin editing
  39. /// </summary>
  40. public TableView ()
  41. {
  42. CanFocus = true;
  43. CollectionNavigator = new TableCollectionNavigator (this);
  44. // Things this view knows how to do
  45. AddCommand (
  46. Command.Right,
  47. () => ChangeSelectionByOffsetWithReturn (1, 0));
  48. AddCommand (
  49. Command.Left,
  50. () => ChangeSelectionByOffsetWithReturn (-1, 0));
  51. AddCommand (
  52. Command.Up,
  53. () => ChangeSelectionByOffsetWithReturn (0, -1));
  54. AddCommand (
  55. Command.Down,
  56. () => ChangeSelectionByOffsetWithReturn (0, 1));
  57. AddCommand (
  58. Command.PageUp,
  59. () =>
  60. {
  61. PageUp (false);
  62. return true;
  63. }
  64. );
  65. AddCommand (
  66. Command.PageDown,
  67. () =>
  68. {
  69. PageDown (false);
  70. return true;
  71. }
  72. );
  73. AddCommand (
  74. Command.LeftStart,
  75. () =>
  76. {
  77. ChangeSelectionToStartOfRow (false);
  78. return true;
  79. }
  80. );
  81. AddCommand (
  82. Command.RightEnd,
  83. () =>
  84. {
  85. ChangeSelectionToEndOfRow (false);
  86. return true;
  87. }
  88. );
  89. AddCommand (
  90. Command.Start,
  91. () =>
  92. {
  93. ChangeSelectionToStartOfTable (false);
  94. return true;
  95. }
  96. );
  97. AddCommand (
  98. Command.End,
  99. () =>
  100. {
  101. ChangeSelectionToEndOfTable (false);
  102. return true;
  103. }
  104. );
  105. AddCommand (
  106. Command.RightExtend,
  107. () =>
  108. {
  109. ChangeSelectionByOffset (1, 0, true);
  110. return true;
  111. }
  112. );
  113. AddCommand (
  114. Command.LeftExtend,
  115. () =>
  116. {
  117. ChangeSelectionByOffset (-1, 0, true);
  118. return true;
  119. }
  120. );
  121. AddCommand (
  122. Command.UpExtend,
  123. () =>
  124. {
  125. ChangeSelectionByOffset (0, -1, true);
  126. return true;
  127. }
  128. );
  129. AddCommand (
  130. Command.DownExtend,
  131. () =>
  132. {
  133. ChangeSelectionByOffset (0, 1, true);
  134. return true;
  135. }
  136. );
  137. AddCommand (
  138. Command.PageUpExtend,
  139. () =>
  140. {
  141. PageUp (true);
  142. return true;
  143. }
  144. );
  145. AddCommand (
  146. Command.PageDownExtend,
  147. () =>
  148. {
  149. PageDown (true);
  150. return true;
  151. }
  152. );
  153. AddCommand (
  154. Command.LeftStartExtend,
  155. () =>
  156. {
  157. ChangeSelectionToStartOfRow (true);
  158. return true;
  159. }
  160. );
  161. AddCommand (
  162. Command.RightEndExtend,
  163. () =>
  164. {
  165. ChangeSelectionToEndOfRow (true);
  166. return true;
  167. }
  168. );
  169. AddCommand (
  170. Command.StartExtend,
  171. () =>
  172. {
  173. ChangeSelectionToStartOfTable (true);
  174. return true;
  175. }
  176. );
  177. AddCommand (
  178. Command.EndExtend,
  179. () =>
  180. {
  181. ChangeSelectionToEndOfTable (true);
  182. return true;
  183. }
  184. );
  185. AddCommand (
  186. Command.SelectAll,
  187. () =>
  188. {
  189. SelectAll ();
  190. return true;
  191. }
  192. );
  193. AddCommand (
  194. Command.Accept,
  195. () =>
  196. {
  197. // BUGBUG: This should return false if the event is not handled
  198. OnCellActivated (new CellActivatedEventArgs (Table, SelectedColumn, SelectedRow));
  199. return true;
  200. }
  201. );
  202. AddCommand (
  203. Command.Select, // was Command.ToggleChecked
  204. () =>
  205. {
  206. ToggleCurrentCellSelection ();
  207. return true;
  208. }
  209. );
  210. // Default keybindings for this view
  211. KeyBindings.Add (Key.CursorLeft, Command.Left);
  212. KeyBindings.Add (Key.CursorRight, Command.Right);
  213. KeyBindings.Add (Key.CursorUp, Command.Up);
  214. KeyBindings.Add (Key.CursorDown, Command.Down);
  215. KeyBindings.Add (Key.PageUp, Command.PageUp);
  216. KeyBindings.Add (Key.PageDown, Command.PageDown);
  217. KeyBindings.Add (Key.Home, Command.LeftStart);
  218. KeyBindings.Add (Key.End, Command.RightEnd);
  219. KeyBindings.Add (Key.Home.WithCtrl, Command.Start);
  220. KeyBindings.Add (Key.End.WithCtrl, Command.End);
  221. KeyBindings.Add (Key.CursorLeft.WithShift, Command.LeftExtend);
  222. KeyBindings.Add (Key.CursorRight.WithShift, Command.RightExtend);
  223. KeyBindings.Add (Key.CursorUp.WithShift, Command.UpExtend);
  224. KeyBindings.Add (Key.CursorDown.WithShift, Command.DownExtend);
  225. KeyBindings.Add (Key.PageUp.WithShift, Command.PageUpExtend);
  226. KeyBindings.Add (Key.PageDown.WithShift, Command.PageDownExtend);
  227. KeyBindings.Add (Key.Home.WithShift, Command.LeftStartExtend);
  228. KeyBindings.Add (Key.End.WithShift, Command.RightEndExtend);
  229. KeyBindings.Add (Key.Home.WithCtrl.WithShift, Command.StartExtend);
  230. KeyBindings.Add (Key.End.WithCtrl.WithShift, Command.EndExtend);
  231. KeyBindings.Add (Key.A.WithCtrl, Command.SelectAll);
  232. KeyBindings.Add (CellActivationKey, Command.Accept);
  233. KeyBindings.Add (Key.Space, Command.Select);
  234. }
  235. // TODO: Update to use Key instead of KeyCode
  236. /// <summary>The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.</summary>
  237. public KeyCode CellActivationKey
  238. {
  239. get => cellActivationKey;
  240. set
  241. {
  242. if (cellActivationKey != value)
  243. {
  244. if (KeyBindings.TryGet (cellActivationKey, out _))
  245. {
  246. KeyBindings.ReplaceKey (cellActivationKey, value);
  247. }
  248. else
  249. {
  250. KeyBindings.Add (value, Command.Accept);
  251. }
  252. cellActivationKey = value;
  253. }
  254. }
  255. }
  256. /// <summary>Navigator for cycling the selected item in the table by typing. Set to null to disable this feature.</summary>
  257. public CollectionNavigatorBase CollectionNavigator { get; set; }
  258. /// <summary>
  259. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering
  260. /// the view.
  261. /// </summary>
  262. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  263. public int ColumnOffset
  264. {
  265. get => columnOffset;
  266. //try to prevent this being set to an out of bounds column
  267. set
  268. {
  269. columnOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Columns - 1, value));
  270. SetNeedsDisplay ();
  271. }
  272. }
  273. /// <summary>True to select the entire row at once. False to select individual cells. Defaults to false</summary>
  274. public bool FullRowSelect { get; set; }
  275. /// <summary>
  276. /// The maximum number of characters to render in any given column. This prevents one long column from pushing
  277. /// out all the others
  278. /// </summary>
  279. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  280. /// <summary>The minimum number of characters to render in any given column.</summary>
  281. public int MinCellWidth { get; set; }
  282. /// <summary>True to allow regions to be selected</summary>
  283. /// <value></value>
  284. public bool MultiSelect { get; set; } = true;
  285. /// <summary>
  286. /// When <see cref="MultiSelect"/> is enabled this property contain all rectangles of selected cells. Rectangles
  287. /// describe column/rows selected in <see cref="Table"/> (not screen coordinates)
  288. /// </summary>
  289. /// <returns></returns>
  290. public Stack<TableSelection> MultiSelectedRegions { get; } = new ();
  291. /// <summary>The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/></summary>
  292. public string NullSymbol { get; set; } = "-";
  293. /// <summary>
  294. /// Vertical scroll offset. The index of the first row in <see cref="Table"/> to display in the first non header
  295. /// line of the control when rendering the view.
  296. /// </summary>
  297. public int RowOffset
  298. {
  299. get => rowOffset;
  300. set => rowOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Rows - 1, value));
  301. }
  302. /// <summary>The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected</summary>
  303. public int SelectedColumn
  304. {
  305. get => selectedColumn;
  306. set
  307. {
  308. int oldValue = selectedColumn;
  309. //try to prevent this being set to an out of bounds column
  310. selectedColumn = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Columns - 1, Math.Max (0, value));
  311. if (oldValue != selectedColumn)
  312. {
  313. OnSelectedCellChanged (
  314. new SelectedCellChangedEventArgs (
  315. Table,
  316. oldValue,
  317. SelectedColumn,
  318. SelectedRow,
  319. SelectedRow
  320. )
  321. );
  322. }
  323. }
  324. }
  325. /// <summary>The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected</summary>
  326. public int SelectedRow
  327. {
  328. get => selectedRow;
  329. set
  330. {
  331. int oldValue = selectedRow;
  332. selectedRow = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Rows - 1, Math.Max (0, value));
  333. if (oldValue != selectedRow)
  334. {
  335. OnSelectedCellChanged (
  336. new SelectedCellChangedEventArgs (
  337. Table,
  338. SelectedColumn,
  339. SelectedColumn,
  340. oldValue,
  341. selectedRow
  342. )
  343. );
  344. }
  345. }
  346. }
  347. /// <summary>
  348. /// The symbol to add after each cell value and header value to visually separate values (if not using vertical
  349. /// gridlines)
  350. /// </summary>
  351. public char SeparatorSymbol { get; set; } = ' ';
  352. /// <summary>Contains options for changing how the table is rendered</summary>
  353. public TableStyle Style
  354. {
  355. get => style;
  356. set
  357. {
  358. style = value;
  359. Update ();
  360. }
  361. }
  362. /// <summary>The data table to render in the view. Setting this property automatically updates and redraws the control.</summary>
  363. public ITableSource Table
  364. {
  365. get => table;
  366. set
  367. {
  368. table = value;
  369. Update ();
  370. }
  371. }
  372. /// <summary>
  373. /// This event is raised when a cell is activated e.g. by double-clicking or pressing
  374. /// <see cref="CellActivationKey"/>
  375. /// </summary>
  376. public event EventHandler<CellActivatedEventArgs> CellActivated;
  377. /// <summary>This event is raised when a cell is toggled (see <see cref="Command.Select"/></summary>
  378. public event EventHandler<CellToggledEventArgs> CellToggled;
  379. /// <summary>
  380. /// Returns the screen position (relative to the control client area) that the given cell is rendered or null if
  381. /// it is outside the current scroll area or no table is loaded
  382. /// </summary>
  383. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for</param>
  384. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  385. /// <returns></returns>
  386. public Point? CellToScreen (int tableColumn, int tableRow)
  387. {
  388. if (TableIsNullOrInvisible ())
  389. {
  390. return null;
  391. }
  392. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Viewport);
  393. int headerHeight = GetHeaderHeightIfAny ();
  394. ColumnToRender colHit = viewPort.FirstOrDefault (c => c.Column == tableColumn);
  395. // current column is outside the scroll area
  396. if (colHit is null)
  397. {
  398. return null;
  399. }
  400. // the cell is too far up above the current scroll area
  401. if (RowOffset > tableRow)
  402. {
  403. return null;
  404. }
  405. // the cell is way down below the scroll area and off the screen
  406. if (tableRow > RowOffset + (Viewport.Height - headerHeight))
  407. {
  408. return null;
  409. }
  410. return new Point (colHit.X, tableRow + headerHeight - RowOffset);
  411. }
  412. /// <summary>
  413. /// Private override of <see cref="ChangeSelectionByOffset"/> that returns true if the selection has
  414. /// changed as a result of moving the selection. Used by key handling logic to determine whether e.g.
  415. /// the cursor right resulted in a change or should be forwarded on to toggle logic handling.
  416. /// </summary>
  417. /// <param name="offsetX"></param>
  418. /// <param name="offsetY"></param>
  419. /// <returns></returns>
  420. private bool ChangeSelectionByOffsetWithReturn (int offsetX, int offsetY)
  421. {
  422. var oldSelection = GetSelectionSnapshot ();
  423. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, false);
  424. Update ();
  425. return !SelectionIsSame (oldSelection);
  426. }
  427. private TableViewSelectionSnapshot GetSelectionSnapshot ()
  428. {
  429. return new (
  430. SelectedColumn,
  431. SelectedRow,
  432. MultiSelectedRegions.Select (s => s.Rectangle).ToArray ());
  433. }
  434. private bool SelectionIsSame (TableViewSelectionSnapshot oldSelection)
  435. {
  436. var newSelection = GetSelectionSnapshot ();
  437. return oldSelection.SelectedColumn == newSelection.SelectedColumn
  438. && oldSelection.SelectedRow == newSelection.SelectedRow
  439. && oldSelection.multiSelection.SequenceEqual (newSelection.multiSelection);
  440. }
  441. private record TableViewSelectionSnapshot (int SelectedColumn, int SelectedRow, Rectangle [] multiSelection);
  442. /// <summary>
  443. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally
  444. /// starting a box selection (see <see cref="MultiSelect"/>)
  445. /// </summary>
  446. /// <param name="offsetX">Offset in number of columns</param>
  447. /// <param name="offsetY">Offset in number of rows</param>
  448. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  449. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  450. {
  451. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
  452. Update ();
  453. }
  454. /// <summary>Moves or extends the selection to the last cell in the current row</summary>
  455. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  456. public void ChangeSelectionToEndOfRow (bool extend)
  457. {
  458. SetSelection (Table.Columns - 1, SelectedRow, extend);
  459. Update ();
  460. }
  461. /// <summary>
  462. /// Moves or extends the selection to the final cell in the table (nX,nY). If <see cref="FullRowSelect"/> is
  463. /// enabled then selection instead moves to ( <see cref="SelectedColumn"/>,nY) i.e. no horizontal scrolling.
  464. /// </summary>
  465. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  466. public void ChangeSelectionToEndOfTable (bool extend)
  467. {
  468. int finalColumn = Table.Columns - 1;
  469. SetSelection (FullRowSelect ? SelectedColumn : finalColumn, Table.Rows - 1, extend);
  470. Update ();
  471. }
  472. /// <summary>Moves or extends the selection to the first cell in the current row</summary>
  473. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  474. public void ChangeSelectionToStartOfRow (bool extend)
  475. {
  476. SetSelection (0, SelectedRow, extend);
  477. Update ();
  478. }
  479. /// <summary>
  480. /// Moves or extends the selection to the first cell in the table (0,0). If <see cref="FullRowSelect"/> is enabled
  481. /// then selection instead moves to ( <see cref="SelectedColumn"/>,0) i.e. no horizontal scrolling.
  482. /// </summary>
  483. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  484. public void ChangeSelectionToStartOfTable (bool extend)
  485. {
  486. SetSelection (FullRowSelect ? SelectedColumn : 0, 0, extend);
  487. Update ();
  488. }
  489. /// <summary>
  490. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has
  491. /// not been set.
  492. /// </summary>
  493. /// <remarks>
  494. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/>
  495. /// </remarks>
  496. public void EnsureSelectedCellIsVisible ()
  497. {
  498. if (Table is null || Table.Columns <= 0)
  499. {
  500. return;
  501. }
  502. ColumnToRender [] columnsToRender = CalculateViewport (Viewport).ToArray ();
  503. int headerHeight = GetHeaderHeightIfAny ();
  504. //if we have scrolled too far to the left
  505. if (SelectedColumn < columnsToRender.Min (r => r.Column))
  506. {
  507. ColumnOffset = SelectedColumn;
  508. }
  509. //if we have scrolled too far to the right
  510. if (SelectedColumn > columnsToRender.Max (r => r.Column))
  511. {
  512. if (Style.SmoothHorizontalScrolling)
  513. {
  514. // Scroll right 1 column at a time until the users selected column is visible
  515. while (SelectedColumn > columnsToRender.Max (r => r.Column))
  516. {
  517. ColumnOffset++;
  518. columnsToRender = CalculateViewport (Viewport).ToArray ();
  519. // if we are already scrolled to the last column then break
  520. // this will prevent any theoretical infinite loop
  521. if (ColumnOffset >= Table.Columns - 1)
  522. {
  523. break;
  524. }
  525. }
  526. }
  527. else
  528. {
  529. ColumnOffset = SelectedColumn;
  530. }
  531. }
  532. //if we have scrolled too far down
  533. if (SelectedRow >= RowOffset + (Viewport.Height - headerHeight))
  534. {
  535. RowOffset = SelectedRow - (Viewport.Height - headerHeight) + 1;
  536. }
  537. //if we have scrolled too far up
  538. if (SelectedRow < RowOffset)
  539. {
  540. RowOffset = SelectedRow;
  541. }
  542. }
  543. /// <summary>
  544. /// Updates <see cref="ColumnOffset"/> and <see cref="RowOffset"/> where they are outside the bounds of the table
  545. /// (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  546. /// </summary>
  547. /// <remarks>
  548. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/>
  549. /// </remarks>
  550. public void EnsureValidScrollOffsets ()
  551. {
  552. if (TableIsNullOrInvisible ())
  553. {
  554. return;
  555. }
  556. ColumnOffset = Math.Max (Math.Min (ColumnOffset, Table.Columns - 1), 0);
  557. RowOffset = Math.Max (Math.Min (RowOffset, Table.Rows - 1), 0);
  558. }
  559. /// <summary>
  560. /// Updates <see cref="SelectedColumn"/>, <see cref="SelectedRow"/> and <see cref="MultiSelectedRegions"/> where
  561. /// they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if
  562. /// <see cref="Table"/> has not been set.
  563. /// </summary>
  564. /// <remarks>
  565. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/>
  566. /// </remarks>
  567. public void EnsureValidSelection ()
  568. {
  569. if (TableIsNullOrInvisible ())
  570. {
  571. // Table doesn't exist, we should probably clear those selections
  572. ClearMultiSelectedRegions (false);
  573. return;
  574. }
  575. SelectedColumn = Math.Max (Math.Min (SelectedColumn, Table.Columns - 1), 0);
  576. SelectedRow = Math.Max (Math.Min (SelectedRow, Table.Rows - 1), 0);
  577. // If SelectedColumn is invisible move it to a visible one
  578. SelectedColumn = GetNearestVisibleColumn (SelectedColumn, true, true);
  579. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  580. MultiSelectedRegions.Clear ();
  581. // evaluate
  582. foreach (TableSelection region in oldRegions)
  583. {
  584. // ignore regions entirely below current table state
  585. if (region.Rectangle.Top >= Table.Rows)
  586. {
  587. continue;
  588. }
  589. // ignore regions entirely too far right of table columns
  590. if (region.Rectangle.Left >= Table.Columns)
  591. {
  592. continue;
  593. }
  594. // ensure region's origin exists
  595. region.Origin = new Point (
  596. Math.Max (Math.Min (region.Origin.X, Table.Columns - 1), 0),
  597. Math.Max (Math.Min (region.Origin.Y, Table.Rows - 1), 0)
  598. );
  599. // ensure regions do not go over edge of table bounds
  600. region.Rectangle = Rectangle.FromLTRB (
  601. region.Rectangle.Left,
  602. region.Rectangle.Top,
  603. Math.Max (Math.Min (region.Rectangle.Right, Table.Columns), 0),
  604. Math.Max (Math.Min (region.Rectangle.Bottom, Table.Rows), 0)
  605. );
  606. MultiSelectedRegions.Push (region);
  607. }
  608. }
  609. /// <summary>
  610. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the
  611. /// selected cell
  612. /// </summary>
  613. /// <returns></returns>
  614. public IEnumerable<Point> GetAllSelectedCells ()
  615. {
  616. if (TableIsNullOrInvisible () || Table.Rows == 0)
  617. {
  618. return Enumerable.Empty<Point> ();
  619. }
  620. EnsureValidSelection ();
  621. HashSet<Point> toReturn = new ();
  622. // If there are one or more rectangular selections
  623. if (MultiSelect && MultiSelectedRegions.Any ())
  624. {
  625. // Quiz any cells for whether they are selected. For performance we only need to check those between the top left and lower right vertex of selection regions
  626. int yMin = MultiSelectedRegions.Min (r => r.Rectangle.Top);
  627. int yMax = MultiSelectedRegions.Max (r => r.Rectangle.Bottom);
  628. int xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rectangle.Left);
  629. int xMax = FullRowSelect ? Table.Columns : MultiSelectedRegions.Max (r => r.Rectangle.Right);
  630. for (int y = yMin; y < yMax; y++)
  631. {
  632. for (int x = xMin; x < xMax; x++)
  633. {
  634. if (IsSelected (x, y))
  635. {
  636. toReturn.Add (new Point (x, y));
  637. }
  638. }
  639. }
  640. }
  641. // if there are no region selections then it is just the active cell
  642. // if we are selecting the full row
  643. if (FullRowSelect)
  644. {
  645. // all cells in active row are selected
  646. for (var x = 0; x < Table.Columns; x++)
  647. {
  648. toReturn.Add (new Point (x, SelectedRow));
  649. }
  650. }
  651. else
  652. {
  653. // Not full row select and no multi selections
  654. toReturn.Add (new Point (SelectedColumn, SelectedRow));
  655. }
  656. return toReturn;
  657. }
  658. /// <summary>
  659. /// <para>
  660. /// Returns true if the given cell is selected either because it is the active cell or part of a multi cell
  661. /// selection (e.g. <see cref="FullRowSelect"/>).
  662. /// </para>
  663. /// <remarks>Returns <see langword="false"/> if <see cref="ColumnStyle.Visible"/> is <see langword="false"/>.</remarks>
  664. /// </summary>
  665. /// <param name="col"></param>
  666. /// <param name="row"></param>
  667. /// <returns></returns>
  668. public bool IsSelected (int col, int row)
  669. {
  670. if (!IsColumnVisible (col))
  671. {
  672. return false;
  673. }
  674. if (GetMultiSelectedRegionsContaining (col, row).Any ())
  675. {
  676. return true;
  677. }
  678. return row == SelectedRow && (col == SelectedColumn || FullRowSelect);
  679. }
  680. ///<inheritdoc/>
  681. protected internal override bool OnMouseEvent (MouseEvent me)
  682. {
  683. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  684. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  685. && me.Flags != MouseFlags.WheeledDown
  686. && me.Flags != MouseFlags.WheeledUp
  687. && me.Flags != MouseFlags.WheeledLeft
  688. && me.Flags != MouseFlags.WheeledRight)
  689. {
  690. return false;
  691. }
  692. if (!HasFocus && CanFocus)
  693. {
  694. SetFocus ();
  695. }
  696. if (TableIsNullOrInvisible ())
  697. {
  698. return false;
  699. }
  700. // Scroll wheel flags
  701. switch (me.Flags)
  702. {
  703. case MouseFlags.WheeledDown:
  704. RowOffset++;
  705. EnsureValidScrollOffsets ();
  706. SetNeedsDisplay ();
  707. return true;
  708. case MouseFlags.WheeledUp:
  709. RowOffset--;
  710. EnsureValidScrollOffsets ();
  711. SetNeedsDisplay ();
  712. return true;
  713. case MouseFlags.WheeledRight:
  714. ColumnOffset++;
  715. EnsureValidScrollOffsets ();
  716. SetNeedsDisplay ();
  717. return true;
  718. case MouseFlags.WheeledLeft:
  719. ColumnOffset--;
  720. EnsureValidScrollOffsets ();
  721. SetNeedsDisplay ();
  722. return true;
  723. }
  724. int boundsX = me.Position.X;
  725. int boundsY = me.Position.Y;
  726. if (me.Flags.HasFlag (MouseFlags.Button1Clicked))
  727. {
  728. if (scrollLeftPoint != null
  729. && scrollLeftPoint.Value.X == boundsX
  730. && scrollLeftPoint.Value.Y == boundsY)
  731. {
  732. ColumnOffset--;
  733. EnsureValidScrollOffsets ();
  734. SetNeedsDisplay ();
  735. }
  736. if (scrollRightPoint != null
  737. && scrollRightPoint.Value.X == boundsX
  738. && scrollRightPoint.Value.Y == boundsY)
  739. {
  740. ColumnOffset++;
  741. EnsureValidScrollOffsets ();
  742. SetNeedsDisplay ();
  743. }
  744. Point? hit = ScreenToCell (boundsX, boundsY);
  745. if (hit is { })
  746. {
  747. if (MultiSelect && HasControlOrAlt (me))
  748. {
  749. UnionSelection (hit.Value.X, hit.Value.Y);
  750. }
  751. else
  752. {
  753. SetSelection (hit.Value.X, hit.Value.Y, me.Flags.HasFlag (MouseFlags.ButtonShift));
  754. }
  755. Update ();
  756. }
  757. }
  758. // Double clicking a cell activates
  759. if (me.Flags == MouseFlags.Button1DoubleClicked)
  760. {
  761. Point? hit = ScreenToCell (boundsX, boundsY);
  762. if (hit is { })
  763. {
  764. OnCellActivated (new CellActivatedEventArgs (Table, hit.Value.X, hit.Value.Y));
  765. }
  766. }
  767. return base.OnMouseEvent (me);
  768. }
  769. ///<inheritdoc/>
  770. public override void OnDrawContent (Rectangle viewport)
  771. {
  772. base.OnDrawContent (viewport);
  773. Move (0, 0);
  774. scrollRightPoint = null;
  775. scrollLeftPoint = null;
  776. // What columns to render at what X offset in viewport
  777. ColumnToRender [] columnsToRender = CalculateViewport (Viewport).ToArray ();
  778. Driver?.SetAttribute (GetNormalColor ());
  779. //invalidate current row (prevents scrolling around leaving old characters in the frame
  780. Driver?.AddStr (new string (' ', Viewport.Width));
  781. var line = 0;
  782. if (ShouldRenderHeaders ())
  783. {
  784. // Render something like:
  785. /*
  786. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  787. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  788. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  789. */
  790. if (Style.ShowHorizontalHeaderOverline)
  791. {
  792. RenderHeaderOverline (line, Viewport.Width, columnsToRender);
  793. line++;
  794. }
  795. if (Style.ShowHeaders)
  796. {
  797. RenderHeaderMidline (line, columnsToRender);
  798. line++;
  799. }
  800. if (Style.ShowHorizontalHeaderUnderline)
  801. {
  802. RenderHeaderUnderline (line, Viewport.Width, columnsToRender);
  803. line++;
  804. }
  805. }
  806. int headerLinesConsumed = line;
  807. //render the cells
  808. for (; line < Viewport.Height; line++)
  809. {
  810. ClearLine (line, Viewport.Width);
  811. //work out what Row to render
  812. int rowToRender = RowOffset + (line - headerLinesConsumed);
  813. //if we have run off the end of the table
  814. if (TableIsNullOrInvisible () || rowToRender < 0)
  815. {
  816. continue;
  817. }
  818. // No more data
  819. if (rowToRender >= Table.Rows)
  820. {
  821. if (rowToRender == Table.Rows && Style.ShowHorizontalBottomline)
  822. {
  823. RenderBottomLine (line, Viewport.Width, columnsToRender);
  824. }
  825. continue;
  826. }
  827. RenderRow (line, rowToRender, columnsToRender);
  828. }
  829. }
  830. /// <inheritdoc/>
  831. public override bool OnProcessKeyDown (Key keyEvent)
  832. {
  833. if (TableIsNullOrInvisible ())
  834. {
  835. return false;
  836. }
  837. if (CollectionNavigator != null
  838. && HasFocus
  839. && Table.Rows != 0
  840. && CollectionNavigatorBase.IsCompatibleKey (keyEvent)
  841. && !keyEvent.KeyCode.HasFlag (KeyCode.CtrlMask)
  842. && !keyEvent.KeyCode.HasFlag (KeyCode.AltMask)
  843. && Rune.IsLetterOrDigit ((Rune)keyEvent))
  844. {
  845. return CycleToNextTableEntryBeginningWith (keyEvent);
  846. }
  847. return false;
  848. }
  849. /// <summary>Moves the selection down by one page</summary>
  850. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  851. public void PageDown (bool extend)
  852. {
  853. ChangeSelectionByOffset (0, Viewport.Height - GetHeaderHeightIfAny (), extend);
  854. Update ();
  855. }
  856. /// <summary>Moves the selection up by one page</summary>
  857. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  858. public void PageUp (bool extend)
  859. {
  860. ChangeSelectionByOffset (0, -(Viewport.Height - GetHeaderHeightIfAny ()), extend);
  861. Update ();
  862. }
  863. /// <summary>
  864. /// Positions the cursor in the area of the screen in which the start of the active cell is rendered. Calls base
  865. /// implementation if active cell is not visible due to scrolling or table is loaded etc
  866. /// </summary>
  867. public override Point? PositionCursor ()
  868. {
  869. if (TableIsNullOrInvisible ())
  870. {
  871. return base.PositionCursor ();
  872. }
  873. Point? screenPoint = CellToScreen (SelectedColumn, SelectedRow);
  874. if (screenPoint is { })
  875. {
  876. Move (screenPoint.Value.X, screenPoint.Value.Y);
  877. return null;//screenPoint;
  878. }
  879. return null;
  880. }
  881. /// <summary>
  882. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  883. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  884. /// bounds.
  885. /// </summary>
  886. /// <param name="clientX">X offset from the top left of the control.</param>
  887. /// <param name="clientY">Y offset from the top left of the control.</param>
  888. /// <returns>Cell clicked or null.</returns>
  889. public Point? ScreenToCell (int clientX, int clientY) { return ScreenToCell (clientX, clientY, out _, out _); }
  890. /// <summary>
  891. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  892. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  893. /// bounds.
  894. /// </summary>
  895. /// <param name="client">offset from the top left of the control.</param>
  896. /// <returns>The position.</returns>
  897. public Point? ScreenToCell (Point client) { return ScreenToCell (client, out _, out _); }
  898. /// <summary>
  899. /// . Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  900. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  901. /// bounds.
  902. /// </summary>
  903. /// <param name="clientX">X offset from the top left of the control.</param>
  904. /// <param name="clientY">Y offset from the top left of the control.</param>
  905. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  906. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny) { return ScreenToCell (clientX, clientY, out headerIfAny, out _); }
  907. /// <summary>
  908. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  909. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  910. /// bounds.
  911. /// </summary>
  912. /// <param name="client">offset from the top left of the control.</param>
  913. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  914. public Point? ScreenToCell (Point client, out int? headerIfAny) { return ScreenToCell (client, out headerIfAny, out _); }
  915. /// <summary>
  916. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  917. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  918. /// bounds.
  919. /// </summary>
  920. /// <param name="clientX">X offset from the top left of the control.</param>
  921. /// <param name="clientY">Y offset from the top left of the control.</param>
  922. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  923. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  924. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny, out int? offsetX)
  925. {
  926. headerIfAny = null;
  927. offsetX = null;
  928. if (TableIsNullOrInvisible ())
  929. {
  930. return null;
  931. }
  932. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Viewport);
  933. int headerHeight = GetHeaderHeightIfAny ();
  934. ColumnToRender col = viewPort.LastOrDefault (c => c.X <= clientX);
  935. // Click is on the header section of rendered UI
  936. if (clientY < headerHeight)
  937. {
  938. headerIfAny = col?.Column;
  939. offsetX = col is { } ? clientX - col.X : null;
  940. return null;
  941. }
  942. int rowIdx = RowOffset - headerHeight + clientY;
  943. // if click is off bottom of the rows don't give an
  944. // invalid index back to user!
  945. if (rowIdx >= Table.Rows)
  946. {
  947. return null;
  948. }
  949. if (col is { } && rowIdx >= 0)
  950. {
  951. offsetX = clientX - col.X;
  952. return new Point (col.Column, rowIdx);
  953. }
  954. return null;
  955. }
  956. /// <summary>
  957. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  958. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  959. /// bounds.
  960. /// </summary>
  961. /// <param name="client">offset from the top left of the control.</param>
  962. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  963. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  964. public Point? ScreenToCell (Point client, out int? headerIfAny, out int? offsetX)
  965. {
  966. return ScreenToCell (client.X, client.Y, out headerIfAny, out offsetX);
  967. }
  968. /// <summary>
  969. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old
  970. /// selection regions)
  971. /// </summary>
  972. public void SelectAll ()
  973. {
  974. if (TableIsNullOrInvisible () || !MultiSelect || Table.Rows == 0)
  975. {
  976. return;
  977. }
  978. ClearMultiSelectedRegions (true);
  979. // Create a single region over entire table, set the origin of the selection to the active cell so that a followup spread selection e.g. shift-right behaves properly
  980. MultiSelectedRegions.Push (
  981. new TableSelection (
  982. new (SelectedColumn, SelectedRow),
  983. new (0, 0, Table.Columns, table.Rows)
  984. )
  985. );
  986. Update ();
  987. }
  988. /// <summary>This event is raised when the selected cell in the table changes.</summary>
  989. public event EventHandler<SelectedCellChangedEventArgs> SelectedCellChanged;
  990. /// <summary>
  991. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in
  992. /// <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  993. /// </summary>
  994. /// <param name="col"></param>
  995. /// <param name="row"></param>
  996. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  997. public void SetSelection (int col, int row, bool extendExistingSelection)
  998. {
  999. // if we are trying to increase the column index then
  1000. // we are moving right otherwise we are moving left
  1001. bool lookRight = col > selectedColumn;
  1002. col = GetNearestVisibleColumn (col, lookRight, true);
  1003. if (!MultiSelect || !extendExistingSelection)
  1004. {
  1005. ClearMultiSelectedRegions (true);
  1006. }
  1007. if (extendExistingSelection)
  1008. {
  1009. // If we are extending current selection but there isn't one
  1010. if (MultiSelectedRegions.Count == 0 || MultiSelectedRegions.All (m => m.IsToggled))
  1011. {
  1012. // Create a new region between the old active cell and the new cell
  1013. TableSelection rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  1014. MultiSelectedRegions.Push (rect);
  1015. }
  1016. else
  1017. {
  1018. // Extend the current head selection to include the new cell
  1019. TableSelection head = MultiSelectedRegions.Pop ();
  1020. TableSelection newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  1021. MultiSelectedRegions.Push (newRect);
  1022. }
  1023. }
  1024. SelectedColumn = col;
  1025. SelectedRow = row;
  1026. }
  1027. /// <summary>
  1028. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> /
  1029. /// <see cref="RowOffset"/>) etc
  1030. /// </summary>
  1031. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  1032. public void Update ()
  1033. {
  1034. if (!IsInitialized || TableIsNullOrInvisible ())
  1035. {
  1036. SetNeedsDisplay ();
  1037. return;
  1038. }
  1039. EnsureValidScrollOffsets ();
  1040. EnsureValidSelection ();
  1041. EnsureSelectedCellIsVisible ();
  1042. SetNeedsDisplay ();
  1043. }
  1044. /// <summary>Invokes the <see cref="CellActivated"/> event</summary>
  1045. /// <param name="args"></param>
  1046. protected virtual void OnCellActivated (CellActivatedEventArgs args) { CellActivated?.Invoke (this, args); }
  1047. /// <summary>Invokes the <see cref="CellToggled"/> event</summary>
  1048. /// <param name="args"></param>
  1049. protected virtual void OnCellToggled (CellToggledEventArgs args) { CellToggled?.Invoke (this, args); }
  1050. /// <summary>Invokes the <see cref="SelectedCellChanged"/> event</summary>
  1051. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args) { SelectedCellChanged?.Invoke (this, args); }
  1052. /// <summary>
  1053. /// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to with
  1054. /// <see cref="ConsoleDriver.AddStr(string)"/>. The driver will already be in the correct place when rendering and you
  1055. /// must render the full <paramref name="render"/> or the view will not look right. For simpler provision of color use
  1056. /// <see cref="ColumnStyle.ColorGetter"/> For changing the content that is rendered use
  1057. /// <see cref="ColumnStyle.RepresentationGetter"/>
  1058. /// </summary>
  1059. /// <param name="cellColor"></param>
  1060. /// <param name="render"></param>
  1061. /// <param name="isPrimaryCell"></param>
  1062. protected virtual void RenderCell (Attribute cellColor, string render, bool isPrimaryCell)
  1063. {
  1064. // If the cell is the selected col/row then draw the first rune in inverted colors
  1065. // this allows the user to track which cell is the active one during a multi cell
  1066. // selection or in full row select mode
  1067. if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell)
  1068. {
  1069. if (render.Length > 0)
  1070. {
  1071. // invert the color of the current cell for the first character
  1072. Driver.SetAttribute (new Attribute (cellColor.Background, cellColor.Foreground));
  1073. Driver.AddRune ((Rune)render [0]);
  1074. if (render.Length > 1)
  1075. {
  1076. Driver.SetAttribute (cellColor);
  1077. Driver.AddStr (render.Substring (1));
  1078. }
  1079. }
  1080. }
  1081. else
  1082. {
  1083. Driver.SetAttribute (cellColor);
  1084. Driver.AddStr (render);
  1085. }
  1086. }
  1087. /// <summary>Returns the amount of vertical space required to display the header</summary>
  1088. /// <returns></returns>
  1089. internal int GetHeaderHeight ()
  1090. {
  1091. int heightRequired = Style.ShowHeaders ? 1 : 0;
  1092. if (Style.ShowHorizontalHeaderOverline)
  1093. {
  1094. heightRequired++;
  1095. }
  1096. if (Style.ShowHorizontalHeaderUnderline)
  1097. {
  1098. heightRequired++;
  1099. }
  1100. return heightRequired;
  1101. }
  1102. /// <summary>Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.</summary>
  1103. /// <returns></returns>
  1104. internal int GetHeaderHeightIfAny () { return ShouldRenderHeaders () ? GetHeaderHeight () : 0; }
  1105. private void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
  1106. {
  1107. Move (col, row);
  1108. d.AddRune (ch);
  1109. }
  1110. /// <summary>
  1111. /// Returns the maximum of the <paramref name="col"/> name and the maximum length of data that will be rendered
  1112. /// starting at <see cref="RowOffset"/> and rendering <paramref name="rowsToRender"/>
  1113. /// </summary>
  1114. /// <param name="col"></param>
  1115. /// <param name="rowsToRender"></param>
  1116. /// <param name="colStyle"></param>
  1117. /// <returns></returns>
  1118. private int CalculateMaxCellWidth (int col, int rowsToRender, ColumnStyle colStyle)
  1119. {
  1120. int spaceRequired = table.ColumnNames [col].EnumerateRunes ().Sum (c => c.GetColumns ());
  1121. // if table has no rows
  1122. if (RowOffset < 0)
  1123. {
  1124. return spaceRequired;
  1125. }
  1126. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows; i++)
  1127. {
  1128. //expand required space if cell is bigger than the last biggest cell or header
  1129. spaceRequired = Math.Max (
  1130. spaceRequired,
  1131. GetRepresentation (Table [i, col], colStyle)
  1132. .EnumerateRunes ()
  1133. .Sum (c => c.GetColumns ())
  1134. );
  1135. }
  1136. // Don't require more space than the style allows
  1137. if (colStyle is { })
  1138. {
  1139. // enforce maximum cell width based on style
  1140. if (spaceRequired > colStyle.MaxWidth)
  1141. {
  1142. spaceRequired = colStyle.MaxWidth;
  1143. }
  1144. // enforce minimum cell width based on style
  1145. if (spaceRequired < colStyle.MinWidth)
  1146. {
  1147. spaceRequired = colStyle.MinWidth;
  1148. }
  1149. }
  1150. // enforce maximum cell width based on global table style
  1151. if (spaceRequired > MaxCellWidth)
  1152. {
  1153. spaceRequired = MaxCellWidth;
  1154. }
  1155. return spaceRequired;
  1156. }
  1157. /// <summary>
  1158. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the
  1159. /// <see cref="ColumnOffset"/>
  1160. /// </summary>
  1161. /// <param name="bounds"></param>
  1162. /// <param name="padding"></param>
  1163. /// <returns></returns>
  1164. private IEnumerable<ColumnToRender> CalculateViewport (Rectangle bounds, int padding = 1)
  1165. {
  1166. if (TableIsNullOrInvisible ())
  1167. {
  1168. return Enumerable.Empty<ColumnToRender> ();
  1169. }
  1170. List<ColumnToRender> toReturn = new ();
  1171. var usedSpace = 0;
  1172. //if horizontal space is required at the start of the line (before the first header)
  1173. if (Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  1174. {
  1175. usedSpace += 1;
  1176. }
  1177. int availableHorizontalSpace = bounds.Width;
  1178. int rowsToRender = bounds.Height;
  1179. // reserved for the headers row
  1180. if (ShouldRenderHeaders ())
  1181. {
  1182. rowsToRender -= GetHeaderHeight ();
  1183. }
  1184. var first = true;
  1185. int lastColumn = Table.Columns - 1;
  1186. // TODO : Maybe just a for loop?
  1187. foreach (int col in Enumerable.Range (0, Table.Columns).Skip (ColumnOffset))
  1188. {
  1189. int startingIdxForCurrentHeader = usedSpace;
  1190. ColumnStyle colStyle = Style.GetColumnStyleIfAny (col);
  1191. int colWidth;
  1192. // if column is not being rendered
  1193. if (colStyle?.Visible == false)
  1194. {
  1195. // do not add it to the returned columns
  1196. continue;
  1197. }
  1198. // is there enough space for this column (and it's data)?
  1199. colWidth = CalculateMaxCellWidth (col, rowsToRender, colStyle) + padding;
  1200. if (MinCellWidth > 0 && colWidth < MinCellWidth + padding)
  1201. {
  1202. if (MinCellWidth > MaxCellWidth)
  1203. {
  1204. colWidth = MaxCellWidth + padding;
  1205. }
  1206. else
  1207. {
  1208. colWidth = MinCellWidth + padding;
  1209. }
  1210. }
  1211. // there is not enough space for this columns
  1212. // visible content
  1213. if (usedSpace + colWidth > availableHorizontalSpace)
  1214. {
  1215. var showColumn = false;
  1216. // if this column accepts flexible width rendering and
  1217. // is therefore happy rendering into less space
  1218. if (colStyle != null
  1219. && colStyle.MinAcceptableWidth > 0
  1220. &&
  1221. // is there enough space to meet the MinAcceptableWidth
  1222. availableHorizontalSpace - usedSpace >= colStyle.MinAcceptableWidth)
  1223. {
  1224. // show column and use whatever space is
  1225. // left for rendering it
  1226. showColumn = true;
  1227. colWidth = availableHorizontalSpace - usedSpace;
  1228. }
  1229. // If it's the only column we are able to render then
  1230. // accept it anyway (that must be one massively wide column!)
  1231. if (first)
  1232. {
  1233. showColumn = true;
  1234. }
  1235. // no special exceptions and we are out of space
  1236. // so stop accepting new columns for the render area
  1237. if (!showColumn)
  1238. {
  1239. break;
  1240. }
  1241. }
  1242. usedSpace += colWidth;
  1243. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  1244. colWidth = Math.Min (availableHorizontalSpace, colWidth);
  1245. bool isVeryLast = lastColumn == col;
  1246. // there is space
  1247. toReturn.Add (new ColumnToRender (col, startingIdxForCurrentHeader, colWidth, isVeryLast));
  1248. first = false;
  1249. }
  1250. if (Style.ExpandLastColumn)
  1251. {
  1252. ColumnToRender last = toReturn.Last ();
  1253. last.Width = Math.Max (last.Width, availableHorizontalSpace - last.X);
  1254. }
  1255. return toReturn;
  1256. }
  1257. /// <summary>Clears a line of the console by filling it with spaces</summary>
  1258. /// <param name="row"></param>
  1259. /// <param name="width"></param>
  1260. private void ClearLine (int row, int width)
  1261. {
  1262. Move (0, row);
  1263. Driver.SetAttribute (GetNormalColor ());
  1264. Driver.AddStr (new string (' ', width));
  1265. }
  1266. private void ClearMultiSelectedRegions (bool keepToggledSelections)
  1267. {
  1268. if (!keepToggledSelections)
  1269. {
  1270. MultiSelectedRegions.Clear ();
  1271. return;
  1272. }
  1273. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1274. MultiSelectedRegions.Clear ();
  1275. foreach (TableSelection region in oldRegions)
  1276. {
  1277. if (region.IsToggled)
  1278. {
  1279. MultiSelectedRegions.Push (region);
  1280. }
  1281. }
  1282. }
  1283. /// <summary>
  1284. /// Returns a new rectangle between the two points with positive width/height regardless of relative positioning
  1285. /// of the points. pt1 is always considered the <see cref="TableSelection.Origin"/> point
  1286. /// </summary>
  1287. /// <param name="pt1X">Origin point for the selection in X</param>
  1288. /// <param name="pt1Y">Origin point for the selection in Y</param>
  1289. /// <param name="pt2X">End point for the selection in X</param>
  1290. /// <param name="pt2Y">End point for the selection in Y</param>
  1291. /// <param name="toggle">True if selection is result of <see cref="Command.Select"/></param>
  1292. /// <returns></returns>
  1293. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y, bool toggle = false)
  1294. {
  1295. int top = Math.Max (Math.Min (pt1Y, pt2Y), 0);
  1296. int bot = Math.Max (Math.Max (pt1Y, pt2Y), 0);
  1297. int left = Math.Max (Math.Min (pt1X, pt2X), 0);
  1298. int right = Math.Max (Math.Max (pt1X, pt2X), 0);
  1299. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  1300. return new TableSelection (new (pt1X, pt1Y), new (left, top, right - left + 1, bot - top + 1))
  1301. {
  1302. IsToggled = toggle
  1303. };
  1304. }
  1305. /// <summary>Returns a single point as a <see cref="TableSelection"/></summary>
  1306. /// <param name="x"></param>
  1307. /// <param name="y"></param>
  1308. /// <returns></returns>
  1309. private TableSelection CreateTableSelection (int x, int y) { return CreateTableSelection (x, y, x, y); }
  1310. private bool CycleToNextTableEntryBeginningWith (Key keyEvent)
  1311. {
  1312. int row = SelectedRow;
  1313. // There is a multi select going on and not just for the current row
  1314. if (GetAllSelectedCells ().Any (c => c.Y != row))
  1315. {
  1316. return false;
  1317. }
  1318. int match = CollectionNavigator.GetNextMatchingItem (row, (char)keyEvent);
  1319. if (match != -1)
  1320. {
  1321. SelectedRow = match;
  1322. EnsureValidSelection ();
  1323. EnsureSelectedCellIsVisible ();
  1324. SetNeedsDisplay ();
  1325. return true;
  1326. }
  1327. return false;
  1328. }
  1329. private IEnumerable<TableSelection> GetMultiSelectedRegionsContaining (int col, int row)
  1330. {
  1331. if (!MultiSelect)
  1332. {
  1333. return Enumerable.Empty<TableSelection> ();
  1334. }
  1335. if (FullRowSelect)
  1336. {
  1337. return MultiSelectedRegions.Where (r => r.Rectangle.Bottom > row && r.Rectangle.Top <= row);
  1338. }
  1339. return MultiSelectedRegions.Where (r => r.Rectangle.Contains (col, row));
  1340. }
  1341. /// <summary>
  1342. /// Returns <paramref name="columnIndex"/> unless the <see cref="ColumnStyle.Visible"/> is false for the indexed
  1343. /// column. If so then the index returned is nudged to the nearest visible column.
  1344. /// </summary>
  1345. /// <remarks>Returns <paramref name="columnIndex"/> unchanged if it is invalid (e.g. out of bounds).</remarks>
  1346. /// <param name="columnIndex">The input column index.</param>
  1347. /// <param name="lookRight">
  1348. /// When nudging invisible selections look right first. <see langword="true"/> to look right,
  1349. /// <see langword="false"/> to look left.
  1350. /// </param>
  1351. /// <param name="allowBumpingInOppositeDirection">
  1352. /// If we cannot find anything visible when looking in direction of
  1353. /// <paramref name="lookRight"/> then should we look in the opposite direction instead? Use true if you want to push a
  1354. /// selection to a valid index no matter what. Use false if you are primarily interested in learning about directional
  1355. /// column visibility.
  1356. /// </param>
  1357. private int GetNearestVisibleColumn (int columnIndex, bool lookRight, bool allowBumpingInOppositeDirection)
  1358. {
  1359. if (TryGetNearestVisibleColumn (columnIndex, lookRight, allowBumpingInOppositeDirection, out int answer))
  1360. {
  1361. return answer;
  1362. }
  1363. return columnIndex;
  1364. }
  1365. /// <summary>
  1366. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read
  1367. /// from <see cref="Table"/>
  1368. /// </summary>
  1369. /// <param name="value"></param>
  1370. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  1371. /// <returns></returns>
  1372. private string GetRepresentation (object value, ColumnStyle colStyle)
  1373. {
  1374. if (value is null || value == DBNull.Value)
  1375. {
  1376. return NullSymbol;
  1377. }
  1378. return colStyle is { } ? colStyle.GetRepresentation (value) : value.ToString ();
  1379. }
  1380. private bool HasControlOrAlt (MouseEvent me) { return me.Flags.HasFlag (MouseFlags.ButtonAlt) || me.Flags.HasFlag (MouseFlags.ButtonCtrl); }
  1381. /// <summary>
  1382. /// Returns true if the given <paramref name="columnIndex"/> indexes a visible column otherwise false. Returns
  1383. /// false for indexes that are out of bounds.
  1384. /// </summary>
  1385. /// <param name="columnIndex"></param>
  1386. /// <returns></returns>
  1387. private bool IsColumnVisible (int columnIndex)
  1388. {
  1389. // if the column index provided is out of bounds
  1390. if (columnIndex < 0 || columnIndex >= table.Columns)
  1391. {
  1392. return false;
  1393. }
  1394. return Style.GetColumnStyleIfAny (columnIndex)?.Visible ?? true;
  1395. }
  1396. private void RenderBottomLine (int row, int availableWidth, ColumnToRender [] columnsToRender)
  1397. {
  1398. // Renders a line at the bottom of the table after all the data like:
  1399. // └─────────────────────────────────┴──────────┴──────┴──────────┴────────┴────────────────────────────────────────────┘
  1400. for (var c = 0; c < availableWidth; c++)
  1401. {
  1402. // Start by assuming we just draw a straight line the
  1403. // whole way but update to instead draw BottomTee / Corner etc
  1404. Rune rune = Glyphs.HLine;
  1405. if (Style.ShowVerticalCellLines)
  1406. {
  1407. if (c == 0)
  1408. {
  1409. // for first character render line
  1410. rune = Glyphs.LLCorner;
  1411. }
  1412. else if (columnsToRender.Any (r => r.X == c + 1))
  1413. {
  1414. // if the next column is the start of a header
  1415. rune = Glyphs.BottomTee;
  1416. }
  1417. else if (c == availableWidth - 1)
  1418. {
  1419. // for the last character in the table
  1420. rune = Glyphs.LRCorner;
  1421. }
  1422. else if (Style.ExpandLastColumn == false && columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c))
  1423. {
  1424. // if the next console column is the last column's end
  1425. rune = Glyphs.BottomTee;
  1426. }
  1427. }
  1428. AddRuneAt (Driver, c, row, rune);
  1429. }
  1430. }
  1431. private void RenderHeaderMidline (int row, ColumnToRender [] columnsToRender)
  1432. {
  1433. // Renders something like:
  1434. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  1435. ClearLine (row, Viewport.Width);
  1436. //render start of line
  1437. if (style.ShowVerticalHeaderLines)
  1438. {
  1439. AddRune (0, row, Glyphs.VLine);
  1440. }
  1441. for (var i = 0; i < columnsToRender.Length; i++)
  1442. {
  1443. ColumnToRender current = columnsToRender [i];
  1444. ColumnStyle colStyle = Style.GetColumnStyleIfAny (current.Column);
  1445. string colName = table.ColumnNames [current.Column];
  1446. RenderSeparator (current.X - 1, row, true);
  1447. Move (current.X, row);
  1448. Driver.AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
  1449. if (Style.ExpandLastColumn == false && current.IsVeryLast)
  1450. {
  1451. RenderSeparator (current.X + current.Width - 1, row, true);
  1452. }
  1453. }
  1454. //render end of line
  1455. if (style.ShowVerticalHeaderLines)
  1456. {
  1457. AddRune (Viewport.Width - 1, row, Glyphs.VLine);
  1458. }
  1459. }
  1460. private void RenderHeaderOverline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  1461. {
  1462. // Renders a line above table headers (when visible) like:
  1463. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  1464. for (var c = 0; c < availableWidth; c++)
  1465. {
  1466. Rune rune = Glyphs.HLine;
  1467. if (Style.ShowVerticalHeaderLines)
  1468. {
  1469. if (c == 0)
  1470. {
  1471. rune = Glyphs.ULCorner;
  1472. }
  1473. // if the next column is the start of a header
  1474. else if (columnsToRender.Any (r => r.X == c + 1))
  1475. {
  1476. rune = Glyphs.TopTee;
  1477. }
  1478. else if (c == availableWidth - 1)
  1479. {
  1480. rune = Glyphs.URCorner;
  1481. }
  1482. // if the next console column is the last column's end
  1483. else if (Style.ExpandLastColumn == false && columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c))
  1484. {
  1485. rune = Glyphs.TopTee;
  1486. }
  1487. }
  1488. AddRuneAt (Driver, c, row, rune);
  1489. }
  1490. }
  1491. private void RenderHeaderUnderline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  1492. {
  1493. /*
  1494. * First lets work out if we should be rendering scroll indicators
  1495. */
  1496. // are there are visible columns to the left that have been pushed
  1497. // off the screen due to horizontal scrolling?
  1498. bool moreColumnsToLeft = ColumnOffset > 0;
  1499. // if we moved left would we find a new column (or are they all invisible?)
  1500. if (!TryGetNearestVisibleColumn (ColumnOffset - 1, false, false, out _))
  1501. {
  1502. moreColumnsToLeft = false;
  1503. }
  1504. // are there visible columns to the right that have not yet been reached?
  1505. // lets find out, what is the column index of the last column we are rendering
  1506. int lastColumnIdxRendered = ColumnOffset + columnsToRender.Length - 1;
  1507. // are there more valid indexes?
  1508. bool moreColumnsToRight = lastColumnIdxRendered < Table.Columns;
  1509. // if we went right from the last column would we find a new visible column?
  1510. if (!TryGetNearestVisibleColumn (lastColumnIdxRendered + 1, true, false, out _))
  1511. {
  1512. // no we would not
  1513. moreColumnsToRight = false;
  1514. }
  1515. /*
  1516. * Now lets draw the line itself
  1517. */
  1518. // Renders a line below the table headers (when visible) like:
  1519. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  1520. for (var c = 0; c < availableWidth; c++)
  1521. {
  1522. // Start by assuming we just draw a straight line the
  1523. // whole way but update to instead draw a header indicator
  1524. // or scroll arrow etc
  1525. Rune rune = Glyphs.HLine;
  1526. if (Style.ShowVerticalHeaderLines)
  1527. {
  1528. if (c == 0)
  1529. {
  1530. // for first character render line
  1531. rune = Style.ShowVerticalCellLines ? Glyphs.LeftTee : Glyphs.LLCorner;
  1532. // unless we have horizontally scrolled along
  1533. // in which case render an arrow, to indicate user
  1534. // can scroll left
  1535. if (Style.ShowHorizontalScrollIndicators && moreColumnsToLeft)
  1536. {
  1537. rune = Glyphs.LeftArrow;
  1538. scrollLeftPoint = new Point (c, row);
  1539. }
  1540. }
  1541. // if the next column is the start of a header
  1542. else if (columnsToRender.Any (r => r.X == c + 1))
  1543. {
  1544. /*TODO: is ┼ symbol in Driver?*/
  1545. rune = Style.ShowVerticalCellLines ? Glyphs.Cross : Glyphs.BottomTee;
  1546. }
  1547. else if (c == availableWidth - 1)
  1548. {
  1549. // for the last character in the table
  1550. rune = Style.ShowVerticalCellLines ? Glyphs.RightTee : Glyphs.LRCorner;
  1551. // unless there is more of the table we could horizontally
  1552. // scroll along to see. In which case render an arrow,
  1553. // to indicate user can scroll right
  1554. if (Style.ShowHorizontalScrollIndicators && moreColumnsToRight)
  1555. {
  1556. rune = Glyphs.RightArrow;
  1557. scrollRightPoint = new Point (c, row);
  1558. }
  1559. }
  1560. // if the next console column is the last column's end
  1561. else if (Style.ExpandLastColumn == false && columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c))
  1562. {
  1563. rune = Style.ShowVerticalCellLines ? Glyphs.Cross : Glyphs.BottomTee;
  1564. }
  1565. }
  1566. AddRuneAt (Driver, c, row, rune);
  1567. }
  1568. }
  1569. private void RenderRow (int row, int rowToRender, ColumnToRender [] columnsToRender)
  1570. {
  1571. bool focused = HasFocus;
  1572. ColorScheme rowScheme = Style.RowColorGetter?.Invoke (
  1573. new RowColorGetterArgs (Table, rowToRender)
  1574. )
  1575. ?? ColorScheme;
  1576. //start by clearing the entire line
  1577. Move (0, row);
  1578. Attribute color;
  1579. if (FullRowSelect && IsSelected (0, rowToRender))
  1580. {
  1581. color = focused ? rowScheme.Focus : rowScheme.HotNormal;
  1582. }
  1583. else
  1584. {
  1585. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  1586. }
  1587. Driver.SetAttribute (color);
  1588. Driver.AddStr (new string (' ', Viewport.Width));
  1589. // Render cells for each visible header for the current row
  1590. for (var i = 0; i < columnsToRender.Length; i++)
  1591. {
  1592. ColumnToRender current = columnsToRender [i];
  1593. ColumnStyle colStyle = Style.GetColumnStyleIfAny (current.Column);
  1594. // move to start of cell (in line with header positions)
  1595. Move (current.X, row);
  1596. // Set color scheme based on whether the current cell is the selected one
  1597. bool isSelectedCell = IsSelected (current.Column, rowToRender);
  1598. object val = Table [rowToRender, current.Column];
  1599. // Render the (possibly truncated) cell value
  1600. string representation = GetRepresentation (val, colStyle);
  1601. // to get the colour scheme
  1602. CellColorGetterDelegate colorSchemeGetter = colStyle?.ColorGetter;
  1603. ColorScheme scheme;
  1604. if (colorSchemeGetter is { })
  1605. {
  1606. // user has a delegate for defining row color per cell, call it
  1607. scheme = colorSchemeGetter (
  1608. new CellColorGetterArgs (
  1609. Table,
  1610. rowToRender,
  1611. current.Column,
  1612. val,
  1613. representation,
  1614. rowScheme
  1615. )
  1616. );
  1617. // if users custom color getter returned null, use the row scheme
  1618. if (scheme is null)
  1619. {
  1620. scheme = rowScheme;
  1621. }
  1622. }
  1623. else
  1624. {
  1625. // There is no custom cell coloring delegate so use the scheme for the row
  1626. scheme = rowScheme;
  1627. }
  1628. Attribute cellColor;
  1629. if (isSelectedCell)
  1630. {
  1631. cellColor = focused ? scheme.Focus : scheme.HotNormal;
  1632. }
  1633. else
  1634. {
  1635. cellColor = Enabled ? scheme.Normal : scheme.Disabled;
  1636. }
  1637. string render = TruncateOrPad (val, representation, current.Width, colStyle);
  1638. // While many cells can be selected (see MultiSelectedRegions) only one cell is the primary (drives navigation etc)
  1639. bool isPrimaryCell = current.Column == selectedColumn && rowToRender == selectedRow;
  1640. RenderCell (cellColor, render, isPrimaryCell);
  1641. // Reset color scheme to normal for drawing separators if we drew text with custom scheme
  1642. if (scheme != rowScheme)
  1643. {
  1644. if (isSelectedCell)
  1645. {
  1646. color = focused ? rowScheme.Focus : rowScheme.HotNormal;
  1647. }
  1648. else
  1649. {
  1650. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  1651. }
  1652. Driver.SetAttribute (color);
  1653. }
  1654. // If not in full row select mode always, reset color scheme to normal and render the vertical line (or space) at the end of the cell
  1655. if (!FullRowSelect)
  1656. {
  1657. Driver.SetAttribute (Enabled ? rowScheme.Normal : rowScheme.Disabled);
  1658. }
  1659. if (style.AlwaysUseNormalColorForVerticalCellLines && style.ShowVerticalCellLines)
  1660. {
  1661. Driver.SetAttribute (rowScheme.Normal);
  1662. }
  1663. RenderSeparator (current.X - 1, row, false);
  1664. if (Style.ExpandLastColumn == false && current.IsVeryLast)
  1665. {
  1666. RenderSeparator (current.X + current.Width - 1, row, false);
  1667. }
  1668. }
  1669. if (style.ShowVerticalCellLines)
  1670. {
  1671. Driver.SetAttribute (rowScheme.Normal);
  1672. //render start and end of line
  1673. AddRune (0, row, Glyphs.VLine);
  1674. AddRune (Viewport.Width - 1, row, Glyphs.VLine);
  1675. }
  1676. }
  1677. private void RenderSeparator (int col, int row, bool isHeader)
  1678. {
  1679. if (col < 0)
  1680. {
  1681. return;
  1682. }
  1683. bool renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  1684. Rune symbol = renderLines ? Glyphs.VLine : (Rune)SeparatorSymbol;
  1685. AddRune (col, row, symbol);
  1686. }
  1687. private bool ShouldRenderHeaders ()
  1688. {
  1689. if (TableIsNullOrInvisible ())
  1690. {
  1691. return false;
  1692. }
  1693. return Style.AlwaysShowHeaders || rowOffset == 0;
  1694. }
  1695. /// <summary>
  1696. /// Returns true if the <see cref="Table"/> is not set or all the columns in the <see cref="Table"/> have an
  1697. /// explicit <see cref="ColumnStyle"/> that marks them <see cref="ColumnStyle.Visible"/> <see langword="false"/>.
  1698. /// </summary>
  1699. /// <returns></returns>
  1700. private bool TableIsNullOrInvisible ()
  1701. {
  1702. return Table == null
  1703. || Table.Columns <= 0
  1704. || Enumerable.Range (0, Table.Columns)
  1705. .All (
  1706. c => (Style.GetColumnStyleIfAny (c)?.Visible ?? true) == false
  1707. );
  1708. }
  1709. private void ToggleCurrentCellSelection ()
  1710. {
  1711. var e = new CellToggledEventArgs (Table, selectedColumn, selectedRow);
  1712. OnCellToggled (e);
  1713. if (e.Cancel)
  1714. {
  1715. return;
  1716. }
  1717. if (!MultiSelect)
  1718. {
  1719. return;
  1720. }
  1721. TableSelection [] regions = GetMultiSelectedRegionsContaining (selectedColumn, selectedRow).ToArray ();
  1722. TableSelection [] toggles = regions.Where (s => s.IsToggled).ToArray ();
  1723. // Toggle it off
  1724. if (toggles.Any ())
  1725. {
  1726. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1727. MultiSelectedRegions.Clear ();
  1728. foreach (TableSelection region in oldRegions)
  1729. {
  1730. if (!toggles.Contains (region))
  1731. {
  1732. MultiSelectedRegions.Push (region);
  1733. }
  1734. }
  1735. }
  1736. else
  1737. {
  1738. // user is toggling selection within a rectangular
  1739. // select. So toggle the full region
  1740. if (regions.Any ())
  1741. {
  1742. foreach (TableSelection r in regions)
  1743. {
  1744. r.IsToggled = true;
  1745. }
  1746. }
  1747. else
  1748. {
  1749. // Toggle on a single cell selection
  1750. MultiSelectedRegions.Push (
  1751. CreateTableSelection (
  1752. selectedColumn,
  1753. SelectedRow,
  1754. selectedColumn,
  1755. selectedRow,
  1756. true
  1757. )
  1758. );
  1759. }
  1760. }
  1761. }
  1762. /// <summary>
  1763. /// Truncates or pads <paramref name="representation"/> so that it occupies a exactly
  1764. /// <paramref name="availableHorizontalSpace"/> using the alignment specified in <paramref name="colStyle"/> (or left
  1765. /// if no style is defined)
  1766. /// </summary>
  1767. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  1768. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  1769. /// <param name="availableHorizontalSpace"></param>
  1770. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  1771. /// <returns></returns>
  1772. private string TruncateOrPad (
  1773. object originalCellValue,
  1774. string representation,
  1775. int availableHorizontalSpace,
  1776. ColumnStyle colStyle
  1777. )
  1778. {
  1779. if (string.IsNullOrEmpty (representation))
  1780. {
  1781. return new string (' ', availableHorizontalSpace);
  1782. }
  1783. // if value is not wide enough
  1784. if (representation.EnumerateRunes ().Sum (c => c.GetColumns ()) < availableHorizontalSpace)
  1785. {
  1786. // pad it out with spaces to the given alignment
  1787. int toPad = availableHorizontalSpace
  1788. - (representation.EnumerateRunes ().Sum (c => c.GetColumns ())
  1789. + 1 /*leave 1 space for cell boundary*/);
  1790. switch (colStyle?.GetAlignment (originalCellValue) ?? Alignment.Start)
  1791. {
  1792. case Alignment.Start:
  1793. return representation + new string (' ', toPad);
  1794. case Alignment.End:
  1795. return new string (' ', toPad) + representation;
  1796. // TODO: With single line cells, centered and justified are the same right?
  1797. case Alignment.Center:
  1798. case Alignment.Fill:
  1799. return
  1800. new string (' ', (int)Math.Floor (toPad / 2.0))
  1801. + // round down
  1802. representation
  1803. + new string (' ', (int)Math.Ceiling (toPad / 2.0)); // round up
  1804. }
  1805. }
  1806. // value is too wide
  1807. return new string (
  1808. representation.TakeWhile (c => (availableHorizontalSpace -= ((Rune)c).GetColumns ()) > 0)
  1809. .ToArray ()
  1810. );
  1811. }
  1812. private bool TryGetNearestVisibleColumn (
  1813. int columnIndex,
  1814. bool lookRight,
  1815. bool allowBumpingInOppositeDirection,
  1816. out int idx
  1817. )
  1818. {
  1819. // if the column index provided is out of bounds
  1820. if (table is null || columnIndex < 0 || columnIndex >= table.Columns)
  1821. {
  1822. idx = columnIndex;
  1823. return false;
  1824. }
  1825. // get the column visibility by index (if no style visible is true)
  1826. bool [] columnVisibility =
  1827. Enumerable.Range (0, Table.Columns)
  1828. .Select (c => Style.GetColumnStyleIfAny (c)?.Visible ?? true)
  1829. .ToArray ();
  1830. // column is visible
  1831. if (columnVisibility [columnIndex])
  1832. {
  1833. idx = columnIndex;
  1834. return true;
  1835. }
  1836. int increment = lookRight ? 1 : -1;
  1837. // move in that direction
  1838. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment)
  1839. {
  1840. // if we find a visible column
  1841. if (columnVisibility [i])
  1842. {
  1843. idx = i;
  1844. return true;
  1845. }
  1846. }
  1847. // Caller only wants to look in one direction and we did not find any
  1848. // visible columns in that direction
  1849. if (!allowBumpingInOppositeDirection)
  1850. {
  1851. idx = columnIndex;
  1852. return false;
  1853. }
  1854. // Caller will let us look in the other direction so
  1855. // now look other way
  1856. increment = -increment;
  1857. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment)
  1858. {
  1859. // if we find a visible column
  1860. if (columnVisibility [i])
  1861. {
  1862. idx = i;
  1863. return true;
  1864. }
  1865. }
  1866. // nothing seems to be visible so just return input index
  1867. idx = columnIndex;
  1868. return false;
  1869. }
  1870. /// <summary>Unions the current selected cell (and/or regions) with the provided cell and makes it the active one.</summary>
  1871. /// <param name="col"></param>
  1872. /// <param name="row"></param>
  1873. private void UnionSelection (int col, int row)
  1874. {
  1875. if (!MultiSelect || TableIsNullOrInvisible ())
  1876. {
  1877. return;
  1878. }
  1879. EnsureValidSelection ();
  1880. int oldColumn = SelectedColumn;
  1881. int oldRow = SelectedRow;
  1882. // move us to the new cell
  1883. SelectedColumn = col;
  1884. SelectedRow = row;
  1885. MultiSelectedRegions.Push (
  1886. CreateTableSelection (col, row)
  1887. );
  1888. // if the old cell was not part of a rectangular select
  1889. // or otherwise selected we need to retain it in the selection
  1890. if (!IsSelected (oldColumn, oldRow))
  1891. {
  1892. MultiSelectedRegions.Push (
  1893. CreateTableSelection (oldColumn, oldRow)
  1894. );
  1895. }
  1896. }
  1897. /// <summary>Describes a desire to render a column at a given horizontal position in the UI</summary>
  1898. internal class ColumnToRender
  1899. {
  1900. public ColumnToRender (int col, int x, int width, bool isVeryLast)
  1901. {
  1902. Column = col;
  1903. X = x;
  1904. Width = width;
  1905. IsVeryLast = isVeryLast;
  1906. }
  1907. /// <summary>The column to render</summary>
  1908. public int Column { get; set; }
  1909. /// <summary>True if this column is the very last column in the <see cref="Table"/> (not just the last visible column)</summary>
  1910. public bool IsVeryLast { get; }
  1911. /// <summary>
  1912. /// The width that the column should occupy as calculated by <see cref="CalculateViewport(Rectangle, int)"/>. Note
  1913. /// that this includes space for padding i.e. the separator between columns.
  1914. /// </summary>
  1915. public int Width { get; internal set; }
  1916. /// <summary>The horizontal position to begin rendering the column at</summary>
  1917. public int X { get; set; }
  1918. }
  1919. }