TableView.cs 84 KB

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