TableView.cs 82 KB

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