TableView.cs 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277
  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.</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. 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.Position.X;
  706. int boundsY = me.Position.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="client">offset from the top left of the control.</param>
  877. /// <returns>The position.</returns>
  878. public Point? ScreenToCell (Point client) { return ScreenToCell (client, out _, 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. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny) { return ScreenToCell (clientX, clientY, out headerIfAny, out _); }
  888. /// <summary>
  889. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  890. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  891. /// bounds.
  892. /// </summary>
  893. /// <param name="client">offset from the top left of the control.</param>
  894. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  895. public Point? ScreenToCell (Point client, out int? headerIfAny) { return ScreenToCell (client, out headerIfAny, out _); }
  896. /// <summary>
  897. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  898. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  899. /// bounds.
  900. /// </summary>
  901. /// <param name="clientX">X offset from the top left of the control.</param>
  902. /// <param name="clientY">Y offset from the top left of the control.</param>
  903. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  904. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  905. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny, out int? offsetX)
  906. {
  907. headerIfAny = null;
  908. offsetX = null;
  909. if (TableIsNullOrInvisible ())
  910. {
  911. return null;
  912. }
  913. IEnumerable<ColumnToRender> viewPort = CalculateViewport (Viewport);
  914. int headerHeight = GetHeaderHeightIfAny ();
  915. ColumnToRender col = viewPort.LastOrDefault (c => c.X <= clientX);
  916. // Click is on the header section of rendered UI
  917. if (clientY < headerHeight)
  918. {
  919. headerIfAny = col?.Column;
  920. offsetX = col is { } ? clientX - col.X : null;
  921. return null;
  922. }
  923. int rowIdx = RowOffset - headerHeight + clientY;
  924. // if click is off bottom of the rows don't give an
  925. // invalid index back to user!
  926. if (rowIdx >= Table.Rows)
  927. {
  928. return null;
  929. }
  930. if (col is { } && rowIdx >= 0)
  931. {
  932. offsetX = clientX - col.X;
  933. return new Point (col.Column, rowIdx);
  934. }
  935. return null;
  936. }
  937. /// <summary>
  938. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative
  939. /// to the control client area). Returns null if the point is in the header, no table is loaded or outside the control
  940. /// bounds.
  941. /// </summary>
  942. /// <param name="client">offset from the top left of the control.</param>
  943. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  944. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  945. public Point? ScreenToCell (Point client, out int? headerIfAny, out int? offsetX)
  946. {
  947. return ScreenToCell (client.X, client.Y, out headerIfAny, out offsetX);
  948. }
  949. /// <summary>
  950. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old
  951. /// selection regions)
  952. /// </summary>
  953. public void SelectAll ()
  954. {
  955. if (TableIsNullOrInvisible () || !MultiSelect || Table.Rows == 0)
  956. {
  957. return;
  958. }
  959. ClearMultiSelectedRegions (true);
  960. // 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
  961. MultiSelectedRegions.Push (
  962. new TableSelection (
  963. new (SelectedColumn, SelectedRow),
  964. new (0, 0, Table.Columns, table.Rows)
  965. )
  966. );
  967. Update ();
  968. }
  969. /// <summary>This event is raised when the selected cell in the table changes.</summary>
  970. public event EventHandler<SelectedCellChangedEventArgs> SelectedCellChanged;
  971. /// <summary>
  972. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in
  973. /// <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  974. /// </summary>
  975. /// <param name="col"></param>
  976. /// <param name="row"></param>
  977. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  978. public void SetSelection (int col, int row, bool extendExistingSelection)
  979. {
  980. // if we are trying to increase the column index then
  981. // we are moving right otherwise we are moving left
  982. bool lookRight = col > selectedColumn;
  983. col = GetNearestVisibleColumn (col, lookRight, true);
  984. if (!MultiSelect || !extendExistingSelection)
  985. {
  986. ClearMultiSelectedRegions (true);
  987. }
  988. if (extendExistingSelection)
  989. {
  990. // If we are extending current selection but there isn't one
  991. if (MultiSelectedRegions.Count == 0 || MultiSelectedRegions.All (m => m.IsToggled))
  992. {
  993. // Create a new region between the old active cell and the new cell
  994. TableSelection rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  995. MultiSelectedRegions.Push (rect);
  996. }
  997. else
  998. {
  999. // Extend the current head selection to include the new cell
  1000. TableSelection head = MultiSelectedRegions.Pop ();
  1001. TableSelection newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  1002. MultiSelectedRegions.Push (newRect);
  1003. }
  1004. }
  1005. SelectedColumn = col;
  1006. SelectedRow = row;
  1007. }
  1008. /// <summary>
  1009. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> /
  1010. /// <see cref="RowOffset"/>) etc
  1011. /// </summary>
  1012. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  1013. public void Update ()
  1014. {
  1015. if (!IsInitialized || TableIsNullOrInvisible ())
  1016. {
  1017. SetNeedsDisplay ();
  1018. return;
  1019. }
  1020. EnsureValidScrollOffsets ();
  1021. EnsureValidSelection ();
  1022. EnsureSelectedCellIsVisible ();
  1023. SetNeedsDisplay ();
  1024. }
  1025. /// <summary>Invokes the <see cref="CellActivated"/> event</summary>
  1026. /// <param name="args"></param>
  1027. protected virtual void OnCellActivated (CellActivatedEventArgs args) { CellActivated?.Invoke (this, args); }
  1028. /// <summary>Invokes the <see cref="CellToggled"/> event</summary>
  1029. /// <param name="args"></param>
  1030. protected virtual void OnCellToggled (CellToggledEventArgs args) { CellToggled?.Invoke (this, args); }
  1031. /// <summary>Invokes the <see cref="SelectedCellChanged"/> event</summary>
  1032. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args) { SelectedCellChanged?.Invoke (this, args); }
  1033. /// <summary>
  1034. /// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to with
  1035. /// <see cref="ConsoleDriver.AddStr(string)"/>. The driver will already be in the correct place when rendering and you
  1036. /// must render the full <paramref name="render"/> or the view will not look right. For simpler provision of color use
  1037. /// <see cref="ColumnStyle.ColorGetter"/> For changing the content that is rendered use
  1038. /// <see cref="ColumnStyle.RepresentationGetter"/>
  1039. /// </summary>
  1040. /// <param name="cellColor"></param>
  1041. /// <param name="render"></param>
  1042. /// <param name="isPrimaryCell"></param>
  1043. protected virtual void RenderCell (Attribute cellColor, string render, bool isPrimaryCell)
  1044. {
  1045. // If the cell is the selected col/row then draw the first rune in inverted colors
  1046. // this allows the user to track which cell is the active one during a multi cell
  1047. // selection or in full row select mode
  1048. if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell)
  1049. {
  1050. if (render.Length > 0)
  1051. {
  1052. // invert the color of the current cell for the first character
  1053. Driver.SetAttribute (new Attribute (cellColor.Background, cellColor.Foreground));
  1054. Driver.AddRune ((Rune)render [0]);
  1055. if (render.Length > 1)
  1056. {
  1057. Driver.SetAttribute (cellColor);
  1058. Driver.AddStr (render.Substring (1));
  1059. }
  1060. }
  1061. }
  1062. else
  1063. {
  1064. Driver.SetAttribute (cellColor);
  1065. Driver.AddStr (render);
  1066. }
  1067. }
  1068. /// <summary>Returns the amount of vertical space required to display the header</summary>
  1069. /// <returns></returns>
  1070. internal int GetHeaderHeight ()
  1071. {
  1072. int heightRequired = Style.ShowHeaders ? 1 : 0;
  1073. if (Style.ShowHorizontalHeaderOverline)
  1074. {
  1075. heightRequired++;
  1076. }
  1077. if (Style.ShowHorizontalHeaderUnderline)
  1078. {
  1079. heightRequired++;
  1080. }
  1081. return heightRequired;
  1082. }
  1083. /// <summary>Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.</summary>
  1084. /// <returns></returns>
  1085. internal int GetHeaderHeightIfAny () { return ShouldRenderHeaders () ? GetHeaderHeight () : 0; }
  1086. private void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
  1087. {
  1088. Move (col, row);
  1089. d.AddRune (ch);
  1090. }
  1091. /// <summary>
  1092. /// Returns the maximum of the <paramref name="col"/> name and the maximum length of data that will be rendered
  1093. /// starting at <see cref="RowOffset"/> and rendering <paramref name="rowsToRender"/>
  1094. /// </summary>
  1095. /// <param name="col"></param>
  1096. /// <param name="rowsToRender"></param>
  1097. /// <param name="colStyle"></param>
  1098. /// <returns></returns>
  1099. private int CalculateMaxCellWidth (int col, int rowsToRender, ColumnStyle colStyle)
  1100. {
  1101. int spaceRequired = table.ColumnNames [col].EnumerateRunes ().Sum (c => c.GetColumns ());
  1102. // if table has no rows
  1103. if (RowOffset < 0)
  1104. {
  1105. return spaceRequired;
  1106. }
  1107. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows; i++)
  1108. {
  1109. //expand required space if cell is bigger than the last biggest cell or header
  1110. spaceRequired = Math.Max (
  1111. spaceRequired,
  1112. GetRepresentation (Table [i, col], colStyle)
  1113. .EnumerateRunes ()
  1114. .Sum (c => c.GetColumns ())
  1115. );
  1116. }
  1117. // Don't require more space than the style allows
  1118. if (colStyle is { })
  1119. {
  1120. // enforce maximum cell width based on style
  1121. if (spaceRequired > colStyle.MaxWidth)
  1122. {
  1123. spaceRequired = colStyle.MaxWidth;
  1124. }
  1125. // enforce minimum cell width based on style
  1126. if (spaceRequired < colStyle.MinWidth)
  1127. {
  1128. spaceRequired = colStyle.MinWidth;
  1129. }
  1130. }
  1131. // enforce maximum cell width based on global table style
  1132. if (spaceRequired > MaxCellWidth)
  1133. {
  1134. spaceRequired = MaxCellWidth;
  1135. }
  1136. return spaceRequired;
  1137. }
  1138. /// <summary>
  1139. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the
  1140. /// <see cref="ColumnOffset"/>
  1141. /// </summary>
  1142. /// <param name="bounds"></param>
  1143. /// <param name="padding"></param>
  1144. /// <returns></returns>
  1145. private IEnumerable<ColumnToRender> CalculateViewport (Rectangle bounds, int padding = 1)
  1146. {
  1147. if (TableIsNullOrInvisible ())
  1148. {
  1149. return Enumerable.Empty<ColumnToRender> ();
  1150. }
  1151. List<ColumnToRender> toReturn = new ();
  1152. var usedSpace = 0;
  1153. //if horizontal space is required at the start of the line (before the first header)
  1154. if (Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  1155. {
  1156. usedSpace += 1;
  1157. }
  1158. int availableHorizontalSpace = bounds.Width;
  1159. int rowsToRender = bounds.Height;
  1160. // reserved for the headers row
  1161. if (ShouldRenderHeaders ())
  1162. {
  1163. rowsToRender -= GetHeaderHeight ();
  1164. }
  1165. var first = true;
  1166. int lastColumn = Table.Columns - 1;
  1167. // TODO : Maybe just a for loop?
  1168. foreach (int col in Enumerable.Range (0, Table.Columns).Skip (ColumnOffset))
  1169. {
  1170. int startingIdxForCurrentHeader = usedSpace;
  1171. ColumnStyle colStyle = Style.GetColumnStyleIfAny (col);
  1172. int colWidth;
  1173. // if column is not being rendered
  1174. if (colStyle?.Visible == false)
  1175. {
  1176. // do not add it to the returned columns
  1177. continue;
  1178. }
  1179. // is there enough space for this column (and it's data)?
  1180. colWidth = CalculateMaxCellWidth (col, rowsToRender, colStyle) + padding;
  1181. if (MinCellWidth > 0 && colWidth < MinCellWidth + padding)
  1182. {
  1183. if (MinCellWidth > MaxCellWidth)
  1184. {
  1185. colWidth = MaxCellWidth + padding;
  1186. }
  1187. else
  1188. {
  1189. colWidth = MinCellWidth + padding;
  1190. }
  1191. }
  1192. // there is not enough space for this columns
  1193. // visible content
  1194. if (usedSpace + colWidth > availableHorizontalSpace)
  1195. {
  1196. var showColumn = false;
  1197. // if this column accepts flexible width rendering and
  1198. // is therefore happy rendering into less space
  1199. if (colStyle != null
  1200. && colStyle.MinAcceptableWidth > 0
  1201. &&
  1202. // is there enough space to meet the MinAcceptableWidth
  1203. availableHorizontalSpace - usedSpace >= colStyle.MinAcceptableWidth)
  1204. {
  1205. // show column and use whatever space is
  1206. // left for rendering it
  1207. showColumn = true;
  1208. colWidth = availableHorizontalSpace - usedSpace;
  1209. }
  1210. // If it's the only column we are able to render then
  1211. // accept it anyway (that must be one massively wide column!)
  1212. if (first)
  1213. {
  1214. showColumn = true;
  1215. }
  1216. // no special exceptions and we are out of space
  1217. // so stop accepting new columns for the render area
  1218. if (!showColumn)
  1219. {
  1220. break;
  1221. }
  1222. }
  1223. usedSpace += colWidth;
  1224. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  1225. colWidth = Math.Min (availableHorizontalSpace, colWidth);
  1226. bool isVeryLast = lastColumn == col;
  1227. // there is space
  1228. toReturn.Add (new ColumnToRender (col, startingIdxForCurrentHeader, colWidth, isVeryLast));
  1229. first = false;
  1230. }
  1231. if (Style.ExpandLastColumn)
  1232. {
  1233. ColumnToRender last = toReturn.Last ();
  1234. last.Width = Math.Max (last.Width, availableHorizontalSpace - last.X);
  1235. }
  1236. return toReturn;
  1237. }
  1238. /// <summary>Clears a line of the console by filling it with spaces</summary>
  1239. /// <param name="row"></param>
  1240. /// <param name="width"></param>
  1241. private void ClearLine (int row, int width)
  1242. {
  1243. Move (0, row);
  1244. Driver.SetAttribute (GetNormalColor ());
  1245. Driver.AddStr (new string (' ', width));
  1246. }
  1247. private void ClearMultiSelectedRegions (bool keepToggledSelections)
  1248. {
  1249. if (!keepToggledSelections)
  1250. {
  1251. MultiSelectedRegions.Clear ();
  1252. return;
  1253. }
  1254. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1255. MultiSelectedRegions.Clear ();
  1256. foreach (TableSelection region in oldRegions)
  1257. {
  1258. if (region.IsToggled)
  1259. {
  1260. MultiSelectedRegions.Push (region);
  1261. }
  1262. }
  1263. }
  1264. /// <summary>
  1265. /// Returns a new rectangle between the two points with positive width/height regardless of relative positioning
  1266. /// of the points. pt1 is always considered the <see cref="TableSelection.Origin"/> point
  1267. /// </summary>
  1268. /// <param name="pt1X">Origin point for the selection in X</param>
  1269. /// <param name="pt1Y">Origin point for the selection in Y</param>
  1270. /// <param name="pt2X">End point for the selection in X</param>
  1271. /// <param name="pt2Y">End point for the selection in Y</param>
  1272. /// <param name="toggle">True if selection is result of <see cref="Command.Select"/></param>
  1273. /// <returns></returns>
  1274. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y, bool toggle = false)
  1275. {
  1276. int top = Math.Max (Math.Min (pt1Y, pt2Y), 0);
  1277. int bot = Math.Max (Math.Max (pt1Y, pt2Y), 0);
  1278. int left = Math.Max (Math.Min (pt1X, pt2X), 0);
  1279. int right = Math.Max (Math.Max (pt1X, pt2X), 0);
  1280. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  1281. return new TableSelection (new (pt1X, pt1Y), new (left, top, right - left + 1, bot - top + 1))
  1282. {
  1283. IsToggled = toggle
  1284. };
  1285. }
  1286. /// <summary>Returns a single point as a <see cref="TableSelection"/></summary>
  1287. /// <param name="x"></param>
  1288. /// <param name="y"></param>
  1289. /// <returns></returns>
  1290. private TableSelection CreateTableSelection (int x, int y) { return CreateTableSelection (x, y, x, y); }
  1291. private bool CycleToNextTableEntryBeginningWith (Key keyEvent)
  1292. {
  1293. int row = SelectedRow;
  1294. // There is a multi select going on and not just for the current row
  1295. if (GetAllSelectedCells ().Any (c => c.Y != row))
  1296. {
  1297. return false;
  1298. }
  1299. int match = CollectionNavigator.GetNextMatchingItem (row, (char)keyEvent);
  1300. if (match != -1)
  1301. {
  1302. SelectedRow = match;
  1303. EnsureValidSelection ();
  1304. EnsureSelectedCellIsVisible ();
  1305. SetNeedsDisplay ();
  1306. return true;
  1307. }
  1308. return false;
  1309. }
  1310. private IEnumerable<TableSelection> GetMultiSelectedRegionsContaining (int col, int row)
  1311. {
  1312. if (!MultiSelect)
  1313. {
  1314. return Enumerable.Empty<TableSelection> ();
  1315. }
  1316. if (FullRowSelect)
  1317. {
  1318. return MultiSelectedRegions.Where (r => r.Rectangle.Bottom > row && r.Rectangle.Top <= row);
  1319. }
  1320. return MultiSelectedRegions.Where (r => r.Rectangle.Contains (col, row));
  1321. }
  1322. /// <summary>
  1323. /// Returns <paramref name="columnIndex"/> unless the <see cref="ColumnStyle.Visible"/> is false for the indexed
  1324. /// column. If so then the index returned is nudged to the nearest visible column.
  1325. /// </summary>
  1326. /// <remarks>Returns <paramref name="columnIndex"/> unchanged if it is invalid (e.g. out of bounds).</remarks>
  1327. /// <param name="columnIndex">The input column index.</param>
  1328. /// <param name="lookRight">
  1329. /// When nudging invisible selections look right first. <see langword="true"/> to look right,
  1330. /// <see langword="false"/> to look left.
  1331. /// </param>
  1332. /// <param name="allowBumpingInOppositeDirection">
  1333. /// If we cannot find anything visible when looking in direction of
  1334. /// <paramref name="lookRight"/> then should we look in the opposite direction instead? Use true if you want to push a
  1335. /// selection to a valid index no matter what. Use false if you are primarily interested in learning about directional
  1336. /// column visibility.
  1337. /// </param>
  1338. private int GetNearestVisibleColumn (int columnIndex, bool lookRight, bool allowBumpingInOppositeDirection)
  1339. {
  1340. if (TryGetNearestVisibleColumn (columnIndex, lookRight, allowBumpingInOppositeDirection, out int answer))
  1341. {
  1342. return answer;
  1343. }
  1344. return columnIndex;
  1345. }
  1346. /// <summary>
  1347. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read
  1348. /// from <see cref="Table"/>
  1349. /// </summary>
  1350. /// <param name="value"></param>
  1351. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  1352. /// <returns></returns>
  1353. private string GetRepresentation (object value, ColumnStyle colStyle)
  1354. {
  1355. if (value is null || value == DBNull.Value)
  1356. {
  1357. return NullSymbol;
  1358. }
  1359. return colStyle is { } ? colStyle.GetRepresentation (value) : value.ToString ();
  1360. }
  1361. private bool HasControlOrAlt (MouseEvent me) { return me.Flags.HasFlag (MouseFlags.ButtonAlt) || me.Flags.HasFlag (MouseFlags.ButtonCtrl); }
  1362. /// <summary>
  1363. /// Returns true if the given <paramref name="columnIndex"/> indexes a visible column otherwise false. Returns
  1364. /// false for indexes that are out of bounds.
  1365. /// </summary>
  1366. /// <param name="columnIndex"></param>
  1367. /// <returns></returns>
  1368. private bool IsColumnVisible (int columnIndex)
  1369. {
  1370. // if the column index provided is out of bounds
  1371. if (columnIndex < 0 || columnIndex >= table.Columns)
  1372. {
  1373. return false;
  1374. }
  1375. return Style.GetColumnStyleIfAny (columnIndex)?.Visible ?? true;
  1376. }
  1377. private void RenderBottomLine (int row, int availableWidth, ColumnToRender [] columnsToRender)
  1378. {
  1379. // Renders a line at the bottom of the table after all the data like:
  1380. // └─────────────────────────────────┴──────────┴──────┴──────────┴────────┴────────────────────────────────────────────┘
  1381. for (var c = 0; c < availableWidth; c++)
  1382. {
  1383. // Start by assuming we just draw a straight line the
  1384. // whole way but update to instead draw BottomTee / Corner etc
  1385. Rune rune = Glyphs.HLine;
  1386. if (Style.ShowVerticalCellLines)
  1387. {
  1388. if (c == 0)
  1389. {
  1390. // for first character render line
  1391. rune = Glyphs.LLCorner;
  1392. }
  1393. else if (columnsToRender.Any (r => r.X == c + 1))
  1394. {
  1395. // if the next column is the start of a header
  1396. rune = Glyphs.BottomTee;
  1397. }
  1398. else if (c == availableWidth - 1)
  1399. {
  1400. // for the last character in the table
  1401. rune = Glyphs.LRCorner;
  1402. }
  1403. else if (Style.ExpandLastColumn == false && columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c))
  1404. {
  1405. // if the next console column is the last column's end
  1406. rune = Glyphs.BottomTee;
  1407. }
  1408. }
  1409. AddRuneAt (Driver, c, row, rune);
  1410. }
  1411. }
  1412. private void RenderHeaderMidline (int row, ColumnToRender [] columnsToRender)
  1413. {
  1414. // Renders something like:
  1415. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  1416. ClearLine (row, Viewport.Width);
  1417. //render start of line
  1418. if (style.ShowVerticalHeaderLines)
  1419. {
  1420. AddRune (0, row, Glyphs.VLine);
  1421. }
  1422. for (var i = 0; i < columnsToRender.Length; i++)
  1423. {
  1424. ColumnToRender current = columnsToRender [i];
  1425. ColumnStyle colStyle = Style.GetColumnStyleIfAny (current.Column);
  1426. string colName = table.ColumnNames [current.Column];
  1427. RenderSeparator (current.X - 1, row, true);
  1428. Move (current.X, row);
  1429. Driver.AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
  1430. if (Style.ExpandLastColumn == false && current.IsVeryLast)
  1431. {
  1432. RenderSeparator (current.X + current.Width - 1, row, true);
  1433. }
  1434. }
  1435. //render end of line
  1436. if (style.ShowVerticalHeaderLines)
  1437. {
  1438. AddRune (Viewport.Width - 1, row, Glyphs.VLine);
  1439. }
  1440. }
  1441. private void RenderHeaderOverline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  1442. {
  1443. // Renders a line above table headers (when visible) like:
  1444. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  1445. for (var c = 0; c < availableWidth; c++)
  1446. {
  1447. Rune rune = Glyphs.HLine;
  1448. if (Style.ShowVerticalHeaderLines)
  1449. {
  1450. if (c == 0)
  1451. {
  1452. rune = Glyphs.ULCorner;
  1453. }
  1454. // if the next column is the start of a header
  1455. else if (columnsToRender.Any (r => r.X == c + 1))
  1456. {
  1457. rune = Glyphs.TopTee;
  1458. }
  1459. else if (c == availableWidth - 1)
  1460. {
  1461. rune = Glyphs.URCorner;
  1462. }
  1463. // if the next console column is the last column's end
  1464. else if (Style.ExpandLastColumn == false && columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c))
  1465. {
  1466. rune = Glyphs.TopTee;
  1467. }
  1468. }
  1469. AddRuneAt (Driver, c, row, rune);
  1470. }
  1471. }
  1472. private void RenderHeaderUnderline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  1473. {
  1474. /*
  1475. * First lets work out if we should be rendering scroll indicators
  1476. */
  1477. // are there are visible columns to the left that have been pushed
  1478. // off the screen due to horizontal scrolling?
  1479. bool moreColumnsToLeft = ColumnOffset > 0;
  1480. // if we moved left would we find a new column (or are they all invisible?)
  1481. if (!TryGetNearestVisibleColumn (ColumnOffset - 1, false, false, out _))
  1482. {
  1483. moreColumnsToLeft = false;
  1484. }
  1485. // are there visible columns to the right that have not yet been reached?
  1486. // lets find out, what is the column index of the last column we are rendering
  1487. int lastColumnIdxRendered = ColumnOffset + columnsToRender.Length - 1;
  1488. // are there more valid indexes?
  1489. bool moreColumnsToRight = lastColumnIdxRendered < Table.Columns;
  1490. // if we went right from the last column would we find a new visible column?
  1491. if (!TryGetNearestVisibleColumn (lastColumnIdxRendered + 1, true, false, out _))
  1492. {
  1493. // no we would not
  1494. moreColumnsToRight = false;
  1495. }
  1496. /*
  1497. * Now lets draw the line itself
  1498. */
  1499. // Renders a line below the table headers (when visible) like:
  1500. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  1501. for (var c = 0; c < availableWidth; c++)
  1502. {
  1503. // Start by assuming we just draw a straight line the
  1504. // whole way but update to instead draw a header indicator
  1505. // or scroll arrow etc
  1506. Rune rune = Glyphs.HLine;
  1507. if (Style.ShowVerticalHeaderLines)
  1508. {
  1509. if (c == 0)
  1510. {
  1511. // for first character render line
  1512. rune = Style.ShowVerticalCellLines ? Glyphs.LeftTee : Glyphs.LLCorner;
  1513. // unless we have horizontally scrolled along
  1514. // in which case render an arrow, to indicate user
  1515. // can scroll left
  1516. if (Style.ShowHorizontalScrollIndicators && moreColumnsToLeft)
  1517. {
  1518. rune = Glyphs.LeftArrow;
  1519. scrollLeftPoint = new Point (c, row);
  1520. }
  1521. }
  1522. // if the next column is the start of a header
  1523. else if (columnsToRender.Any (r => r.X == c + 1))
  1524. {
  1525. /*TODO: is ┼ symbol in Driver?*/
  1526. rune = Style.ShowVerticalCellLines ? Glyphs.Cross : Glyphs.BottomTee;
  1527. }
  1528. else if (c == availableWidth - 1)
  1529. {
  1530. // for the last character in the table
  1531. rune = Style.ShowVerticalCellLines ? Glyphs.RightTee : Glyphs.LRCorner;
  1532. // unless there is more of the table we could horizontally
  1533. // scroll along to see. In which case render an arrow,
  1534. // to indicate user can scroll right
  1535. if (Style.ShowHorizontalScrollIndicators && moreColumnsToRight)
  1536. {
  1537. rune = Glyphs.RightArrow;
  1538. scrollRightPoint = new Point (c, row);
  1539. }
  1540. }
  1541. // if the next console column is the last column's end
  1542. else if (Style.ExpandLastColumn == false && columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c))
  1543. {
  1544. rune = Style.ShowVerticalCellLines ? Glyphs.Cross : Glyphs.BottomTee;
  1545. }
  1546. }
  1547. AddRuneAt (Driver, c, row, rune);
  1548. }
  1549. }
  1550. private void RenderRow (int row, int rowToRender, ColumnToRender [] columnsToRender)
  1551. {
  1552. bool focused = HasFocus;
  1553. ColorScheme rowScheme = Style.RowColorGetter?.Invoke (
  1554. new RowColorGetterArgs (Table, rowToRender)
  1555. )
  1556. ?? ColorScheme;
  1557. //start by clearing the entire line
  1558. Move (0, row);
  1559. Attribute color;
  1560. if (FullRowSelect && IsSelected (0, rowToRender))
  1561. {
  1562. color = focused ? rowScheme.Focus : rowScheme.HotNormal;
  1563. }
  1564. else
  1565. {
  1566. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  1567. }
  1568. Driver.SetAttribute (color);
  1569. Driver.AddStr (new string (' ', Viewport.Width));
  1570. // Render cells for each visible header for the current row
  1571. for (var i = 0; i < columnsToRender.Length; i++)
  1572. {
  1573. ColumnToRender current = columnsToRender [i];
  1574. ColumnStyle colStyle = Style.GetColumnStyleIfAny (current.Column);
  1575. // move to start of cell (in line with header positions)
  1576. Move (current.X, row);
  1577. // Set color scheme based on whether the current cell is the selected one
  1578. bool isSelectedCell = IsSelected (current.Column, rowToRender);
  1579. object val = Table [rowToRender, current.Column];
  1580. // Render the (possibly truncated) cell value
  1581. string representation = GetRepresentation (val, colStyle);
  1582. // to get the colour scheme
  1583. CellColorGetterDelegate colorSchemeGetter = colStyle?.ColorGetter;
  1584. ColorScheme scheme;
  1585. if (colorSchemeGetter is { })
  1586. {
  1587. // user has a delegate for defining row color per cell, call it
  1588. scheme = colorSchemeGetter (
  1589. new CellColorGetterArgs (
  1590. Table,
  1591. rowToRender,
  1592. current.Column,
  1593. val,
  1594. representation,
  1595. rowScheme
  1596. )
  1597. );
  1598. // if users custom color getter returned null, use the row scheme
  1599. if (scheme is null)
  1600. {
  1601. scheme = rowScheme;
  1602. }
  1603. }
  1604. else
  1605. {
  1606. // There is no custom cell coloring delegate so use the scheme for the row
  1607. scheme = rowScheme;
  1608. }
  1609. Attribute cellColor;
  1610. if (isSelectedCell)
  1611. {
  1612. cellColor = focused ? scheme.Focus : scheme.HotNormal;
  1613. }
  1614. else
  1615. {
  1616. cellColor = Enabled ? scheme.Normal : scheme.Disabled;
  1617. }
  1618. string render = TruncateOrPad (val, representation, current.Width, colStyle);
  1619. // While many cells can be selected (see MultiSelectedRegions) only one cell is the primary (drives navigation etc)
  1620. bool isPrimaryCell = current.Column == selectedColumn && rowToRender == selectedRow;
  1621. RenderCell (cellColor, render, isPrimaryCell);
  1622. // Reset color scheme to normal for drawing separators if we drew text with custom scheme
  1623. if (scheme != rowScheme)
  1624. {
  1625. if (isSelectedCell)
  1626. {
  1627. color = focused ? rowScheme.Focus : rowScheme.HotNormal;
  1628. }
  1629. else
  1630. {
  1631. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  1632. }
  1633. Driver.SetAttribute (color);
  1634. }
  1635. // 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
  1636. if (!FullRowSelect)
  1637. {
  1638. Driver.SetAttribute (Enabled ? rowScheme.Normal : rowScheme.Disabled);
  1639. }
  1640. if (style.AlwaysUseNormalColorForVerticalCellLines && style.ShowVerticalCellLines)
  1641. {
  1642. Driver.SetAttribute (rowScheme.Normal);
  1643. }
  1644. RenderSeparator (current.X - 1, row, false);
  1645. if (Style.ExpandLastColumn == false && current.IsVeryLast)
  1646. {
  1647. RenderSeparator (current.X + current.Width - 1, row, false);
  1648. }
  1649. }
  1650. if (style.ShowVerticalCellLines)
  1651. {
  1652. Driver.SetAttribute (rowScheme.Normal);
  1653. //render start and end of line
  1654. AddRune (0, row, Glyphs.VLine);
  1655. AddRune (Viewport.Width - 1, row, Glyphs.VLine);
  1656. }
  1657. }
  1658. private void RenderSeparator (int col, int row, bool isHeader)
  1659. {
  1660. if (col < 0)
  1661. {
  1662. return;
  1663. }
  1664. bool renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  1665. Rune symbol = renderLines ? Glyphs.VLine : (Rune)SeparatorSymbol;
  1666. AddRune (col, row, symbol);
  1667. }
  1668. private bool ShouldRenderHeaders ()
  1669. {
  1670. if (TableIsNullOrInvisible ())
  1671. {
  1672. return false;
  1673. }
  1674. return Style.AlwaysShowHeaders || rowOffset == 0;
  1675. }
  1676. /// <summary>
  1677. /// Returns true if the <see cref="Table"/> is not set or all the columns in the <see cref="Table"/> have an
  1678. /// explicit <see cref="ColumnStyle"/> that marks them <see cref="ColumnStyle.Visible"/> <see langword="false"/>.
  1679. /// </summary>
  1680. /// <returns></returns>
  1681. private bool TableIsNullOrInvisible ()
  1682. {
  1683. return Table == null
  1684. || Table.Columns <= 0
  1685. || Enumerable.Range (0, Table.Columns)
  1686. .All (
  1687. c => (Style.GetColumnStyleIfAny (c)?.Visible ?? true) == false
  1688. );
  1689. }
  1690. private void ToggleCurrentCellSelection ()
  1691. {
  1692. var e = new CellToggledEventArgs (Table, selectedColumn, selectedRow);
  1693. OnCellToggled (e);
  1694. if (e.Cancel)
  1695. {
  1696. return;
  1697. }
  1698. if (!MultiSelect)
  1699. {
  1700. return;
  1701. }
  1702. TableSelection [] regions = GetMultiSelectedRegionsContaining (selectedColumn, selectedRow).ToArray ();
  1703. TableSelection [] toggles = regions.Where (s => s.IsToggled).ToArray ();
  1704. // Toggle it off
  1705. if (toggles.Any ())
  1706. {
  1707. IEnumerable<TableSelection> oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1708. MultiSelectedRegions.Clear ();
  1709. foreach (TableSelection region in oldRegions)
  1710. {
  1711. if (!toggles.Contains (region))
  1712. {
  1713. MultiSelectedRegions.Push (region);
  1714. }
  1715. }
  1716. }
  1717. else
  1718. {
  1719. // user is toggling selection within a rectangular
  1720. // select. So toggle the full region
  1721. if (regions.Any ())
  1722. {
  1723. foreach (TableSelection r in regions)
  1724. {
  1725. r.IsToggled = true;
  1726. }
  1727. }
  1728. else
  1729. {
  1730. // Toggle on a single cell selection
  1731. MultiSelectedRegions.Push (
  1732. CreateTableSelection (
  1733. selectedColumn,
  1734. SelectedRow,
  1735. selectedColumn,
  1736. selectedRow,
  1737. true
  1738. )
  1739. );
  1740. }
  1741. }
  1742. }
  1743. /// <summary>
  1744. /// Truncates or pads <paramref name="representation"/> so that it occupies a exactly
  1745. /// <paramref name="availableHorizontalSpace"/> using the alignment specified in <paramref name="colStyle"/> (or left
  1746. /// if no style is defined)
  1747. /// </summary>
  1748. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  1749. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  1750. /// <param name="availableHorizontalSpace"></param>
  1751. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  1752. /// <returns></returns>
  1753. private string TruncateOrPad (
  1754. object originalCellValue,
  1755. string representation,
  1756. int availableHorizontalSpace,
  1757. ColumnStyle colStyle
  1758. )
  1759. {
  1760. if (string.IsNullOrEmpty (representation))
  1761. {
  1762. return new string (' ', availableHorizontalSpace);
  1763. }
  1764. // if value is not wide enough
  1765. if (representation.EnumerateRunes ().Sum (c => c.GetColumns ()) < availableHorizontalSpace)
  1766. {
  1767. // pad it out with spaces to the given alignment
  1768. int toPad = availableHorizontalSpace
  1769. - (representation.EnumerateRunes ().Sum (c => c.GetColumns ())
  1770. + 1 /*leave 1 space for cell boundary*/);
  1771. switch (colStyle?.GetAlignment (originalCellValue) ?? Alignment.Start)
  1772. {
  1773. case Alignment.Start:
  1774. return representation + new string (' ', toPad);
  1775. case Alignment.End:
  1776. return new string (' ', toPad) + representation;
  1777. // TODO: With single line cells, centered and justified are the same right?
  1778. case Alignment.Center:
  1779. case Alignment.Fill:
  1780. return
  1781. new string (' ', (int)Math.Floor (toPad / 2.0))
  1782. + // round down
  1783. representation
  1784. + new string (' ', (int)Math.Ceiling (toPad / 2.0)); // round up
  1785. }
  1786. }
  1787. // value is too wide
  1788. return new string (
  1789. representation.TakeWhile (c => (availableHorizontalSpace -= ((Rune)c).GetColumns ()) > 0)
  1790. .ToArray ()
  1791. );
  1792. }
  1793. private bool TryGetNearestVisibleColumn (
  1794. int columnIndex,
  1795. bool lookRight,
  1796. bool allowBumpingInOppositeDirection,
  1797. out int idx
  1798. )
  1799. {
  1800. // if the column index provided is out of bounds
  1801. if (table is null || columnIndex < 0 || columnIndex >= table.Columns)
  1802. {
  1803. idx = columnIndex;
  1804. return false;
  1805. }
  1806. // get the column visibility by index (if no style visible is true)
  1807. bool [] columnVisibility =
  1808. Enumerable.Range (0, Table.Columns)
  1809. .Select (c => Style.GetColumnStyleIfAny (c)?.Visible ?? true)
  1810. .ToArray ();
  1811. // column is visible
  1812. if (columnVisibility [columnIndex])
  1813. {
  1814. idx = columnIndex;
  1815. return true;
  1816. }
  1817. int increment = lookRight ? 1 : -1;
  1818. // move in that direction
  1819. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment)
  1820. {
  1821. // if we find a visible column
  1822. if (columnVisibility [i])
  1823. {
  1824. idx = i;
  1825. return true;
  1826. }
  1827. }
  1828. // Caller only wants to look in one direction and we did not find any
  1829. // visible columns in that direction
  1830. if (!allowBumpingInOppositeDirection)
  1831. {
  1832. idx = columnIndex;
  1833. return false;
  1834. }
  1835. // Caller will let us look in the other direction so
  1836. // now look other way
  1837. increment = -increment;
  1838. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment)
  1839. {
  1840. // if we find a visible column
  1841. if (columnVisibility [i])
  1842. {
  1843. idx = i;
  1844. return true;
  1845. }
  1846. }
  1847. // nothing seems to be visible so just return input index
  1848. idx = columnIndex;
  1849. return false;
  1850. }
  1851. /// <summary>Unions the current selected cell (and/or regions) with the provided cell and makes it the active one.</summary>
  1852. /// <param name="col"></param>
  1853. /// <param name="row"></param>
  1854. private void UnionSelection (int col, int row)
  1855. {
  1856. if (!MultiSelect || TableIsNullOrInvisible ())
  1857. {
  1858. return;
  1859. }
  1860. EnsureValidSelection ();
  1861. int oldColumn = SelectedColumn;
  1862. int oldRow = SelectedRow;
  1863. // move us to the new cell
  1864. SelectedColumn = col;
  1865. SelectedRow = row;
  1866. MultiSelectedRegions.Push (
  1867. CreateTableSelection (col, row)
  1868. );
  1869. // if the old cell was not part of a rectangular select
  1870. // or otherwise selected we need to retain it in the selection
  1871. if (!IsSelected (oldColumn, oldRow))
  1872. {
  1873. MultiSelectedRegions.Push (
  1874. CreateTableSelection (oldColumn, oldRow)
  1875. );
  1876. }
  1877. }
  1878. /// <summary>Describes a desire to render a column at a given horizontal position in the UI</summary>
  1879. internal class ColumnToRender
  1880. {
  1881. public ColumnToRender (int col, int x, int width, bool isVeryLast)
  1882. {
  1883. Column = col;
  1884. X = x;
  1885. Width = width;
  1886. IsVeryLast = isVeryLast;
  1887. }
  1888. /// <summary>The column to render</summary>
  1889. public int Column { get; set; }
  1890. /// <summary>True if this column is the very last column in the <see cref="Table"/> (not just the last visible column)</summary>
  1891. public bool IsVeryLast { get; }
  1892. /// <summary>
  1893. /// The width that the column should occupy as calculated by <see cref="CalculateViewport(Rectangle, int)"/>. Note
  1894. /// that this includes space for padding i.e. the separator between columns.
  1895. /// </summary>
  1896. public int Width { get; internal set; }
  1897. /// <summary>The horizontal position to begin rendering the column at</summary>
  1898. public int X { get; set; }
  1899. }
  1900. }