TableView.cs 84 KB

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