TableView.cs 79 KB

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