TableView.cs 82 KB

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