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.ToggleChecked,
  223. () =>
  224. {
  225. ToggleCurrentCellSelection ();
  226. return true;
  227. }
  228. );
  229. // Default keybindings for this view
  230. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  231. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  232. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  233. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  234. KeyBindings.Add (KeyCode.PageUp, Command.PageUp);
  235. KeyBindings.Add (KeyCode.PageDown, Command.PageDown);
  236. KeyBindings.Add (KeyCode.Home, Command.LeftHome);
  237. KeyBindings.Add (KeyCode.End, Command.RightEnd);
  238. KeyBindings.Add (KeyCode.Home | KeyCode.CtrlMask, Command.TopHome);
  239. KeyBindings.Add (KeyCode.End | KeyCode.CtrlMask, Command.BottomEnd);
  240. KeyBindings.Add (KeyCode.CursorLeft | KeyCode.ShiftMask, Command.LeftExtend);
  241. KeyBindings.Add (KeyCode.CursorRight | KeyCode.ShiftMask, Command.RightExtend);
  242. KeyBindings.Add (KeyCode.CursorUp | KeyCode.ShiftMask, Command.LineUpExtend);
  243. KeyBindings.Add (KeyCode.CursorDown | KeyCode.ShiftMask, Command.LineDownExtend);
  244. KeyBindings.Add (KeyCode.PageUp | KeyCode.ShiftMask, Command.PageUpExtend);
  245. KeyBindings.Add (KeyCode.PageDown | KeyCode.ShiftMask, Command.PageDownExtend);
  246. KeyBindings.Add (KeyCode.Home | KeyCode.ShiftMask, Command.LeftHomeExtend);
  247. KeyBindings.Add (KeyCode.End | KeyCode.ShiftMask, Command.RightEndExtend);
  248. KeyBindings.Add (KeyCode.Home | KeyCode.CtrlMask | KeyCode.ShiftMask, Command.TopHomeExtend);
  249. KeyBindings.Add (KeyCode.End | KeyCode.CtrlMask | KeyCode.ShiftMask, Command.BottomEndExtend);
  250. KeyBindings.Add (KeyCode.A | KeyCode.CtrlMask, Command.SelectAll);
  251. KeyBindings.Add (CellActivationKey, Command.Accept);
  252. }
  253. // TODO: Update to use Key instead of KeyCode
  254. /// <summary>The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.</summary>
  255. public KeyCode CellActivationKey
  256. {
  257. get => cellActivationKey;
  258. set
  259. {
  260. if (cellActivationKey != value)
  261. {
  262. KeyBindings.Replace (cellActivationKey, value);
  263. // of API user is mixing and matching old and new methods of keybinding then they may have lost
  264. // the old binding (e.g. with ClearKeybindings) so KeyBindings.Replace alone will fail
  265. KeyBindings.Add (value, Command.Accept);
  266. cellActivationKey = value;
  267. }
  268. }
  269. }
  270. /// <summary>Navigator for cycling the selected item in the table by typing. Set to null to disable this feature.</summary>
  271. public CollectionNavigatorBase CollectionNavigator { get; set; }
  272. /// <summary>
  273. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering
  274. /// the view.
  275. /// </summary>
  276. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  277. public int ColumnOffset
  278. {
  279. get => columnOffset;
  280. //try to prevent this being set to an out of bounds column
  281. set => columnOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Columns - 1, value));
  282. }
  283. /// <summary>True to select the entire row at once. False to select individual cells. Defaults to false</summary>
  284. public bool FullRowSelect { get; set; }
  285. /// <summary>
  286. /// The maximum number of characters to render in any given column. This prevents one long column from pushing
  287. /// out all the others
  288. /// </summary>
  289. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  290. /// <summary>The minimum number of characters to render in any given column.</summary>
  291. public int MinCellWidth { get; set; }
  292. /// <summary>True to allow regions to be selected</summary>
  293. /// <value></value>
  294. public bool MultiSelect { get; set; } = true;
  295. /// <summary>
  296. /// When <see cref="MultiSelect"/> is enabled this property contain all rectangles of selected cells. Rectangles
  297. /// describe column/rows selected in <see cref="Table"/> (not screen coordinates)
  298. /// </summary>
  299. /// <returns></returns>
  300. public Stack<TableSelection> MultiSelectedRegions { get; } = new ();
  301. /// <summary>The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/></summary>
  302. public string NullSymbol { get; set; } = "-";
  303. /// <summary>
  304. /// Vertical scroll offset. The index of the first row in <see cref="Table"/> to display in the first non header
  305. /// line of the control when rendering the view.
  306. /// </summary>
  307. public int RowOffset
  308. {
  309. get => rowOffset;
  310. set => rowOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Rows - 1, value));
  311. }
  312. /// <summary>The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected</summary>
  313. public int SelectedColumn
  314. {
  315. get => selectedColumn;
  316. set
  317. {
  318. int oldValue = selectedColumn;
  319. //try to prevent this being set to an out of bounds column
  320. selectedColumn = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Columns - 1, Math.Max (0, value));
  321. if (oldValue != selectedColumn)
  322. {
  323. OnSelectedCellChanged (
  324. new SelectedCellChangedEventArgs (
  325. Table,
  326. oldValue,
  327. SelectedColumn,
  328. SelectedRow,
  329. SelectedRow
  330. )
  331. );
  332. }
  333. }
  334. }
  335. /// <summary>The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected</summary>
  336. public int SelectedRow
  337. {
  338. get => selectedRow;
  339. set
  340. {
  341. int oldValue = selectedRow;
  342. selectedRow = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Rows - 1, Math.Max (0, value));
  343. if (oldValue != selectedRow)
  344. {
  345. OnSelectedCellChanged (
  346. new SelectedCellChangedEventArgs (
  347. Table,
  348. SelectedColumn,
  349. SelectedColumn,
  350. oldValue,
  351. selectedRow
  352. )
  353. );
  354. }
  355. }
  356. }
  357. /// <summary>
  358. /// The symbol to add after each cell value and header value to visually seperate values (if not using vertical
  359. /// gridlines)
  360. /// </summary>
  361. public char SeparatorSymbol { get; set; } = ' ';
  362. /// <summary>Contains options for changing how the table is rendered</summary>
  363. public TableStyle Style
  364. {
  365. get => style;
  366. set
  367. {
  368. style = value;
  369. Update ();
  370. }
  371. }
  372. /// <summary>The data table to render in the view. Setting this property automatically updates and redraws the control.</summary>
  373. public ITableSource Table
  374. {
  375. get => table;
  376. set
  377. {
  378. table = value;
  379. Update ();
  380. }
  381. }
  382. /// <summary>
  383. /// This event is raised when a cell is activated e.g. by double clicking or pressing
  384. /// <see cref="CellActivationKey"/>
  385. /// </summary>
  386. public event EventHandler<CellActivatedEventArgs> CellActivated;
  387. /// <summary>This event is raised when a cell is toggled (see <see cref="Command.ToggleChecked"/></summary>
  388. public event EventHandler<CellToggledEventArgs> CellToggled;
  389. /// <summary>
  390. /// Returns the screen position (relative to the control client area) that the given cell is rendered or null if
  391. /// it is outside the current scroll area or no table is loaded
  392. /// </summary>
  393. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for</param>
  394. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  395. /// <returns></returns>
  396. public Point? CellToScreen (int tableColumn, int tableRow)
  397. {
  398. if (TableIsNullOrInvisible ())
  399. {
  400. return null;
  401. }
  402. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Bounds);
  403. int headerHeight = GetHeaderHeightIfAny ();
  404. ColumnToRender colHit = viewPort.FirstOrDefault (c => c.Column == tableColumn);
  405. // current column is outside the scroll area
  406. if (colHit is null)
  407. {
  408. return null;
  409. }
  410. // the cell is too far up above the current scroll area
  411. if (RowOffset > tableRow)
  412. {
  413. return null;
  414. }
  415. // the cell is way down below the scroll area and off the screen
  416. if (tableRow > RowOffset + (Bounds.Height - headerHeight))
  417. {
  418. return null;
  419. }
  420. return new Point (colHit.X, tableRow + headerHeight - RowOffset);
  421. }
  422. /// <summary>
  423. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally
  424. /// starting a box selection (see <see cref="MultiSelect"/>)
  425. /// </summary>
  426. /// <param name="offsetX">Offset in number of columns</param>
  427. /// <param name="offsetY">Offset in number of rows</param>
  428. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  429. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  430. {
  431. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
  432. Update ();
  433. }
  434. /// <summary>Moves or extends the selection to the last cell in the current row</summary>
  435. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  436. public void ChangeSelectionToEndOfRow (bool extend)
  437. {
  438. SetSelection (Table.Columns - 1, SelectedRow, extend);
  439. Update ();
  440. }
  441. /// <summary>
  442. /// Moves or extends the selection to the final cell in the table (nX,nY). If <see cref="FullRowSelect"/> is
  443. /// enabled then selection instead moves to ( <see cref="SelectedColumn"/>,nY) i.e. no horizontal scrolling.
  444. /// </summary>
  445. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  446. public void ChangeSelectionToEndOfTable (bool extend)
  447. {
  448. int finalColumn = Table.Columns - 1;
  449. SetSelection (FullRowSelect ? SelectedColumn : finalColumn, Table.Rows - 1, extend);
  450. Update ();
  451. }
  452. /// <summary>Moves or extends the selection to the first cell in the current row</summary>
  453. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  454. public void ChangeSelectionToStartOfRow (bool extend)
  455. {
  456. SetSelection (0, SelectedRow, extend);
  457. Update ();
  458. }
  459. /// <summary>
  460. /// Moves or extends the selection to the first cell in the table (0,0). If <see cref="FullRowSelect"/> is enabled
  461. /// then selection instead moves to ( <see cref="SelectedColumn"/>,0) i.e. no horizontal scrolling.
  462. /// </summary>
  463. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  464. public void ChangeSelectionToStartOfTable (bool extend)
  465. {
  466. SetSelection (FullRowSelect ? SelectedColumn : 0, 0, extend);
  467. Update ();
  468. }
  469. /// <summary>
  470. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has
  471. /// not been set.
  472. /// </summary>
  473. /// <remarks>
  474. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/>
  475. /// </remarks>
  476. public void EnsureSelectedCellIsVisible ()
  477. {
  478. if (Table is null || Table.Columns <= 0)
  479. {
  480. return;
  481. }
  482. ColumnToRender [] columnsToRender = CalculateViewport (Bounds).ToArray ();
  483. int headerHeight = GetHeaderHeightIfAny ();
  484. //if we have scrolled too far to the left
  485. if (SelectedColumn < columnsToRender.Min (r => r.Column))
  486. {
  487. ColumnOffset = SelectedColumn;
  488. }
  489. //if we have scrolled too far to the right
  490. if (SelectedColumn > columnsToRender.Max (r => r.Column))
  491. {
  492. if (Style.SmoothHorizontalScrolling)
  493. {
  494. // Scroll right 1 column at a time until the users selected column is visible
  495. while (SelectedColumn > columnsToRender.Max (r => r.Column))
  496. {
  497. ColumnOffset++;
  498. columnsToRender = CalculateViewport (Bounds).ToArray ();
  499. // if we are already scrolled to the last column then break
  500. // this will prevent any theoretical infinite loop
  501. if (ColumnOffset >= Table.Columns - 1)
  502. {
  503. break;
  504. }
  505. }
  506. }
  507. else
  508. {
  509. ColumnOffset = SelectedColumn;
  510. }
  511. }
  512. //if we have scrolled too far down
  513. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight))
  514. {
  515. RowOffset = SelectedRow - (Bounds.Height - headerHeight) + 1;
  516. }
  517. //if we have scrolled too far up
  518. if (SelectedRow < RowOffset)
  519. {
  520. RowOffset = SelectedRow;
  521. }
  522. }
  523. /// <summary>
  524. /// Updates <see cref="ColumnOffset"/> and <see cref="RowOffset"/> where they are outside the bounds of the table
  525. /// (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  526. /// </summary>
  527. /// <remarks>
  528. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/>
  529. /// </remarks>
  530. public void EnsureValidScrollOffsets ()
  531. {
  532. if (TableIsNullOrInvisible ())
  533. {
  534. return;
  535. }
  536. ColumnOffset = Math.Max (Math.Min (ColumnOffset, Table.Columns - 1), 0);
  537. RowOffset = Math.Max (Math.Min (RowOffset, Table.Rows - 1), 0);
  538. }
  539. /// <summary>
  540. /// Updates <see cref="SelectedColumn"/>, <see cref="SelectedRow"/> and <see cref="MultiSelectedRegions"/> where
  541. /// they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if
  542. /// <see cref="Table"/> has not been set.
  543. /// </summary>
  544. /// <remarks>
  545. /// Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/>
  546. /// </remarks>
  547. public void EnsureValidSelection ()
  548. {
  549. if (TableIsNullOrInvisible ())
  550. {
  551. // Table doesn't exist, we should probably clear those selections
  552. ClearMultiSelectedRegions (false);
  553. return;
  554. }
  555. SelectedColumn = Math.Max (Math.Min (SelectedColumn, Table.Columns - 1), 0);
  556. SelectedRow = Math.Max (Math.Min (SelectedRow, Table.Rows - 1), 0);
  557. // If SelectedColumn is invisible move it to a visible one
  558. SelectedColumn = GetNearestVisibleColumn (SelectedColumn, true, true);
  559. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  560. MultiSelectedRegions.Clear ();
  561. // evaluate
  562. foreach (TableSelection region in oldRegions)
  563. {
  564. // ignore regions entirely below current table state
  565. if (region.Rect.Top >= Table.Rows)
  566. {
  567. continue;
  568. }
  569. // ignore regions entirely too far right of table columns
  570. if (region.Rect.Left >= Table.Columns)
  571. {
  572. continue;
  573. }
  574. // ensure region's origin exists
  575. region.Origin = new Point (
  576. Math.Max (Math.Min (region.Origin.X, Table.Columns - 1), 0),
  577. Math.Max (Math.Min (region.Origin.Y, Table.Rows - 1), 0)
  578. );
  579. // ensure regions do not go over edge of table bounds
  580. region.Rect = Rect.FromLTRB (
  581. region.Rect.Left,
  582. region.Rect.Top,
  583. Math.Max (Math.Min (region.Rect.Right, Table.Columns), 0),
  584. Math.Max (Math.Min (region.Rect.Bottom, Table.Rows), 0)
  585. );
  586. MultiSelectedRegions.Push (region);
  587. }
  588. }
  589. /// <summary>
  590. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the
  591. /// selected cell
  592. /// </summary>
  593. /// <returns></returns>
  594. public IEnumerable<Point> GetAllSelectedCells ()
  595. {
  596. if (TableIsNullOrInvisible () || Table.Rows == 0)
  597. {
  598. return Enumerable.Empty<Point> ();
  599. }
  600. EnsureValidSelection ();
  601. HashSet<Point> toReturn = new ();
  602. // If there are one or more rectangular selections
  603. if (MultiSelect && MultiSelectedRegions.Any ())
  604. {
  605. // 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
  606. int yMin = MultiSelectedRegions.Min (r => r.Rect.Top);
  607. int yMax = MultiSelectedRegions.Max (r => r.Rect.Bottom);
  608. int xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rect.Left);
  609. int xMax = FullRowSelect ? Table.Columns : MultiSelectedRegions.Max (r => r.Rect.Right);
  610. for (int y = yMin; y < yMax; y++)
  611. {
  612. for (int x = xMin; x < xMax; x++)
  613. {
  614. if (IsSelected (x, y))
  615. {
  616. toReturn.Add (new Point (x, y));
  617. }
  618. }
  619. }
  620. }
  621. // if there are no region selections then it is just the active cell
  622. // if we are selecting the full row
  623. if (FullRowSelect)
  624. {
  625. // all cells in active row are selected
  626. for (var x = 0; x < Table.Columns; x++)
  627. {
  628. toReturn.Add (new Point (x, SelectedRow));
  629. }
  630. }
  631. else
  632. {
  633. // Not full row select and no multi selections
  634. toReturn.Add (new Point (SelectedColumn, SelectedRow));
  635. }
  636. return toReturn;
  637. }
  638. /// <summary>
  639. /// <para>
  640. /// Returns true if the given cell is selected either because it is the active cell or part of a multi cell
  641. /// selection (e.g. <see cref="FullRowSelect"/>).
  642. /// </para>
  643. /// <remarks>Returns <see langword="false"/> if <see cref="ColumnStyle.Visible"/> is <see langword="false"/>.</remarks>
  644. /// </summary>
  645. /// <param name="col"></param>
  646. /// <param name="row"></param>
  647. /// <returns></returns>
  648. public bool IsSelected (int col, int row)
  649. {
  650. if (!IsColumnVisible (col))
  651. {
  652. return false;
  653. }
  654. if (GetMultiSelectedRegionsContaining (col, row).Any ())
  655. {
  656. return true;
  657. }
  658. return row == SelectedRow && (col == SelectedColumn || FullRowSelect);
  659. }
  660. ///<inheritdoc/>
  661. public override bool MouseEvent (MouseEvent me)
  662. {
  663. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  664. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  665. && me.Flags != MouseFlags.WheeledDown
  666. && me.Flags != MouseFlags.WheeledUp
  667. && me.Flags != MouseFlags.WheeledLeft
  668. && me.Flags != MouseFlags.WheeledRight)
  669. {
  670. return false;
  671. }
  672. if (!HasFocus && CanFocus)
  673. {
  674. SetFocus ();
  675. }
  676. if (TableIsNullOrInvisible ())
  677. {
  678. return false;
  679. }
  680. // Scroll wheel flags
  681. switch (me.Flags)
  682. {
  683. case MouseFlags.WheeledDown:
  684. RowOffset++;
  685. EnsureValidScrollOffsets ();
  686. SetNeedsDisplay ();
  687. return true;
  688. case MouseFlags.WheeledUp:
  689. RowOffset--;
  690. EnsureValidScrollOffsets ();
  691. SetNeedsDisplay ();
  692. return true;
  693. case MouseFlags.WheeledRight:
  694. ColumnOffset++;
  695. EnsureValidScrollOffsets ();
  696. SetNeedsDisplay ();
  697. return true;
  698. case MouseFlags.WheeledLeft:
  699. ColumnOffset--;
  700. EnsureValidScrollOffsets ();
  701. SetNeedsDisplay ();
  702. return true;
  703. }
  704. int boundsX = me.X;
  705. int boundsY = me.Y;
  706. if (me.Flags.HasFlag (MouseFlags.Button1Clicked))
  707. {
  708. if (scrollLeftPoint != null
  709. && scrollLeftPoint.Value.X == boundsX
  710. && scrollLeftPoint.Value.Y == boundsY)
  711. {
  712. ColumnOffset--;
  713. EnsureValidScrollOffsets ();
  714. SetNeedsDisplay ();
  715. }
  716. if (scrollRightPoint != null
  717. && scrollRightPoint.Value.X == boundsX
  718. && scrollRightPoint.Value.Y == boundsY)
  719. {
  720. ColumnOffset++;
  721. EnsureValidScrollOffsets ();
  722. SetNeedsDisplay ();
  723. }
  724. Point? hit = ScreenToCell (boundsX, boundsY);
  725. if (hit != null)
  726. {
  727. if (MultiSelect && HasControlOrAlt (me))
  728. {
  729. UnionSelection (hit.Value.X, hit.Value.Y);
  730. }
  731. else
  732. {
  733. SetSelection (hit.Value.X, hit.Value.Y, me.Flags.HasFlag (MouseFlags.ButtonShift));
  734. }
  735. Update ();
  736. }
  737. }
  738. // Double clicking a cell activates
  739. if (me.Flags == MouseFlags.Button1DoubleClicked)
  740. {
  741. Point? hit = ScreenToCell (boundsX, boundsY);
  742. if (hit != null)
  743. {
  744. OnCellActivated (new CellActivatedEventArgs (Table, hit.Value.X, hit.Value.Y));
  745. }
  746. }
  747. return false;
  748. }
  749. ///<inheritdoc/>
  750. public override void OnDrawContent (Rect contentArea)
  751. {
  752. base.OnDrawContent (contentArea);
  753. Move (0, 0);
  754. scrollRightPoint = null;
  755. scrollLeftPoint = null;
  756. // What columns to render at what X offset in viewport
  757. ColumnToRender [] columnsToRender = CalculateViewport (Bounds).ToArray ();
  758. Driver.SetAttribute (GetNormalColor ());
  759. //invalidate current row (prevents scrolling around leaving old characters in the frame
  760. Driver.AddStr (new string (' ', Bounds.Width));
  761. var line = 0;
  762. if (ShouldRenderHeaders ())
  763. {
  764. // Render something like:
  765. /*
  766. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  767. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  768. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  769. */
  770. if (Style.ShowHorizontalHeaderOverline)
  771. {
  772. RenderHeaderOverline (line, Bounds.Width, columnsToRender);
  773. line++;
  774. }
  775. if (Style.ShowHeaders)
  776. {
  777. RenderHeaderMidline (line, columnsToRender);
  778. line++;
  779. }
  780. if (Style.ShowHorizontalHeaderUnderline)
  781. {
  782. RenderHeaderUnderline (line, Bounds.Width, columnsToRender);
  783. line++;
  784. }
  785. }
  786. int headerLinesConsumed = line;
  787. //render the cells
  788. for (; line < Bounds.Height; line++)
  789. {
  790. ClearLine (line, Bounds.Width);
  791. //work out what Row to render
  792. int rowToRender = RowOffset + (line - headerLinesConsumed);
  793. //if we have run off the end of the table
  794. if (TableIsNullOrInvisible () || rowToRender < 0)
  795. {
  796. continue;
  797. }
  798. // No more data
  799. if (rowToRender >= Table.Rows)
  800. {
  801. if (rowToRender == Table.Rows && Style.ShowHorizontalBottomline)
  802. {
  803. RenderBottomLine (line, Bounds.Width, columnsToRender);
  804. }
  805. continue;
  806. }
  807. RenderRow (line, rowToRender, columnsToRender);
  808. }
  809. }
  810. /// <inheritdoc/>
  811. public override bool OnProcessKeyDown (Key keyEvent)
  812. {
  813. if (TableIsNullOrInvisible ())
  814. {
  815. PositionCursor ();
  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, Bounds.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, -(Bounds.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 void PositionCursor ()
  849. {
  850. if (TableIsNullOrInvisible ())
  851. {
  852. base.PositionCursor ();
  853. return;
  854. }
  855. Point? screenPoint = CellToScreen (SelectedColumn, SelectedRow);
  856. if (screenPoint != null)
  857. {
  858. Move (screenPoint.Value.X, screenPoint.Value.Y);
  859. }
  860. }
  861. /// <summary>
  862. /// . Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  863. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  864. /// bounds.
  865. /// </summary>
  866. /// <param name="clientX">X offset from the top left of the control.</param>
  867. /// <param name="clientY">Y offset from the top left of the control.</param>
  868. /// <returns>Cell clicked or null.</returns>
  869. public Point? ScreenToCell (int clientX, int clientY) { return ScreenToCell (clientX, clientY, out _, out _); }
  870. /// <summary>
  871. /// . Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  872. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  873. /// bounds.
  874. /// </summary>
  875. /// <param name="clientX">X offset from the top left of the control.</param>
  876. /// <param name="clientY">Y offset from the top left of the control.</param>
  877. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  878. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny) { return ScreenToCell (clientX, clientY, out headerIfAny, out _); }
  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. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  887. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  888. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny, out int? offsetX)
  889. {
  890. headerIfAny = null;
  891. offsetX = null;
  892. if (TableIsNullOrInvisible ())
  893. {
  894. return null;
  895. }
  896. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Bounds);
  897. int headerHeight = GetHeaderHeightIfAny ();
  898. ColumnToRender col = viewPort.LastOrDefault (c => c.X <= clientX);
  899. // Click is on the header section of rendered UI
  900. if (clientY < headerHeight)
  901. {
  902. headerIfAny = col?.Column;
  903. offsetX = col != null ? clientX - col.X : null;
  904. return null;
  905. }
  906. int rowIdx = RowOffset - headerHeight + clientY;
  907. // if click is off bottom of the rows don't give an
  908. // invalid index back to user!
  909. if (rowIdx >= Table.Rows)
  910. {
  911. return null;
  912. }
  913. if (col != null && rowIdx >= 0)
  914. {
  915. offsetX = clientX - col.X;
  916. return new Point (col.Column, rowIdx);
  917. }
  918. return null;
  919. }
  920. /// <summary>
  921. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old
  922. /// selection regions)
  923. /// </summary>
  924. public void SelectAll ()
  925. {
  926. if (TableIsNullOrInvisible () || !MultiSelect || Table.Rows == 0)
  927. {
  928. return;
  929. }
  930. ClearMultiSelectedRegions (true);
  931. // 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
  932. MultiSelectedRegions.Push (
  933. new TableSelection (
  934. new Point (SelectedColumn, SelectedRow),
  935. new Rect (0, 0, Table.Columns, table.Rows)
  936. )
  937. );
  938. Update ();
  939. }
  940. /// <summary>This event is raised when the selected cell in the table changes.</summary>
  941. public event EventHandler<SelectedCellChangedEventArgs> SelectedCellChanged;
  942. /// <summary>
  943. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in
  944. /// <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  945. /// </summary>
  946. /// <param name="col"></param>
  947. /// <param name="row"></param>
  948. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  949. public void SetSelection (int col, int row, bool extendExistingSelection)
  950. {
  951. // if we are trying to increase the column index then
  952. // we are moving right otherwise we are moving left
  953. bool lookRight = col > selectedColumn;
  954. col = GetNearestVisibleColumn (col, lookRight, true);
  955. if (!MultiSelect || !extendExistingSelection)
  956. {
  957. ClearMultiSelectedRegions (true);
  958. }
  959. if (extendExistingSelection)
  960. {
  961. // If we are extending current selection but there isn't one
  962. if (MultiSelectedRegions.Count == 0 || MultiSelectedRegions.All (m => m.IsToggled))
  963. {
  964. // Create a new region between the old active cell and the new cell
  965. TableSelection rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  966. MultiSelectedRegions.Push (rect);
  967. }
  968. else
  969. {
  970. // Extend the current head selection to include the new cell
  971. TableSelection head = MultiSelectedRegions.Pop ();
  972. TableSelection newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  973. MultiSelectedRegions.Push (newRect);
  974. }
  975. }
  976. SelectedColumn = col;
  977. SelectedRow = row;
  978. }
  979. /// <summary>
  980. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> /
  981. /// <see cref="RowOffset"/>) etc
  982. /// </summary>
  983. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  984. public void Update ()
  985. {
  986. if (!IsInitialized || TableIsNullOrInvisible ())
  987. {
  988. SetNeedsDisplay ();
  989. return;
  990. }
  991. EnsureValidScrollOffsets ();
  992. EnsureValidSelection ();
  993. EnsureSelectedCellIsVisible ();
  994. SetNeedsDisplay ();
  995. }
  996. /// <summary>Invokes the <see cref="CellActivated"/> event</summary>
  997. /// <param name="args"></param>
  998. protected virtual void OnCellActivated (CellActivatedEventArgs args) { CellActivated?.Invoke (this, args); }
  999. /// <summary>Invokes the <see cref="CellToggled"/> event</summary>
  1000. /// <param name="args"></param>
  1001. protected virtual void OnCellToggled (CellToggledEventArgs args) { CellToggled?.Invoke (this, args); }
  1002. /// <summary>Invokes the <see cref="SelectedCellChanged"/> event</summary>
  1003. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args) { SelectedCellChanged?.Invoke (this, args); }
  1004. /// <summary>
  1005. /// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to with
  1006. /// <see cref="ConsoleDriver.AddStr(string)"/>. The driver will already be in the correct place when rendering and you
  1007. /// must render the full <paramref name="render"/> or the view will not look right. For simpler provision of color use
  1008. /// <see cref="ColumnStyle.ColorGetter"/> For changing the content that is rendered use
  1009. /// <see cref="ColumnStyle.RepresentationGetter"/>
  1010. /// </summary>
  1011. /// <param name="cellColor"></param>
  1012. /// <param name="render"></param>
  1013. /// <param name="isPrimaryCell"></param>
  1014. protected virtual void RenderCell (Attribute cellColor, string render, bool isPrimaryCell)
  1015. {
  1016. // If the cell is the selected col/row then draw the first rune in inverted colors
  1017. // this allows the user to track which cell is the active one during a multi cell
  1018. // selection or in full row select mode
  1019. if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell)
  1020. {
  1021. if (render.Length > 0)
  1022. {
  1023. // invert the color of the current cell for the first character
  1024. Driver.SetAttribute (new Attribute (cellColor.Background, cellColor.Foreground));
  1025. Driver.AddRune ((Rune)render [0]);
  1026. if (render.Length > 1)
  1027. {
  1028. Driver.SetAttribute (cellColor);
  1029. Driver.AddStr (render.Substring (1));
  1030. }
  1031. }
  1032. }
  1033. else
  1034. {
  1035. Driver.SetAttribute (cellColor);
  1036. Driver.AddStr (render);
  1037. }
  1038. }
  1039. /// <summary>Returns the amount of vertical space required to display the header</summary>
  1040. /// <returns></returns>
  1041. internal int GetHeaderHeight ()
  1042. {
  1043. int heightRequired = Style.ShowHeaders ? 1 : 0;
  1044. if (Style.ShowHorizontalHeaderOverline)
  1045. {
  1046. heightRequired++;
  1047. }
  1048. if (Style.ShowHorizontalHeaderUnderline)
  1049. {
  1050. heightRequired++;
  1051. }
  1052. return heightRequired;
  1053. }
  1054. /// <summary>Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.</summary>
  1055. /// <returns></returns>
  1056. internal int GetHeaderHeightIfAny () { return ShouldRenderHeaders () ? GetHeaderHeight () : 0; }
  1057. private void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
  1058. {
  1059. Move (col, row);
  1060. d.AddRune (ch);
  1061. }
  1062. /// <summary>
  1063. /// Returns the maximum of the <paramref name="col"/> name and the maximum length of data that will be rendered
  1064. /// starting at <see cref="RowOffset"/> and rendering <paramref name="rowsToRender"/>
  1065. /// </summary>
  1066. /// <param name="col"></param>
  1067. /// <param name="rowsToRender"></param>
  1068. /// <param name="colStyle"></param>
  1069. /// <returns></returns>
  1070. private int CalculateMaxCellWidth (int col, int rowsToRender, ColumnStyle colStyle)
  1071. {
  1072. int spaceRequired = table.ColumnNames [col].EnumerateRunes ().Sum (c => c.GetColumns ());
  1073. // if table has no rows
  1074. if (RowOffset < 0)
  1075. {
  1076. return spaceRequired;
  1077. }
  1078. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows; i++)
  1079. {
  1080. //expand required space if cell is bigger than the last biggest cell or header
  1081. spaceRequired = Math.Max (
  1082. spaceRequired,
  1083. GetRepresentation (Table [i, col], colStyle)
  1084. .EnumerateRunes ()
  1085. .Sum (c => c.GetColumns ())
  1086. );
  1087. }
  1088. // Don't require more space than the style allows
  1089. if (colStyle != null)
  1090. {
  1091. // enforce maximum cell width based on style
  1092. if (spaceRequired > colStyle.MaxWidth)
  1093. {
  1094. spaceRequired = colStyle.MaxWidth;
  1095. }
  1096. // enforce minimum cell width based on style
  1097. if (spaceRequired < colStyle.MinWidth)
  1098. {
  1099. spaceRequired = colStyle.MinWidth;
  1100. }
  1101. }
  1102. // enforce maximum cell width based on global table style
  1103. if (spaceRequired > MaxCellWidth)
  1104. {
  1105. spaceRequired = MaxCellWidth;
  1106. }
  1107. return spaceRequired;
  1108. }
  1109. /// <summary>
  1110. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the
  1111. /// <see cref="ColumnOffset"/>
  1112. /// </summary>
  1113. /// <param name="bounds"></param>
  1114. /// <param name="padding"></param>
  1115. /// <returns></returns>
  1116. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  1117. {
  1118. if (TableIsNullOrInvisible ())
  1119. {
  1120. return Enumerable.Empty<ColumnToRender> ();
  1121. }
  1122. List<ColumnToRender> toReturn = new ();
  1123. var usedSpace = 0;
  1124. //if horizontal space is required at the start of the line (before the first header)
  1125. if (Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  1126. {
  1127. usedSpace += 1;
  1128. }
  1129. int availableHorizontalSpace = bounds.Width;
  1130. int rowsToRender = bounds.Height;
  1131. // reserved for the headers row
  1132. if (ShouldRenderHeaders ())
  1133. {
  1134. rowsToRender -= GetHeaderHeight ();
  1135. }
  1136. var first = true;
  1137. int lastColumn = Table.Columns - 1;
  1138. // TODO : Maybe just a for loop?
  1139. foreach (int col in Enumerable.Range (0, Table.Columns).Skip (ColumnOffset))
  1140. {
  1141. int startingIdxForCurrentHeader = usedSpace;
  1142. ColumnStyle colStyle = Style.GetColumnStyleIfAny (col);
  1143. int colWidth;
  1144. // if column is not being rendered
  1145. if (colStyle?.Visible == false)
  1146. {
  1147. // do not add it to the returned columns
  1148. continue;
  1149. }
  1150. // is there enough space for this column (and it's data)?
  1151. colWidth = CalculateMaxCellWidth (col, rowsToRender, colStyle) + padding;
  1152. if (MinCellWidth > 0 && colWidth < MinCellWidth + padding)
  1153. {
  1154. if (MinCellWidth > MaxCellWidth)
  1155. {
  1156. colWidth = MaxCellWidth + padding;
  1157. }
  1158. else
  1159. {
  1160. colWidth = MinCellWidth + padding;
  1161. }
  1162. }
  1163. // there is not enough space for this columns
  1164. // visible content
  1165. if (usedSpace + colWidth > availableHorizontalSpace)
  1166. {
  1167. var showColumn = false;
  1168. // if this column accepts flexible width rendering and
  1169. // is therefore happy rendering into less space
  1170. if (colStyle != null
  1171. && colStyle.MinAcceptableWidth > 0
  1172. &&
  1173. // is there enough space to meet the MinAcceptableWidth
  1174. availableHorizontalSpace - usedSpace >= colStyle.MinAcceptableWidth)
  1175. {
  1176. // show column and use use whatever space is
  1177. // left for rendering it
  1178. showColumn = true;
  1179. colWidth = availableHorizontalSpace - usedSpace;
  1180. }
  1181. // If its the only column we are able to render then
  1182. // accept it anyway (that must be one massively wide column!)
  1183. if (first)
  1184. {
  1185. showColumn = true;
  1186. }
  1187. // no special exceptions and we are out of space
  1188. // so stop accepting new columns for the render area
  1189. if (!showColumn)
  1190. {
  1191. break;
  1192. }
  1193. }
  1194. usedSpace += colWidth;
  1195. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  1196. colWidth = Math.Min (availableHorizontalSpace, colWidth);
  1197. bool isVeryLast = lastColumn == col;
  1198. // there is space
  1199. toReturn.Add (new ColumnToRender (col, startingIdxForCurrentHeader, colWidth, isVeryLast));
  1200. first = false;
  1201. }
  1202. if (Style.ExpandLastColumn)
  1203. {
  1204. ColumnToRender last = toReturn.Last ();
  1205. last.Width = Math.Max (last.Width, availableHorizontalSpace - last.X);
  1206. }
  1207. return toReturn;
  1208. }
  1209. /// <summary>Clears a line of the console by filling it with spaces</summary>
  1210. /// <param name="row"></param>
  1211. /// <param name="width"></param>
  1212. private void ClearLine (int row, int width)
  1213. {
  1214. Move (0, row);
  1215. Driver.SetAttribute (GetNormalColor ());
  1216. Driver.AddStr (new string (' ', width));
  1217. }
  1218. private void ClearMultiSelectedRegions (bool keepToggledSelections)
  1219. {
  1220. if (!keepToggledSelections)
  1221. {
  1222. MultiSelectedRegions.Clear ();
  1223. return;
  1224. }
  1225. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1226. MultiSelectedRegions.Clear ();
  1227. foreach (TableSelection region in oldRegions)
  1228. {
  1229. if (region.IsToggled)
  1230. {
  1231. MultiSelectedRegions.Push (region);
  1232. }
  1233. }
  1234. }
  1235. /// <summary>
  1236. /// Returns a new rectangle between the two points with positive width/height regardless of relative positioning
  1237. /// of the points. pt1 is always considered the <see cref="TableSelection.Origin"/> point
  1238. /// </summary>
  1239. /// <param name="pt1X">Origin point for the selection in X</param>
  1240. /// <param name="pt1Y">Origin point for the selection in Y</param>
  1241. /// <param name="pt2X">End point for the selection in X</param>
  1242. /// <param name="pt2Y">End point for the selection in Y</param>
  1243. /// <param name="toggle">True if selection is result of <see cref="Command.ToggleChecked"/></param>
  1244. /// <returns></returns>
  1245. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y, bool toggle = false)
  1246. {
  1247. int top = Math.Max (Math.Min (pt1Y, pt2Y), 0);
  1248. int bot = Math.Max (Math.Max (pt1Y, pt2Y), 0);
  1249. int left = Math.Max (Math.Min (pt1X, pt2X), 0);
  1250. int right = Math.Max (Math.Max (pt1X, pt2X), 0);
  1251. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  1252. return new TableSelection (new Point (pt1X, pt1Y), new Rect (left, top, right - left + 1, bot - top + 1))
  1253. {
  1254. IsToggled = toggle
  1255. };
  1256. }
  1257. /// <summary>Returns a single point as a <see cref="TableSelection"/></summary>
  1258. /// <param name="x"></param>
  1259. /// <param name="y"></param>
  1260. /// <returns></returns>
  1261. private TableSelection CreateTableSelection (int x, int y) { return CreateTableSelection (x, y, x, y); }
  1262. private bool CycleToNextTableEntryBeginningWith (Key keyEvent)
  1263. {
  1264. int row = SelectedRow;
  1265. // There is a multi select going on and not just for the current row
  1266. if (GetAllSelectedCells ().Any (c => c.Y != row))
  1267. {
  1268. return false;
  1269. }
  1270. int match = CollectionNavigator.GetNextMatchingItem (row, (char)keyEvent);
  1271. if (match != -1)
  1272. {
  1273. SelectedRow = match;
  1274. EnsureValidSelection ();
  1275. EnsureSelectedCellIsVisible ();
  1276. PositionCursor ();
  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.Rect.Bottom > row && r.Rect.Top <= row);
  1291. }
  1292. return MultiSelectedRegions.Where (r => r.Rect.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 != null ? 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, Bounds.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 (Bounds.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 (' ', Bounds.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 != null)
  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 (Bounds.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 (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(Rect, 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. }