TableView.cs 84 KB

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