TableView.cs 81 KB

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