2
0

TableView.cs 82 KB

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