TableView.cs 81 KB

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