2
0

TableView.cs 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  1. #nullable disable
  2. using System.Data;
  3. using System.Globalization;
  4. namespace Terminal.Gui.Views;
  5. /// <summary>Delegate for providing color to <see cref="TableView"/> cells based on the value being rendered</summary>
  6. /// <param name="args">Contains information about the cell for which color is needed</param>
  7. /// <returns></returns>
  8. public delegate Scheme CellColorGetterDelegate (CellColorGetterArgs args);
  9. /// <summary>Delegate for providing color for a whole row of a <see cref="TableView"/></summary>
  10. /// <param name="args"></param>
  11. /// <returns></returns>
  12. public delegate Scheme RowColorGetterDelegate (RowColorGetterArgs args);
  13. /// <summary>
  14. /// Displays and enables infinite scrolling through tabular data based on a <see cref="ITableSource"/>.
  15. /// <a href="../docs/tableview.md">See the TableView Deep Dive for more</a>.
  16. /// </summary>
  17. public class TableView : View, IDesignable
  18. {
  19. /// <summary>
  20. /// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
  21. /// </summary>
  22. public const int DefaultMaxCellWidth = 100;
  23. /// <summary>The default minimum cell width for <see cref="ColumnStyle.MinAcceptableWidth"/></summary>
  24. public const int DefaultMinAcceptableWidth = 100;
  25. // TODO: Update to use Key instead of KeyCode
  26. private KeyCode cellActivationKey = KeyCode.Enter;
  27. private int columnOffset;
  28. private int rowOffset;
  29. private Point? scrollLeftPoint;
  30. private Point? scrollRightPoint;
  31. private int selectedColumn;
  32. private int selectedRow;
  33. private TableStyle style = new ();
  34. private ITableSource table;
  35. /// <summary>Initializes a <see cref="TableView"/> class.</summary>
  36. /// <param name="table">The table to display in the control</param>
  37. public TableView (ITableSource table) : this () { Table = table; }
  38. /// <summary>
  39. /// Initializes a <see cref="TableView"/> class. Set the
  40. /// <see cref="Table"/> property to begin editing
  41. /// </summary>
  42. public TableView ()
  43. {
  44. CanFocus = true;
  45. CollectionNavigator = new TableCollectionNavigator (this);
  46. // Things this view knows how to do
  47. AddCommand (
  48. Command.Right,
  49. () => ChangeSelectionByOffsetWithReturn (1, 0));
  50. AddCommand (
  51. Command.Left,
  52. () => ChangeSelectionByOffsetWithReturn (-1, 0));
  53. AddCommand (
  54. Command.Up,
  55. () => ChangeSelectionByOffsetWithReturn (0, -1));
  56. AddCommand (
  57. Command.Down,
  58. () => ChangeSelectionByOffsetWithReturn (0, 1));
  59. AddCommand (
  60. Command.PageUp,
  61. () =>
  62. {
  63. PageUp (false);
  64. return true;
  65. }
  66. );
  67. AddCommand (
  68. Command.PageDown,
  69. () =>
  70. {
  71. PageDown (false);
  72. return true;
  73. }
  74. );
  75. AddCommand (
  76. Command.LeftStart,
  77. () =>
  78. {
  79. ChangeSelectionToStartOfRow (false);
  80. return true;
  81. }
  82. );
  83. AddCommand (
  84. Command.RightEnd,
  85. () =>
  86. {
  87. ChangeSelectionToEndOfRow (false);
  88. return true;
  89. }
  90. );
  91. AddCommand (
  92. Command.Start,
  93. () =>
  94. {
  95. ChangeSelectionToStartOfTable (false);
  96. return true;
  97. }
  98. );
  99. AddCommand (
  100. Command.End,
  101. () =>
  102. {
  103. ChangeSelectionToEndOfTable (false);
  104. return true;
  105. }
  106. );
  107. AddCommand (
  108. Command.RightExtend,
  109. () =>
  110. {
  111. ChangeSelectionByOffset (1, 0, true);
  112. return true;
  113. }
  114. );
  115. AddCommand (
  116. Command.LeftExtend,
  117. () =>
  118. {
  119. ChangeSelectionByOffset (-1, 0, true);
  120. return true;
  121. }
  122. );
  123. AddCommand (
  124. Command.UpExtend,
  125. () =>
  126. {
  127. ChangeSelectionByOffset (0, -1, true);
  128. return true;
  129. }
  130. );
  131. AddCommand (
  132. Command.DownExtend,
  133. () =>
  134. {
  135. ChangeSelectionByOffset (0, 1, true);
  136. return true;
  137. }
  138. );
  139. AddCommand (
  140. Command.PageUpExtend,
  141. () =>
  142. {
  143. PageUp (true);
  144. return true;
  145. }
  146. );
  147. AddCommand (
  148. Command.PageDownExtend,
  149. () =>
  150. {
  151. PageDown (true);
  152. return true;
  153. }
  154. );
  155. AddCommand (
  156. Command.LeftStartExtend,
  157. () =>
  158. {
  159. ChangeSelectionToStartOfRow (true);
  160. return true;
  161. }
  162. );
  163. AddCommand (
  164. Command.RightEndExtend,
  165. () =>
  166. {
  167. ChangeSelectionToEndOfRow (true);
  168. return true;
  169. }
  170. );
  171. AddCommand (
  172. Command.StartExtend,
  173. () =>
  174. {
  175. ChangeSelectionToStartOfTable (true);
  176. return true;
  177. }
  178. );
  179. AddCommand (
  180. Command.EndExtend,
  181. () =>
  182. {
  183. ChangeSelectionToEndOfTable (true);
  184. return true;
  185. }
  186. );
  187. AddCommand (
  188. Command.SelectAll,
  189. () =>
  190. {
  191. SelectAll ();
  192. return true;
  193. }
  194. );
  195. AddCommand (Command.Accept, () => OnCellActivated (new (Table, SelectedColumn, SelectedRow)));
  196. AddCommand (
  197. Command.Select, // was Command.ToggleChecked
  198. ctx =>
  199. {
  200. if (ToggleCurrentCellSelection () is true)
  201. {
  202. return RaiseSelecting (ctx) is true;
  203. }
  204. return false;
  205. }
  206. );
  207. // Default keybindings for this view
  208. KeyBindings.Add (Key.CursorLeft, Command.Left);
  209. KeyBindings.Add (Key.CursorRight, Command.Right);
  210. KeyBindings.Add (Key.CursorUp, Command.Up);
  211. KeyBindings.Add (Key.CursorDown, Command.Down);
  212. KeyBindings.Add (Key.PageUp, Command.PageUp);
  213. KeyBindings.Add (Key.PageDown, Command.PageDown);
  214. KeyBindings.Add (Key.Home, Command.LeftStart);
  215. KeyBindings.Add (Key.End, Command.RightEnd);
  216. KeyBindings.Add (Key.Home.WithCtrl, Command.Start);
  217. KeyBindings.Add (Key.End.WithCtrl, Command.End);
  218. KeyBindings.Add (Key.CursorLeft.WithShift, Command.LeftExtend);
  219. KeyBindings.Add (Key.CursorRight.WithShift, Command.RightExtend);
  220. KeyBindings.Add (Key.CursorUp.WithShift, Command.UpExtend);
  221. KeyBindings.Add (Key.CursorDown.WithShift, Command.DownExtend);
  222. KeyBindings.Add (Key.PageUp.WithShift, Command.PageUpExtend);
  223. KeyBindings.Add (Key.PageDown.WithShift, Command.PageDownExtend);
  224. KeyBindings.Add (Key.Home.WithShift, Command.LeftStartExtend);
  225. KeyBindings.Add (Key.End.WithShift, Command.RightEndExtend);
  226. KeyBindings.Add (Key.Home.WithCtrl.WithShift, Command.StartExtend);
  227. KeyBindings.Add (Key.End.WithCtrl.WithShift, Command.EndExtend);
  228. KeyBindings.Add (Key.A.WithCtrl, Command.SelectAll);
  229. KeyBindings.Remove (CellActivationKey);
  230. KeyBindings.Add (CellActivationKey, Command.Accept);
  231. }
  232. // TODO: Update to use Key instead of KeyCode
  233. /// <summary>The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.</summary>
  234. public KeyCode CellActivationKey
  235. {
  236. get => cellActivationKey;
  237. set
  238. {
  239. if (cellActivationKey != value)
  240. {
  241. if (KeyBindings.TryGet (cellActivationKey, out _))
  242. {
  243. KeyBindings.Replace (cellActivationKey, value);
  244. }
  245. else
  246. {
  247. KeyBindings.Add (value, Command.Accept);
  248. }
  249. cellActivationKey = value;
  250. }
  251. }
  252. }
  253. /// <summary>Navigator for cycling the selected item in the table by typing. Set to null to disable this feature.</summary>
  254. public ICollectionNavigator CollectionNavigator { get; set; }
  255. /// <summary>
  256. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering
  257. /// the view.
  258. /// </summary>
  259. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  260. public int ColumnOffset
  261. {
  262. get => columnOffset;
  263. //try to prevent this being set to an out of bounds column
  264. set
  265. {
  266. int prev = columnOffset;
  267. columnOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Columns - 1, value));
  268. if (prev != columnOffset)
  269. {
  270. SetNeedsDraw ();
  271. }
  272. }
  273. }
  274. /// <summary>True to select the entire row at once. False to select individual cells. Defaults to false</summary>
  275. public bool FullRowSelect { get; set; }
  276. /// <summary>
  277. /// The maximum number of characters to render in any given column. This prevents one long column from pushing
  278. /// out all the others
  279. /// </summary>
  280. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  281. /// <summary>The minimum number of characters to render in any given column.</summary>
  282. public int MinCellWidth { get; set; }
  283. /// <summary>True to allow regions to be selected</summary>
  284. /// <value></value>
  285. public bool MultiSelect { get; set; } = true;
  286. /// <summary>
  287. /// When <see cref="MultiSelect"/> is enabled this property contain all rectangles of selected cells. Rectangles
  288. /// describe column/rows selected in <see cref="Table"/> (not screen coordinates)
  289. /// </summary>
  290. /// <returns></returns>
  291. public Stack<TableSelection> MultiSelectedRegions { get; } = new ();
  292. /// <summary>The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/></summary>
  293. public string NullSymbol { get; set; } = "-";
  294. /// <summary>
  295. /// Vertical scroll offset. The index of the first row in <see cref="Table"/> to display in the first non header
  296. /// line of the control when rendering the view.
  297. /// </summary>
  298. public int RowOffset
  299. {
  300. get => rowOffset;
  301. set
  302. {
  303. int prev = rowOffset;
  304. rowOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Rows - 1, value));
  305. if (rowOffset != prev)
  306. {
  307. SetNeedsDraw ();
  308. }
  309. }
  310. }
  311. /// <summary>The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected</summary>
  312. public int SelectedColumn
  313. {
  314. get => selectedColumn;
  315. set
  316. {
  317. int oldValue = selectedColumn;
  318. //try to prevent this being set to an out of bounds column
  319. selectedColumn = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Columns - 1, Math.Max (0, value));
  320. if (oldValue != selectedColumn)
  321. {
  322. OnSelectedCellChanged (
  323. new (
  324. Table,
  325. oldValue,
  326. SelectedColumn,
  327. SelectedRow,
  328. SelectedRow
  329. )
  330. );
  331. }
  332. }
  333. }
  334. /// <summary>The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected</summary>
  335. public int SelectedRow
  336. {
  337. get => selectedRow;
  338. set
  339. {
  340. int oldValue = selectedRow;
  341. selectedRow = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Rows - 1, Math.Max (0, value));
  342. if (oldValue != selectedRow)
  343. {
  344. OnSelectedCellChanged (
  345. new (
  346. Table,
  347. SelectedColumn,
  348. SelectedColumn,
  349. oldValue,
  350. selectedRow
  351. )
  352. );
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// The symbol to add after each cell value and header value to visually separate values (if not using vertical
  358. /// gridlines)
  359. /// </summary>
  360. public char SeparatorSymbol { get; set; } = ' ';
  361. /// <summary>Contains options for changing how the table is rendered</summary>
  362. public TableStyle Style
  363. {
  364. get => style;
  365. set
  366. {
  367. style = value;
  368. Update ();
  369. }
  370. }
  371. /// <summary>The data table to render in the view. Setting this property automatically updates and redraws the control.</summary>
  372. public ITableSource Table
  373. {
  374. get => table;
  375. set
  376. {
  377. table = value;
  378. Update ();
  379. }
  380. }
  381. /// <summary>
  382. /// This event is raised when a cell is activated e.g. by double-clicking or pressing
  383. /// <see cref="CellActivationKey"/>
  384. /// </summary>
  385. public event EventHandler<CellActivatedEventArgs> CellActivated;
  386. /// <summary>This event is raised when a cell is toggled (see <see cref="Command.Select"/></summary>
  387. public event EventHandler<CellToggledEventArgs> CellToggled;
  388. /// <summary>
  389. /// Returns the screen position (relative to the control client area) that the given cell is rendered or null if
  390. /// it is outside the current scroll area or no table is loaded
  391. /// </summary>
  392. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for</param>
  393. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  394. /// <returns></returns>
  395. public Point? CellToScreen (int tableColumn, int tableRow)
  396. {
  397. if (TableIsNullOrInvisible ())
  398. {
  399. return null;
  400. }
  401. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Viewport);
  402. int headerHeight = GetHeaderHeightIfAny ();
  403. ColumnToRender colHit = viewPort.FirstOrDefault (c => c.Column == tableColumn);
  404. // current column is outside the scroll area
  405. if (colHit is null)
  406. {
  407. return null;
  408. }
  409. // the cell is too far up above the current scroll area
  410. if (RowOffset > tableRow)
  411. {
  412. return null;
  413. }
  414. // the cell is way down below the scroll area and off the screen
  415. if (tableRow > RowOffset + (Viewport.Height - headerHeight))
  416. {
  417. return null;
  418. }
  419. return new Point (colHit.X, tableRow + headerHeight - RowOffset);
  420. }
  421. /// <summary>
  422. /// Private override of <see cref="ChangeSelectionByOffset"/> that returns true if the selection has
  423. /// changed as a result of moving the selection. Used by key handling logic to determine whether e.g.
  424. /// the cursor right resulted in a change or should be forwarded on to toggle logic handling.
  425. /// </summary>
  426. /// <param name="offsetX"></param>
  427. /// <param name="offsetY"></param>
  428. /// <returns></returns>
  429. private bool ChangeSelectionByOffsetWithReturn (int offsetX, int offsetY)
  430. {
  431. TableViewSelectionSnapshot oldSelection = GetSelectionSnapshot ();
  432. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, false);
  433. Update ();
  434. return !SelectionIsSame (oldSelection);
  435. }
  436. private TableViewSelectionSnapshot GetSelectionSnapshot ()
  437. {
  438. return new (
  439. SelectedColumn,
  440. SelectedRow,
  441. MultiSelectedRegions.Select (s => s.Rectangle).ToArray ());
  442. }
  443. private bool SelectionIsSame (TableViewSelectionSnapshot oldSelection)
  444. {
  445. TableViewSelectionSnapshot newSelection = GetSelectionSnapshot ();
  446. return oldSelection.SelectedColumn == newSelection.SelectedColumn
  447. && oldSelection.SelectedRow == newSelection.SelectedRow
  448. && oldSelection.multiSelection.SequenceEqual (newSelection.multiSelection);
  449. }
  450. private record TableViewSelectionSnapshot (int SelectedColumn, int SelectedRow, Rectangle [] multiSelection);
  451. /// <summary>
  452. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally
  453. /// starting a box selection (see <see cref="MultiSelect"/>)
  454. /// </summary>
  455. /// <param name="offsetX">Offset in number of columns</param>
  456. /// <param name="offsetY">Offset in number of rows</param>
  457. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  458. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  459. {
  460. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
  461. Update ();
  462. }
  463. /// <summary>Moves or extends the selection to the last cell in the current row</summary>
  464. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  465. public void ChangeSelectionToEndOfRow (bool extend)
  466. {
  467. SetSelection (Table.Columns - 1, SelectedRow, extend);
  468. Update ();
  469. }
  470. /// <summary>
  471. /// Moves or extends the selection to the final cell in the table (nX,nY). If <see cref="FullRowSelect"/> is
  472. /// enabled then selection instead moves to ( <see cref="SelectedColumn"/>,nY) i.e. no horizontal scrolling.
  473. /// </summary>
  474. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  475. public void ChangeSelectionToEndOfTable (bool extend)
  476. {
  477. int finalColumn = Table.Columns - 1;
  478. SetSelection (FullRowSelect ? SelectedColumn : finalColumn, Table.Rows - 1, extend);
  479. Update ();
  480. }
  481. /// <summary>Moves or extends the selection to the first cell in the current row</summary>
  482. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  483. public void ChangeSelectionToStartOfRow (bool extend)
  484. {
  485. SetSelection (0, SelectedRow, extend);
  486. Update ();
  487. }
  488. /// <summary>
  489. /// Moves or extends the selection to the first cell in the table (0,0). If <see cref="FullRowSelect"/> is enabled
  490. /// then selection instead moves to ( <see cref="SelectedColumn"/>,0) i.e. no horizontal scrolling.
  491. /// </summary>
  492. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  493. public void ChangeSelectionToStartOfTable (bool extend)
  494. {
  495. SetSelection (FullRowSelect ? SelectedColumn : 0, 0, extend);
  496. Update ();
  497. }
  498. /// <summary>
  499. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has
  500. /// not been set.
  501. /// </summary>
  502. /// <remarks>
  503. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDraw()"/>
  504. /// </remarks>
  505. public void EnsureSelectedCellIsVisible ()
  506. {
  507. if (Table is null || Table.Columns <= 0)
  508. {
  509. return;
  510. }
  511. ColumnToRender [] columnsToRender = CalculateViewport (Viewport).ToArray ();
  512. int headerHeight = GetHeaderHeightIfAny ();
  513. //if we have scrolled too far to the left
  514. if (SelectedColumn < columnsToRender.Min (r => r.Column))
  515. {
  516. ColumnOffset = SelectedColumn;
  517. }
  518. //if we have scrolled too far to the right
  519. if (SelectedColumn > columnsToRender.Max (r => r.Column))
  520. {
  521. if (Style.SmoothHorizontalScrolling)
  522. {
  523. // Scroll right 1 column at a time until the users selected column is visible
  524. while (SelectedColumn > columnsToRender.Max (r => r.Column))
  525. {
  526. ColumnOffset++;
  527. columnsToRender = CalculateViewport (Viewport).ToArray ();
  528. // if we are already scrolled to the last column then break
  529. // this will prevent any theoretical infinite loop
  530. if (ColumnOffset >= Table.Columns - 1)
  531. {
  532. break;
  533. }
  534. }
  535. }
  536. else
  537. {
  538. ColumnOffset = SelectedColumn;
  539. }
  540. }
  541. //if we have scrolled too far down
  542. if (SelectedRow >= RowOffset + (Viewport.Height - headerHeight))
  543. {
  544. RowOffset = SelectedRow - (Viewport.Height - headerHeight) + 1;
  545. }
  546. //if we have scrolled too far up
  547. if (SelectedRow < RowOffset)
  548. {
  549. RowOffset = SelectedRow;
  550. }
  551. }
  552. /// <summary>
  553. /// Updates <see cref="ColumnOffset"/> and <see cref="RowOffset"/> where they are outside the bounds of the table
  554. /// (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  555. /// </summary>
  556. /// <remarks>
  557. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDraw()"/>
  558. /// </remarks>
  559. public void EnsureValidScrollOffsets ()
  560. {
  561. if (TableIsNullOrInvisible ())
  562. {
  563. return;
  564. }
  565. ColumnOffset = Math.Max (Math.Min (ColumnOffset, Table.Columns - 1), 0);
  566. RowOffset = Math.Max (Math.Min (RowOffset, Table.Rows - 1), 0);
  567. }
  568. /// <summary>
  569. /// Updates <see cref="SelectedColumn"/>, <see cref="SelectedRow"/> and <see cref="MultiSelectedRegions"/> where
  570. /// they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if
  571. /// <see cref="Table"/> has not been set.
  572. /// </summary>
  573. /// <remarks>
  574. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDraw()"/>
  575. /// </remarks>
  576. public void EnsureValidSelection ()
  577. {
  578. if (TableIsNullOrInvisible ())
  579. {
  580. // Table doesn't exist, we should probably clear those selections
  581. ClearMultiSelectedRegions (false);
  582. return;
  583. }
  584. SelectedColumn = Math.Max (Math.Min (SelectedColumn, Table.Columns - 1), 0);
  585. SelectedRow = Math.Max (Math.Min (SelectedRow, Table.Rows - 1), 0);
  586. // If SelectedColumn is invisible move it to a visible one
  587. SelectedColumn = GetNearestVisibleColumn (SelectedColumn, true, true);
  588. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  589. MultiSelectedRegions.Clear ();
  590. // evaluate
  591. foreach (TableSelection region in oldRegions)
  592. {
  593. // ignore regions entirely below current table state
  594. if (region.Rectangle.Top >= Table.Rows)
  595. {
  596. continue;
  597. }
  598. // ignore regions entirely too far right of table columns
  599. if (region.Rectangle.Left >= Table.Columns)
  600. {
  601. continue;
  602. }
  603. // ensure region's origin exists
  604. region.Origin = new (
  605. Math.Max (Math.Min (region.Origin.X, Table.Columns - 1), 0),
  606. Math.Max (Math.Min (region.Origin.Y, Table.Rows - 1), 0)
  607. );
  608. // ensure regions do not go over edge of table bounds
  609. region.Rectangle = Rectangle.FromLTRB (
  610. region.Rectangle.Left,
  611. region.Rectangle.Top,
  612. Math.Max (Math.Min (region.Rectangle.Right, Table.Columns), 0),
  613. Math.Max (Math.Min (region.Rectangle.Bottom, Table.Rows), 0)
  614. );
  615. MultiSelectedRegions.Push (region);
  616. }
  617. }
  618. /// <summary>
  619. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the
  620. /// selected cell
  621. /// </summary>
  622. /// <returns></returns>
  623. public IEnumerable<Point> GetAllSelectedCells ()
  624. {
  625. if (TableIsNullOrInvisible () || Table.Rows == 0)
  626. {
  627. return Enumerable.Empty<Point> ();
  628. }
  629. EnsureValidSelection ();
  630. HashSet<Point> toReturn = new ();
  631. // If there are one or more rectangular selections
  632. if (MultiSelect && MultiSelectedRegions.Any ())
  633. {
  634. // 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
  635. int yMin = MultiSelectedRegions.Min (r => r.Rectangle.Top);
  636. int yMax = MultiSelectedRegions.Max (r => r.Rectangle.Bottom);
  637. int xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rectangle.Left);
  638. int xMax = FullRowSelect ? Table.Columns : MultiSelectedRegions.Max (r => r.Rectangle.Right);
  639. for (int y = yMin; y < yMax; y++)
  640. {
  641. for (int x = xMin; x < xMax; x++)
  642. {
  643. if (IsSelected (x, y))
  644. {
  645. toReturn.Add (new (x, y));
  646. }
  647. }
  648. }
  649. }
  650. // if there are no region selections then it is just the active cell
  651. // if we are selecting the full row
  652. if (FullRowSelect)
  653. {
  654. // all cells in active row are selected
  655. for (var x = 0; x < Table.Columns; x++)
  656. {
  657. toReturn.Add (new (x, SelectedRow));
  658. }
  659. }
  660. else
  661. {
  662. // Not full row select and no multi selections
  663. toReturn.Add (new (SelectedColumn, SelectedRow));
  664. }
  665. return toReturn;
  666. }
  667. /// <summary>
  668. /// <para>
  669. /// Returns true if the given cell is selected either because it is the active cell or part of a multi cell
  670. /// selection (e.g. <see cref="FullRowSelect"/>).
  671. /// </para>
  672. /// <remarks>Returns <see langword="false"/> if <see cref="ColumnStyle.Visible"/> is <see langword="false"/>.</remarks>
  673. /// </summary>
  674. /// <param name="col"></param>
  675. /// <param name="row"></param>
  676. /// <returns></returns>
  677. public bool IsSelected (int col, int row)
  678. {
  679. if (!IsColumnVisible (col))
  680. {
  681. return false;
  682. }
  683. if (GetMultiSelectedRegionsContaining (col, row).Any ())
  684. {
  685. return true;
  686. }
  687. return row == SelectedRow && (col == SelectedColumn || FullRowSelect);
  688. }
  689. ///<inheritdoc/>
  690. protected override bool OnMouseEvent (MouseEventArgs me)
  691. {
  692. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  693. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  694. && me.Flags != MouseFlags.WheeledDown
  695. && me.Flags != MouseFlags.WheeledUp
  696. && me.Flags != MouseFlags.WheeledLeft
  697. && me.Flags != MouseFlags.WheeledRight)
  698. {
  699. return false;
  700. }
  701. if (!HasFocus && CanFocus)
  702. {
  703. SetFocus ();
  704. }
  705. if (TableIsNullOrInvisible ())
  706. {
  707. return false;
  708. }
  709. // Scroll wheel flags
  710. switch (me.Flags)
  711. {
  712. case MouseFlags.WheeledDown:
  713. RowOffset++;
  714. EnsureValidScrollOffsets ();
  715. //SetNeedsDraw ();
  716. return true;
  717. case MouseFlags.WheeledUp:
  718. RowOffset--;
  719. EnsureValidScrollOffsets ();
  720. //SetNeedsDraw ();
  721. return true;
  722. case MouseFlags.WheeledRight:
  723. ColumnOffset++;
  724. EnsureValidScrollOffsets ();
  725. //SetNeedsDraw ();
  726. return true;
  727. case MouseFlags.WheeledLeft:
  728. ColumnOffset--;
  729. EnsureValidScrollOffsets ();
  730. //SetNeedsDraw ();
  731. return true;
  732. }
  733. int boundsX = me.Position.X;
  734. int boundsY = me.Position.Y;
  735. if (me.Flags.HasFlag (MouseFlags.Button1Clicked))
  736. {
  737. if (scrollLeftPoint != null
  738. && scrollLeftPoint.Value.X == boundsX
  739. && scrollLeftPoint.Value.Y == boundsY)
  740. {
  741. ColumnOffset--;
  742. EnsureValidScrollOffsets ();
  743. SetNeedsDraw ();
  744. }
  745. if (scrollRightPoint != null
  746. && scrollRightPoint.Value.X == boundsX
  747. && scrollRightPoint.Value.Y == boundsY)
  748. {
  749. ColumnOffset++;
  750. EnsureValidScrollOffsets ();
  751. SetNeedsDraw ();
  752. }
  753. Point? hit = ScreenToCell (boundsX, boundsY);
  754. if (hit is { })
  755. {
  756. if (MultiSelect && HasControlOrAlt (me))
  757. {
  758. UnionSelection (hit.Value.X, hit.Value.Y);
  759. }
  760. else
  761. {
  762. SetSelection (hit.Value.X, hit.Value.Y, me.Flags.HasFlag (MouseFlags.ButtonShift));
  763. }
  764. Update ();
  765. }
  766. }
  767. // Double clicking a cell activates
  768. if (me.Flags == MouseFlags.Button1DoubleClicked)
  769. {
  770. Point? hit = ScreenToCell (boundsX, boundsY);
  771. if (hit is { })
  772. {
  773. return OnCellActivated (new (Table, hit.Value.X, hit.Value.Y));
  774. }
  775. }
  776. return me.Handled;
  777. }
  778. ///<inheritdoc/>
  779. protected override bool OnDrawingContent ()
  780. {
  781. Move (0, 0);
  782. scrollRightPoint = null;
  783. scrollLeftPoint = null;
  784. // What columns to render at what X offset in viewport
  785. ColumnToRender [] columnsToRender = CalculateViewport (Viewport).ToArray ();
  786. SetAttribute (GetAttributeForRole (VisualRole.Normal));
  787. //invalidate current row (prevents scrolling around leaving old characters in the frame
  788. AddStr (new (' ', Viewport.Width));
  789. var line = 0;
  790. if (ShouldRenderHeaders ())
  791. {
  792. // Render something like:
  793. /*
  794. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  795. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  796. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  797. */
  798. if (Style.ShowHorizontalHeaderOverline)
  799. {
  800. RenderHeaderOverline (line, Viewport.Width, columnsToRender);
  801. line++;
  802. }
  803. if (Style.ShowHeaders)
  804. {
  805. RenderHeaderMidline (line, columnsToRender);
  806. line++;
  807. }
  808. if (Style.ShowHorizontalHeaderUnderline)
  809. {
  810. RenderHeaderUnderline (line, Viewport.Width, columnsToRender);
  811. line++;
  812. }
  813. }
  814. int headerLinesConsumed = line;
  815. //render the cells
  816. for (; line < Viewport.Height; line++)
  817. {
  818. ClearLine (line, Viewport.Width);
  819. //work out what Row to render
  820. int rowToRender = RowOffset + (line - headerLinesConsumed);
  821. //if we have run off the end of the table
  822. if (TableIsNullOrInvisible () || rowToRender < 0)
  823. {
  824. continue;
  825. }
  826. // No more data
  827. if (rowToRender >= Table.Rows)
  828. {
  829. if (rowToRender == Table.Rows && Style.ShowHorizontalBottomline)
  830. {
  831. RenderBottomLine (line, Viewport.Width, columnsToRender);
  832. }
  833. continue;
  834. }
  835. RenderRow (line, rowToRender, columnsToRender);
  836. }
  837. return true;
  838. }
  839. /// <inheritdoc/>
  840. protected override bool OnKeyDown (Key key)
  841. {
  842. if (TableIsNullOrInvisible ())
  843. {
  844. return false;
  845. }
  846. // If the key was bound to key command, let normal KeyDown processing happen. This enables overriding the default handling.
  847. // See: https://github.com/gui-cs/Terminal.Gui/issues/3950#issuecomment-2807350939
  848. if (KeyBindings.TryGet (key, out _))
  849. {
  850. return false;
  851. }
  852. if (CollectionNavigator != null
  853. && HasFocus
  854. && Table.Rows != 0
  855. && key != KeyBindings.GetFirstFromCommands (Command.Accept)
  856. && key != CellActivationKey
  857. && CollectionNavigator.Matcher.IsCompatibleKey (key)
  858. && !key.KeyCode.HasFlag (KeyCode.CtrlMask)
  859. && !key.KeyCode.HasFlag (KeyCode.AltMask)
  860. && Rune.IsLetterOrDigit ((Rune)key))
  861. {
  862. return CycleToNextTableEntryBeginningWith (key);
  863. }
  864. return false;
  865. }
  866. /// <summary>Moves the selection down by one page</summary>
  867. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  868. public void PageDown (bool extend)
  869. {
  870. ChangeSelectionByOffset (0, Viewport.Height - GetHeaderHeightIfAny (), extend);
  871. Update ();
  872. }
  873. /// <summary>Moves the selection up by one page</summary>
  874. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  875. public void PageUp (bool extend)
  876. {
  877. ChangeSelectionByOffset (0, -(Viewport.Height - GetHeaderHeightIfAny ()), extend);
  878. Update ();
  879. }
  880. /// <summary>
  881. /// Positions the cursor in the area of the screen in which the start of the active cell is rendered. Calls base
  882. /// implementation if active cell is not visible due to scrolling or table is loaded etc
  883. /// </summary>
  884. public override Point? PositionCursor ()
  885. {
  886. if (TableIsNullOrInvisible ())
  887. {
  888. return base.PositionCursor ();
  889. }
  890. Point? screenPoint = CellToScreen (SelectedColumn, SelectedRow);
  891. if (screenPoint is { })
  892. {
  893. Move (screenPoint.Value.X, screenPoint.Value.Y);
  894. return null; //screenPoint;
  895. }
  896. return null;
  897. }
  898. /// <summary>
  899. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  900. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  901. /// bounds.
  902. /// </summary>
  903. /// <param name="clientX">X offset from the top left of the control.</param>
  904. /// <param name="clientY">Y offset from the top left of the control.</param>
  905. /// <returns>Cell clicked or null.</returns>
  906. public Point? ScreenToCell (int clientX, int clientY) { return ScreenToCell (clientX, clientY, out _, out _); }
  907. /// <summary>
  908. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  909. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  910. /// bounds.
  911. /// </summary>
  912. /// <param name="client">offset from the top left of the control.</param>
  913. /// <returns>The position.</returns>
  914. public Point? ScreenToCell (Point client) { return ScreenToCell (client, out _, out _); }
  915. /// <summary>
  916. /// . Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  917. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  918. /// bounds.
  919. /// </summary>
  920. /// <param name="clientX">X offset from the top left of the control.</param>
  921. /// <param name="clientY">Y offset from the top left of the control.</param>
  922. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  923. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny) { return ScreenToCell (clientX, clientY, out headerIfAny, out _); }
  924. /// <summary>
  925. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  926. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  927. /// bounds.
  928. /// </summary>
  929. /// <param name="client">offset from the top left of the control.</param>
  930. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  931. public Point? ScreenToCell (Point client, out int? headerIfAny) { return ScreenToCell (client, out headerIfAny, out _); }
  932. /// <summary>
  933. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  934. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  935. /// bounds.
  936. /// </summary>
  937. /// <param name="clientX">X offset from the top left of the control.</param>
  938. /// <param name="clientY">Y offset from the top left of the control.</param>
  939. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  940. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  941. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny, out int? offsetX)
  942. {
  943. headerIfAny = null;
  944. offsetX = null;
  945. if (TableIsNullOrInvisible ())
  946. {
  947. return null;
  948. }
  949. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Viewport);
  950. int headerHeight = GetHeaderHeightIfAny ();
  951. ColumnToRender col = viewPort.LastOrDefault (c => c.X <= clientX);
  952. // Click is on the header section of rendered UI
  953. if (clientY < headerHeight)
  954. {
  955. headerIfAny = col?.Column;
  956. offsetX = col is { } ? clientX - col.X : null;
  957. return null;
  958. }
  959. int rowIdx = RowOffset - headerHeight + clientY;
  960. // if click is off bottom of the rows don't give an
  961. // invalid index back to user!
  962. if (rowIdx >= Table.Rows)
  963. {
  964. return null;
  965. }
  966. if (col is { } && rowIdx >= 0)
  967. {
  968. offsetX = clientX - col.X;
  969. return new Point (col.Column, rowIdx);
  970. }
  971. return null;
  972. }
  973. /// <summary>
  974. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  975. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  976. /// bounds.
  977. /// </summary>
  978. /// <param name="client">offset from the top left of the control.</param>
  979. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  980. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  981. public Point? ScreenToCell (Point client, out int? headerIfAny, out int? offsetX)
  982. {
  983. return ScreenToCell (client.X, client.Y, out headerIfAny, out offsetX);
  984. }
  985. /// <summary>
  986. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old
  987. /// selection regions)
  988. /// </summary>
  989. public void SelectAll ()
  990. {
  991. if (TableIsNullOrInvisible () || !MultiSelect || Table.Rows == 0)
  992. {
  993. return;
  994. }
  995. ClearMultiSelectedRegions (true);
  996. // 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
  997. MultiSelectedRegions.Push (
  998. new (
  999. new (SelectedColumn, SelectedRow),
  1000. new (0, 0, Table.Columns, table.Rows)
  1001. )
  1002. );
  1003. Update ();
  1004. }
  1005. /// <summary>This event is raised when the selected cell in the table changes.</summary>
  1006. public event EventHandler<SelectedCellChangedEventArgs> SelectedCellChanged;
  1007. /// <summary>
  1008. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in
  1009. /// <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  1010. /// </summary>
  1011. /// <param name="col"></param>
  1012. /// <param name="row"></param>
  1013. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  1014. public void SetSelection (int col, int row, bool extendExistingSelection)
  1015. {
  1016. // if we are trying to increase the column index then
  1017. // we are moving right otherwise we are moving left
  1018. bool lookRight = col > selectedColumn;
  1019. col = GetNearestVisibleColumn (col, lookRight, true);
  1020. if (!MultiSelect || !extendExistingSelection)
  1021. {
  1022. ClearMultiSelectedRegions (true);
  1023. }
  1024. if (extendExistingSelection)
  1025. {
  1026. // If we are extending current selection but there isn't one
  1027. if (MultiSelectedRegions.Count == 0 || MultiSelectedRegions.All (m => m.IsToggled))
  1028. {
  1029. // Create a new region between the old active cell and the new cell
  1030. TableSelection rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  1031. MultiSelectedRegions.Push (rect);
  1032. }
  1033. else
  1034. {
  1035. // Extend the current head selection to include the new cell
  1036. TableSelection head = MultiSelectedRegions.Pop ();
  1037. TableSelection newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  1038. MultiSelectedRegions.Push (newRect);
  1039. }
  1040. }
  1041. SelectedColumn = col;
  1042. SelectedRow = row;
  1043. }
  1044. /// <summary>
  1045. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> /
  1046. /// <see cref="RowOffset"/>) etc
  1047. /// </summary>
  1048. /// <remarks>This always calls <see cref="View.SetNeedsDraw()"/></remarks>
  1049. public void Update ()
  1050. {
  1051. if (!IsInitialized || TableIsNullOrInvisible ())
  1052. {
  1053. SetNeedsDraw ();
  1054. return;
  1055. }
  1056. EnsureValidScrollOffsets ();
  1057. EnsureValidSelection ();
  1058. EnsureSelectedCellIsVisible ();
  1059. SetNeedsDraw ();
  1060. }
  1061. /// <summary>Invokes the <see cref="CellActivated"/> event</summary>
  1062. /// <param name="args"></param>
  1063. /// <returns><see langword="true"/> if the CellActivated event was raised.</returns>
  1064. protected virtual bool OnCellActivated (CellActivatedEventArgs args)
  1065. {
  1066. CellActivated?.Invoke (this, args);
  1067. return CellActivated is { };
  1068. }
  1069. /// <summary>Invokes the <see cref="CellToggled"/> event</summary>
  1070. /// <param name="args"></param>
  1071. protected virtual void OnCellToggled (CellToggledEventArgs args) { CellToggled?.Invoke (this, args); }
  1072. /// <summary>Invokes the <see cref="SelectedCellChanged"/> event</summary>
  1073. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args) { SelectedCellChanged?.Invoke (this, args); }
  1074. /// <summary>
  1075. /// Override to provide custom multi-coloring to cells. Use methods like <see cref="View.AddStr(string)"/>.
  1076. /// The cursor will already be in the correct position when rendering. You must render the full
  1077. /// <paramref name="render"/> or the view will not look right. For simpler color provision 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. AddRune ((Rune)render [0]);
  1096. if (render.Length > 1)
  1097. {
  1098. SetAttribute (cellAttribute);
  1099. AddStr (render.Substring (1));
  1100. }
  1101. }
  1102. }
  1103. else
  1104. {
  1105. SetAttribute (cellAttribute);
  1106. 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 (int col, int row, Rune ch)
  1128. {
  1129. Move (col, row);
  1130. 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 (Application.Screen.Height == 0)
  1285. {
  1286. return;
  1287. }
  1288. Move (0, row);
  1289. SetAttribute (GetAttributeForRole (VisualRole.Normal));
  1290. 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 != null)
  1346. {
  1347. SelectedRow = match.Value;
  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 (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. 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 (Application.Screen.Height > 0)
  1515. {
  1516. AddRuneAt (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 (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. 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. }