TableView.cs 82 KB

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