TableView.cs 84 KB

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