TableView.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. using NStack;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// View for tabular data based on a <see cref="DataTable"/>.
  9. ///
  10. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/tableview.html">See TableView Deep Dive for more information</a>.
  11. /// </summary>
  12. public class TableView : View {
  13. /// <summary>
  14. /// Defines the event arguments for <see cref="TableView.CellActivated"/> event
  15. /// </summary>
  16. public class CellActivatedEventArgs : EventArgs {
  17. /// <summary>
  18. /// The current table to which the new indexes refer. May be null e.g. if selection change is the result of clearing the table from the view
  19. /// </summary>
  20. /// <value></value>
  21. public DataTable Table { get; }
  22. /// <summary>
  23. /// The column index of the <see cref="Table"/> cell that is being activated
  24. /// </summary>
  25. /// <value></value>
  26. public int Col { get; }
  27. /// <summary>
  28. /// The row index of the <see cref="Table"/> cell that is being activated
  29. /// </summary>
  30. /// <value></value>
  31. public int Row { get; }
  32. /// <summary>
  33. /// Creates a new instance of arguments describing a cell being activated in <see cref="TableView"/>
  34. /// </summary>
  35. /// <param name="t"></param>
  36. /// <param name="col"></param>
  37. /// <param name="row"></param>
  38. public CellActivatedEventArgs (DataTable t, int col, int row)
  39. {
  40. Table = t;
  41. Col = col;
  42. Row = row;
  43. }
  44. }
  45. private int columnOffset;
  46. private int rowOffset;
  47. private int selectedRow;
  48. private int selectedColumn;
  49. private DataTable table;
  50. private TableStyle style = new TableStyle ();
  51. private Key cellActivationKey = Key.Enter;
  52. /// <summary>
  53. /// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
  54. /// </summary>
  55. public const int DefaultMaxCellWidth = 100;
  56. /// <summary>
  57. /// The data table to render in the view. Setting this property automatically updates and redraws the control.
  58. /// </summary>
  59. public DataTable Table { get => table; set { table = value; Update (); } }
  60. /// <summary>
  61. /// Contains options for changing how the table is rendered
  62. /// </summary>
  63. public TableStyle Style { get => style; set { style = value; Update (); } }
  64. /// <summary>
  65. /// True to select the entire row at once. False to select individual cells. Defaults to false
  66. /// </summary>
  67. public bool FullRowSelect { get; set; }
  68. /// <summary>
  69. /// True to allow regions to be selected
  70. /// </summary>
  71. /// <value></value>
  72. public bool MultiSelect { get; set; } = true;
  73. /// <summary>
  74. /// When <see cref="MultiSelect"/> is enabled this property contain all rectangles of selected cells. Rectangles describe column/rows selected in <see cref="Table"/> (not screen coordinates)
  75. /// </summary>
  76. /// <returns></returns>
  77. public Stack<TableSelection> MultiSelectedRegions { get; } = new Stack<TableSelection> ();
  78. /// <summary>
  79. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering the view.
  80. /// </summary>
  81. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  82. public int ColumnOffset {
  83. get => columnOffset;
  84. //try to prevent this being set to an out of bounds column
  85. set => columnOffset = Table == null ? 0 : Math.Max (0, Math.Min (Table.Columns.Count - 1, value));
  86. }
  87. /// <summary>
  88. /// Vertical scroll offset. The index of the first row in <see cref="Table"/> to display in the first non header line of the control when rendering the view.
  89. /// </summary>
  90. public int RowOffset {
  91. get => rowOffset;
  92. set => rowOffset = Table == null ? 0 : Math.Max (0, Math.Min (Table.Rows.Count - 1, value));
  93. }
  94. /// <summary>
  95. /// The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected
  96. /// </summary>
  97. public int SelectedColumn {
  98. get => selectedColumn;
  99. set {
  100. var oldValue = selectedColumn;
  101. //try to prevent this being set to an out of bounds column
  102. selectedColumn = Table == null ? 0 : Math.Min (Table.Columns.Count - 1, Math.Max (0, value));
  103. if (oldValue != selectedColumn)
  104. OnSelectedCellChanged (new SelectedCellChangedEventArgs (Table, oldValue, SelectedColumn, SelectedRow, SelectedRow));
  105. }
  106. }
  107. /// <summary>
  108. /// The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected
  109. /// </summary>
  110. public int SelectedRow {
  111. get => selectedRow;
  112. set {
  113. var oldValue = selectedRow;
  114. selectedRow = Table == null ? 0 : Math.Min (Table.Rows.Count - 1, Math.Max (0, value));
  115. if (oldValue != selectedRow)
  116. OnSelectedCellChanged (new SelectedCellChangedEventArgs (Table, SelectedColumn, SelectedColumn, oldValue, selectedRow));
  117. }
  118. }
  119. /// <summary>
  120. /// The maximum number of characters to render in any given column. This prevents one long column from pushing out all the others
  121. /// </summary>
  122. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  123. /// <summary>
  124. /// The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/>
  125. /// </summary>
  126. public string NullSymbol { get; set; } = "-";
  127. /// <summary>
  128. /// The symbol to add after each cell value and header value to visually seperate values (if not using vertical gridlines)
  129. /// </summary>
  130. public char SeparatorSymbol { get; set; } = ' ';
  131. /// <summary>
  132. /// This event is raised when the selected cell in the table changes.
  133. /// </summary>
  134. public event Action<SelectedCellChangedEventArgs> SelectedCellChanged;
  135. /// <summary>
  136. /// This event is raised when a cell is activated e.g. by double clicking or pressing <see cref="CellActivationKey"/>
  137. /// </summary>
  138. public event Action<CellActivatedEventArgs> CellActivated;
  139. /// <summary>
  140. /// The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.
  141. /// </summary>
  142. public Key CellActivationKey {
  143. get => cellActivationKey;
  144. set {
  145. if (cellActivationKey != value) {
  146. ReplaceKeyBinding (cellActivationKey, value);
  147. cellActivationKey = value;
  148. }
  149. }
  150. }
  151. /// <summary>
  152. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  153. /// </summary>
  154. /// <param name="table">The table to display in the control</param>
  155. public TableView (DataTable table) : this ()
  156. {
  157. this.Table = table;
  158. }
  159. /// <summary>
  160. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
  161. /// </summary>
  162. public TableView () : base ()
  163. {
  164. CanFocus = true;
  165. // Things this view knows how to do
  166. AddCommand (Command.Right, () => { ChangeSelectionByOffset (1, 0, false); return true; });
  167. AddCommand (Command.Left, () => { ChangeSelectionByOffset (-1, 0, false); return true; });
  168. AddCommand (Command.LineUp, () => { ChangeSelectionByOffset (0, -1, false); return true; });
  169. AddCommand (Command.LineDown, () => { ChangeSelectionByOffset (0, 1, false); return true; });
  170. AddCommand (Command.PageUp, () => { PageUp (false); return true; });
  171. AddCommand (Command.PageDown, () => { PageDown (false); return true; });
  172. AddCommand (Command.LeftHome, () => { ChangeSelectionToStartOfRow (false); return true; });
  173. AddCommand (Command.RightEnd, () => { ChangeSelectionToEndOfRow (false); return true; });
  174. AddCommand (Command.TopHome, () => { ChangeSelectionToStartOfTable(false); return true; });
  175. AddCommand (Command.BottomEnd, () => { ChangeSelectionToEndOfTable (false); return true; });
  176. AddCommand (Command.RightExtend, () => { ChangeSelectionByOffset (1, 0, true); return true; });
  177. AddCommand (Command.LeftExtend, () => { ChangeSelectionByOffset (-1, 0, true); return true; });
  178. AddCommand (Command.LineUpExtend, () => { ChangeSelectionByOffset (0, -1, true); return true; });
  179. AddCommand (Command.LineDownExtend, () => { ChangeSelectionByOffset (0, 1, true); return true; });
  180. AddCommand (Command.PageUpExtend, () => { PageUp (true); return true; });
  181. AddCommand (Command.PageDownExtend, () => { PageDown (true); return true; });
  182. AddCommand (Command.LeftHomeExtend, () => { ChangeSelectionToStartOfRow (true); return true; });
  183. AddCommand (Command.RightEndExtend, () => { ChangeSelectionToEndOfRow (true); return true; });
  184. AddCommand (Command.TopHomeExtend, () => { ChangeSelectionToStartOfTable (true); return true; });
  185. AddCommand (Command.BottomEndExtend, () => { ChangeSelectionToEndOfTable (true); return true; });
  186. AddCommand (Command.SelectAll, () => { SelectAll(); return true; });
  187. AddCommand (Command.Accept, () => { new CellActivatedEventArgs (Table, SelectedColumn, SelectedRow); return true; });
  188. // Default keybindings for this view
  189. AddKeyBinding (Key.CursorLeft, Command.Left);
  190. AddKeyBinding (Key.CursorRight, Command.Right);
  191. AddKeyBinding (Key.CursorUp, Command.LineUp);
  192. AddKeyBinding (Key.CursorDown, Command.LineDown);
  193. AddKeyBinding (Key.PageUp, Command.PageUp);
  194. AddKeyBinding (Key.PageDown, Command.PageDown);
  195. AddKeyBinding (Key.Home, Command.LeftHome);
  196. AddKeyBinding (Key.End, Command.RightEnd);
  197. AddKeyBinding (Key.Home | Key.CtrlMask, Command.TopHome);
  198. AddKeyBinding (Key.End | Key.CtrlMask, Command.BottomEnd);
  199. AddKeyBinding (Key.CursorLeft | Key.ShiftMask, Command.LeftExtend);
  200. AddKeyBinding (Key.CursorRight | Key.ShiftMask, Command.RightExtend);
  201. AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LineUpExtend);
  202. AddKeyBinding (Key.CursorDown| Key.ShiftMask, Command.LineDownExtend);
  203. AddKeyBinding (Key.PageUp | Key.ShiftMask, Command.PageUpExtend);
  204. AddKeyBinding (Key.PageDown | Key.ShiftMask, Command.PageDownExtend);
  205. AddKeyBinding (Key.Home | Key.ShiftMask, Command.LeftHomeExtend);
  206. AddKeyBinding (Key.End | Key.ShiftMask, Command.RightEndExtend);
  207. AddKeyBinding (Key.Home | Key.CtrlMask | Key.ShiftMask, Command.TopHomeExtend);
  208. AddKeyBinding (Key.End | Key.CtrlMask | Key.ShiftMask, Command.BottomEndExtend);
  209. AddKeyBinding (Key.A | Key.CtrlMask, Command.SelectAll);
  210. AddKeyBinding (CellActivationKey, Command.Accept);
  211. }
  212. ///<inheritdoc/>
  213. public override void Redraw (Rect bounds)
  214. {
  215. Move (0, 0);
  216. var frame = Frame;
  217. // What columns to render at what X offset in viewport
  218. var columnsToRender = CalculateViewport (bounds).ToArray ();
  219. Driver.SetAttribute (GetNormalColor ());
  220. //invalidate current row (prevents scrolling around leaving old characters in the frame
  221. Driver.AddStr (new string (' ', bounds.Width));
  222. int line = 0;
  223. if (ShouldRenderHeaders ()) {
  224. // Render something like:
  225. /*
  226. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  227. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  228. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  229. */
  230. if (Style.ShowHorizontalHeaderOverline) {
  231. RenderHeaderOverline (line, bounds.Width, columnsToRender);
  232. line++;
  233. }
  234. RenderHeaderMidline (line, columnsToRender);
  235. line++;
  236. if (Style.ShowHorizontalHeaderUnderline) {
  237. RenderHeaderUnderline (line, bounds.Width, columnsToRender);
  238. line++;
  239. }
  240. }
  241. int headerLinesConsumed = line;
  242. //render the cells
  243. for (; line < frame.Height; line++) {
  244. ClearLine (line, bounds.Width);
  245. //work out what Row to render
  246. var rowToRender = RowOffset + (line - headerLinesConsumed);
  247. //if we have run off the end of the table
  248. if (Table == null || rowToRender >= Table.Rows.Count || rowToRender < 0)
  249. continue;
  250. RenderRow (line, rowToRender, columnsToRender);
  251. }
  252. }
  253. /// <summary>
  254. /// Clears a line of the console by filling it with spaces
  255. /// </summary>
  256. /// <param name="row"></param>
  257. /// <param name="width"></param>
  258. private void ClearLine (int row, int width)
  259. {
  260. Move (0, row);
  261. Driver.SetAttribute (GetNormalColor ());
  262. Driver.AddStr (new string (' ', width));
  263. }
  264. /// <summary>
  265. /// Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.
  266. /// </summary>
  267. /// <returns></returns>
  268. private int GetHeaderHeightIfAny ()
  269. {
  270. return ShouldRenderHeaders () ? GetHeaderHeight () : 0;
  271. }
  272. /// <summary>
  273. /// Returns the amount of vertical space required to display the header
  274. /// </summary>
  275. /// <returns></returns>
  276. private int GetHeaderHeight ()
  277. {
  278. int heightRequired = 1;
  279. if (Style.ShowHorizontalHeaderOverline)
  280. heightRequired++;
  281. if (Style.ShowHorizontalHeaderUnderline)
  282. heightRequired++;
  283. return heightRequired;
  284. }
  285. private void RenderHeaderOverline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  286. {
  287. // Renders a line above table headers (when visible) like:
  288. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  289. for (int c = 0; c < availableWidth; c++) {
  290. var rune = Driver.HLine;
  291. if (Style.ShowVerticalHeaderLines) {
  292. if (c == 0) {
  293. rune = Driver.ULCorner;
  294. }
  295. // if the next column is the start of a header
  296. else if (columnsToRender.Any (r => r.X == c + 1)) {
  297. rune = Driver.TopTee;
  298. } else if (c == availableWidth - 1) {
  299. rune = Driver.URCorner;
  300. }
  301. // if the next console column is the lastcolumns end
  302. else if (Style.ExpandLastColumn == false &&
  303. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
  304. rune = Driver.TopTee;
  305. }
  306. }
  307. AddRuneAt (Driver, c, row, rune);
  308. }
  309. }
  310. private void RenderHeaderMidline (int row, ColumnToRender [] columnsToRender)
  311. {
  312. // Renders something like:
  313. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  314. ClearLine (row, Bounds.Width);
  315. //render start of line
  316. if (style.ShowVerticalHeaderLines)
  317. AddRune (0, row, Driver.VLine);
  318. for (int i = 0; i < columnsToRender.Length; i++) {
  319. var current = columnsToRender [i];
  320. var colStyle = Style.GetColumnStyleIfAny (current.Column);
  321. var colName = current.Column.ColumnName;
  322. RenderSeparator (current.X - 1, row, true);
  323. Move (current.X, row);
  324. Driver.AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
  325. if (Style.ExpandLastColumn == false && current.IsVeryLast) {
  326. RenderSeparator (current.X + current.Width - 1, row, true);
  327. }
  328. }
  329. //render end of line
  330. if (style.ShowVerticalHeaderLines)
  331. AddRune (Bounds.Width - 1, row, Driver.VLine);
  332. }
  333. private void RenderHeaderUnderline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  334. {
  335. // Renders a line below the table headers (when visible) like:
  336. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  337. for (int c = 0; c < availableWidth; c++) {
  338. var rune = Driver.HLine;
  339. if (Style.ShowVerticalHeaderLines) {
  340. if (c == 0) {
  341. rune = Style.ShowVerticalCellLines ? Driver.LeftTee : Driver.LLCorner;
  342. }
  343. // if the next column is the start of a header
  344. else if (columnsToRender.Any (r => r.X == c + 1)) {
  345. /*TODO: is ┼ symbol in Driver?*/
  346. rune = Style.ShowVerticalCellLines ? '┼' : Driver.BottomTee;
  347. } else if (c == availableWidth - 1) {
  348. rune = Style.ShowVerticalCellLines ? Driver.RightTee : Driver.LRCorner;
  349. }
  350. // if the next console column is the lastcolumns end
  351. else if (Style.ExpandLastColumn == false &&
  352. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
  353. rune = Style.ShowVerticalCellLines ? '┼' : Driver.BottomTee;
  354. }
  355. }
  356. AddRuneAt (Driver, c, row, rune);
  357. }
  358. }
  359. private void RenderRow (int row, int rowToRender, ColumnToRender [] columnsToRender)
  360. {
  361. var rowScheme = (Style.RowColorGetter?.Invoke (
  362. new RowColorGetterArgs(Table,rowToRender))) ?? ColorScheme;
  363. //render start of line
  364. if (style.ShowVerticalCellLines)
  365. AddRune (0, row, Driver.VLine);
  366. //start by clearing the entire line
  367. Move (0, row);
  368. Driver.SetAttribute (FullRowSelect && IsSelected (0, rowToRender) ? rowScheme.HotFocus
  369. : Enabled ? rowScheme.Normal : rowScheme.Disabled);
  370. Driver.AddStr (new string (' ', Bounds.Width));
  371. // Render cells for each visible header for the current row
  372. for (int i = 0; i < columnsToRender.Length; i++) {
  373. var current = columnsToRender [i];
  374. var colStyle = Style.GetColumnStyleIfAny (current.Column);
  375. // move to start of cell (in line with header positions)
  376. Move (current.X, row);
  377. // Set color scheme based on whether the current cell is the selected one
  378. bool isSelectedCell = IsSelected (current.Column.Ordinal, rowToRender);
  379. var val = Table.Rows [rowToRender] [current.Column];
  380. // Render the (possibly truncated) cell value
  381. var representation = GetRepresentation (val, colStyle);
  382. // to get the colour scheme
  383. var colorSchemeGetter = colStyle?.ColorGetter;
  384. ColorScheme scheme;
  385. if(colorSchemeGetter != null) {
  386. // user has a delegate for defining row color per cell, call it
  387. scheme = colorSchemeGetter(
  388. new CellColorGetterArgs (Table, rowToRender, current.Column.Ordinal, val, representation,rowScheme));
  389. // if users custom color getter returned null, use the row scheme
  390. if(scheme == null) {
  391. scheme = rowScheme;
  392. }
  393. }
  394. else {
  395. // There is no custom cell coloring delegate so use the scheme for the row
  396. scheme = rowScheme;
  397. }
  398. var cellColor = isSelectedCell ? scheme.HotFocus : Enabled ? scheme.Normal : scheme.Disabled;
  399. var render = TruncateOrPad (val, representation, current.Width, colStyle);
  400. // While many cells can be selected (see MultiSelectedRegions) only one cell is the primary (drives navigation etc)
  401. bool isPrimaryCell = current.Column.Ordinal == selectedColumn && rowToRender == selectedRow;
  402. RenderCell (cellColor,render,isPrimaryCell);
  403. // Reset color scheme to normal for drawing separators if we drew text with custom scheme
  404. if (scheme != rowScheme) {
  405. Driver.SetAttribute (isSelectedCell ? rowScheme.HotFocus
  406. : Enabled ? rowScheme.Normal : rowScheme.Disabled);
  407. }
  408. // 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
  409. if (!FullRowSelect)
  410. Driver.SetAttribute (Enabled ? rowScheme.Normal : rowScheme.Disabled);
  411. RenderSeparator (current.X - 1, row, false);
  412. if (Style.ExpandLastColumn == false && current.IsVeryLast) {
  413. RenderSeparator (current.X + current.Width - 1, row, false);
  414. }
  415. }
  416. //render end of line
  417. if (style.ShowVerticalCellLines)
  418. AddRune (Bounds.Width - 1, row, Driver.VLine);
  419. }
  420. /// <summary>
  421. /// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to
  422. /// with <see cref="ConsoleDriver.AddStr(ustring)"/>. The driver will already be
  423. /// in the correct place when rendering and you must render the full <paramref name="render"/>
  424. /// or the view will not look right. For simpler provision of color use <see cref="ColumnStyle.ColorGetter"/>
  425. /// For changing the content that is rendered use <see cref="ColumnStyle.RepresentationGetter"/>
  426. /// </summary>
  427. /// <param name="cellColor"></param>
  428. /// <param name="render"></param>
  429. /// <param name="isPrimaryCell"></param>
  430. protected virtual void RenderCell (Attribute cellColor, string render,bool isPrimaryCell)
  431. {
  432. // If the cell is the selected col/row then draw the first rune in inverted colors
  433. // this allows the user to track which cell is the active one during a multi cell
  434. // selection or in full row select mode
  435. if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell) {
  436. if (render.Length > 0) {
  437. // invert the color of the current cell for the first character
  438. Driver.SetAttribute (Driver.MakeAttribute (cellColor.Background, cellColor.Foreground));
  439. Driver.AddRune (render [0]);
  440. if (render.Length > 1) {
  441. Driver.SetAttribute (cellColor);
  442. Driver.AddStr (render.Substring (1));
  443. }
  444. }
  445. } else {
  446. Driver.SetAttribute (cellColor);
  447. Driver.AddStr (render);
  448. }
  449. }
  450. private void RenderSeparator (int col, int row, bool isHeader)
  451. {
  452. if (col < 0)
  453. return;
  454. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  455. Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
  456. AddRune (col, row, symbol);
  457. }
  458. void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
  459. {
  460. Move (col, row);
  461. d.AddRune (ch);
  462. }
  463. /// <summary>
  464. /// Truncates or pads <paramref name="representation"/> so that it occupies a exactly <paramref name="availableHorizontalSpace"/> using the alignment specified in <paramref name="colStyle"/> (or left if no style is defined)
  465. /// </summary>
  466. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  467. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  468. /// <param name="availableHorizontalSpace"></param>
  469. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  470. /// <returns></returns>
  471. private string TruncateOrPad (object originalCellValue, string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  472. {
  473. if (string.IsNullOrEmpty (representation))
  474. return representation;
  475. // if value is not wide enough
  476. if (representation.Sum (c => Rune.ColumnWidth (c)) < availableHorizontalSpace) {
  477. // pad it out with spaces to the given alignment
  478. int toPad = availableHorizontalSpace - (representation.Sum (c => Rune.ColumnWidth (c)) + 1 /*leave 1 space for cell boundary*/);
  479. switch (colStyle?.GetAlignment (originalCellValue) ?? TextAlignment.Left) {
  480. case TextAlignment.Left:
  481. return representation + new string (' ', toPad);
  482. case TextAlignment.Right:
  483. return new string (' ', toPad) + representation;
  484. // TODO: With single line cells, centered and justified are the same right?
  485. case TextAlignment.Centered:
  486. case TextAlignment.Justified:
  487. return
  488. new string (' ', (int)Math.Floor (toPad / 2.0)) + // round down
  489. representation +
  490. new string (' ', (int)Math.Ceiling (toPad / 2.0)); // round up
  491. }
  492. }
  493. // value is too wide
  494. return new string (representation.TakeWhile (c => (availableHorizontalSpace -= Rune.ColumnWidth (c)) > 0).ToArray ());
  495. }
  496. /// <inheritdoc/>
  497. public override bool ProcessKey (KeyEvent keyEvent)
  498. {
  499. if (Table == null) {
  500. PositionCursor ();
  501. return false;
  502. }
  503. var result = InvokeKeybindings (keyEvent);
  504. if (result != null) {
  505. PositionCursor ();
  506. return true;
  507. }
  508. return false;
  509. }
  510. /// <summary>
  511. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  512. /// </summary>
  513. /// <param name="col"></param>
  514. /// <param name="row"></param>
  515. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  516. public void SetSelection (int col, int row, bool extendExistingSelection)
  517. {
  518. if (!MultiSelect || !extendExistingSelection)
  519. MultiSelectedRegions.Clear ();
  520. if (extendExistingSelection) {
  521. // If we are extending current selection but there isn't one
  522. if (MultiSelectedRegions.Count == 0) {
  523. // Create a new region between the old active cell and the new cell
  524. var rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  525. MultiSelectedRegions.Push (rect);
  526. } else {
  527. // Extend the current head selection to include the new cell
  528. var head = MultiSelectedRegions.Pop ();
  529. var newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  530. MultiSelectedRegions.Push (newRect);
  531. }
  532. }
  533. SelectedColumn = col;
  534. SelectedRow = row;
  535. }
  536. /// <summary>
  537. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  538. /// </summary>
  539. /// <param name="offsetX">Offset in number of columns</param>
  540. /// <param name="offsetY">Offset in number of rows</param>
  541. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  542. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  543. {
  544. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
  545. Update ();
  546. }
  547. /// <summary>
  548. /// Moves the selection up by one page
  549. /// </summary>
  550. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  551. public void PageUp(bool extend)
  552. {
  553. ChangeSelectionByOffset (0, -(Bounds.Height - GetHeaderHeightIfAny ()), extend);
  554. Update ();
  555. }
  556. /// <summary>
  557. /// Moves the selection down by one page
  558. /// </summary>
  559. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  560. public void PageDown(bool extend)
  561. {
  562. ChangeSelectionByOffset (0, Bounds.Height - GetHeaderHeightIfAny (), extend);
  563. Update ();
  564. }
  565. /// <summary>
  566. /// Moves or extends the selection to the first cell in the table (0,0)
  567. /// </summary>
  568. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  569. public void ChangeSelectionToStartOfTable (bool extend)
  570. {
  571. SetSelection (0, 0, extend);
  572. Update ();
  573. }
  574. /// <summary>
  575. /// Moves or extends the selection to the final cell in the table
  576. /// </summary>
  577. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  578. public void ChangeSelectionToEndOfTable(bool extend)
  579. {
  580. SetSelection (Table.Columns.Count - 1, Table.Rows.Count - 1, extend);
  581. Update ();
  582. }
  583. /// <summary>
  584. /// Moves or extends the selection to the last cell in the current row
  585. /// </summary>
  586. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  587. public void ChangeSelectionToEndOfRow (bool extend)
  588. {
  589. SetSelection (Table.Columns.Count - 1, SelectedRow, extend);
  590. Update ();
  591. }
  592. /// <summary>
  593. /// Moves or extends the selection to the first cell in the current row
  594. /// </summary>
  595. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  596. public void ChangeSelectionToStartOfRow (bool extend)
  597. {
  598. SetSelection (0, SelectedRow, extend);
  599. Update ();
  600. }
  601. /// <summary>
  602. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old selection regions)
  603. /// </summary>
  604. public void SelectAll ()
  605. {
  606. if (Table == null || !MultiSelect || Table.Rows.Count == 0)
  607. return;
  608. MultiSelectedRegions.Clear ();
  609. // 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
  610. MultiSelectedRegions.Push (new TableSelection (new Point (SelectedColumn, SelectedRow), new Rect (0, 0, Table.Columns.Count, table.Rows.Count)));
  611. Update ();
  612. }
  613. /// <summary>
  614. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the selected cell
  615. /// </summary>
  616. /// <returns></returns>
  617. public IEnumerable<Point> GetAllSelectedCells ()
  618. {
  619. if (Table == null || Table.Rows.Count == 0)
  620. yield break;
  621. EnsureValidSelection ();
  622. // If there are one or more rectangular selections
  623. if (MultiSelect && MultiSelectedRegions.Any ()) {
  624. // 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
  625. var yMin = MultiSelectedRegions.Min (r => r.Rect.Top);
  626. var yMax = MultiSelectedRegions.Max (r => r.Rect.Bottom);
  627. var xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rect.Left);
  628. var xMax = FullRowSelect ? Table.Columns.Count : MultiSelectedRegions.Max (r => r.Rect.Right);
  629. for (int y = yMin; y < yMax; y++) {
  630. for (int x = xMin; x < xMax; x++) {
  631. if (IsSelected (x, y)) {
  632. yield return new Point (x, y);
  633. }
  634. }
  635. }
  636. } else {
  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. // all cells in active row are selected
  641. for (int x = 0; x < Table.Columns.Count; x++) {
  642. yield return new Point (x, SelectedRow);
  643. }
  644. } else {
  645. // Not full row select and no multi selections
  646. yield return new Point (SelectedColumn, SelectedRow);
  647. }
  648. }
  649. }
  650. /// <summary>
  651. /// Returns a new rectangle between the two points with positive width/height regardless of relative positioning of the points. pt1 is always considered the <see cref="TableSelection.Origin"/> point
  652. /// </summary>
  653. /// <param name="pt1X">Origin point for the selection in X</param>
  654. /// <param name="pt1Y">Origin point for the selection in Y</param>
  655. /// <param name="pt2X">End point for the selection in X</param>
  656. /// <param name="pt2Y">End point for the selection in Y</param>
  657. /// <returns></returns>
  658. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y)
  659. {
  660. var top = Math.Min (pt1Y, pt2Y);
  661. var bot = Math.Max (pt1Y, pt2Y);
  662. var left = Math.Min (pt1X, pt2X);
  663. var right = Math.Max (pt1X, pt2X);
  664. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  665. return new TableSelection (new Point (pt1X, pt1Y), new Rect (left, top, right - left + 1, bot - top + 1));
  666. }
  667. /// <summary>
  668. /// Returns true if the given cell is selected either because it is the active cell or part of a multi cell selection (e.g. <see cref="FullRowSelect"/>)
  669. /// </summary>
  670. /// <param name="col"></param>
  671. /// <param name="row"></param>
  672. /// <returns></returns>
  673. public bool IsSelected (int col, int row)
  674. {
  675. // Cell is also selected if in any multi selection region
  676. if (MultiSelect && MultiSelectedRegions.Any (r => r.Rect.Contains (col, row)))
  677. return true;
  678. // Cell is also selected if Y axis appears in any region (when FullRowSelect is enabled)
  679. if (FullRowSelect && MultiSelect && MultiSelectedRegions.Any (r => r.Rect.Bottom > row && r.Rect.Top <= row))
  680. return true;
  681. return row == SelectedRow &&
  682. (col == SelectedColumn || FullRowSelect);
  683. }
  684. /// <summary>
  685. /// Positions the cursor in the area of the screen in which the start of the active cell is rendered. Calls base implementation if active cell is not visible due to scrolling or table is loaded etc
  686. /// </summary>
  687. public override void PositionCursor ()
  688. {
  689. if (Table == null) {
  690. base.PositionCursor ();
  691. return;
  692. }
  693. var screenPoint = CellToScreen (SelectedColumn, SelectedRow);
  694. if (screenPoint != null)
  695. Move (screenPoint.Value.X, screenPoint.Value.Y);
  696. }
  697. ///<inheritdoc/>
  698. public override bool MouseEvent (MouseEvent me)
  699. {
  700. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  701. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  702. me.Flags != MouseFlags.WheeledLeft && me.Flags != MouseFlags.WheeledRight)
  703. return false;
  704. if (!HasFocus && CanFocus) {
  705. SetFocus ();
  706. }
  707. if (Table == null) {
  708. return false;
  709. }
  710. // Scroll wheel flags
  711. switch (me.Flags) {
  712. case MouseFlags.WheeledDown:
  713. RowOffset++;
  714. EnsureValidScrollOffsets ();
  715. SetNeedsDisplay ();
  716. return true;
  717. case MouseFlags.WheeledUp:
  718. RowOffset--;
  719. EnsureValidScrollOffsets ();
  720. SetNeedsDisplay ();
  721. return true;
  722. case MouseFlags.WheeledRight:
  723. ColumnOffset++;
  724. EnsureValidScrollOffsets ();
  725. SetNeedsDisplay ();
  726. return true;
  727. case MouseFlags.WheeledLeft:
  728. ColumnOffset--;
  729. EnsureValidScrollOffsets ();
  730. SetNeedsDisplay ();
  731. return true;
  732. }
  733. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  734. var hit = ScreenToCell (me.X, me.Y);
  735. if (hit != null) {
  736. SetSelection (hit.Value.X, hit.Value.Y, me.Flags.HasFlag (MouseFlags.ButtonShift));
  737. Update ();
  738. }
  739. }
  740. // Double clicking a cell activates
  741. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  742. var hit = ScreenToCell (me.X, me.Y);
  743. if (hit != null) {
  744. OnCellActivated (new CellActivatedEventArgs (Table, hit.Value.X, hit.Value.Y));
  745. }
  746. }
  747. return false;
  748. }
  749. /// <summary>
  750. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative to the control client area). Returns null if the point is in the header, no table is loaded or outside the control bounds
  751. /// </summary>
  752. /// <param name="clientX">X offset from the top left of the control</param>
  753. /// <param name="clientY">Y offset from the top left of the control</param>
  754. /// <returns></returns>
  755. public Point? ScreenToCell (int clientX, int clientY)
  756. {
  757. if (Table == null)
  758. return null;
  759. var viewPort = CalculateViewport (Bounds);
  760. var headerHeight = GetHeaderHeightIfAny ();
  761. var col = viewPort.LastOrDefault (c => c.X <= clientX);
  762. // Click is on the header section of rendered UI
  763. if (clientY < headerHeight)
  764. return null;
  765. var rowIdx = RowOffset - headerHeight + clientY;
  766. if (col != null && rowIdx >= 0) {
  767. return new Point (col.Column.Ordinal, rowIdx);
  768. }
  769. return null;
  770. }
  771. /// <summary>
  772. /// Returns the screen position (relative to the control client area) that the given cell is rendered or null if it is outside the current scroll area or no table is loaded
  773. /// </summary>
  774. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for, use <see cref="DataColumn.Ordinal"/></param>
  775. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  776. /// <returns></returns>
  777. public Point? CellToScreen (int tableColumn, int tableRow)
  778. {
  779. if (Table == null)
  780. return null;
  781. var viewPort = CalculateViewport (Bounds);
  782. var headerHeight = GetHeaderHeightIfAny ();
  783. var colHit = viewPort.FirstOrDefault (c => c.Column.Ordinal == tableColumn);
  784. // current column is outside the scroll area
  785. if (colHit == null)
  786. return null;
  787. // the cell is too far up above the current scroll area
  788. if (RowOffset > tableRow)
  789. return null;
  790. // the cell is way down below the scroll area and off the screen
  791. if (tableRow > RowOffset + (Bounds.Height - headerHeight))
  792. return null;
  793. return new Point (colHit.X, tableRow + headerHeight - RowOffset);
  794. }
  795. /// <summary>
  796. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  797. /// </summary>
  798. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  799. public void Update ()
  800. {
  801. if (Table == null) {
  802. SetNeedsDisplay ();
  803. return;
  804. }
  805. EnsureValidScrollOffsets ();
  806. EnsureValidSelection ();
  807. EnsureSelectedCellIsVisible ();
  808. SetNeedsDisplay ();
  809. }
  810. /// <summary>
  811. /// Updates <see cref="ColumnOffset"/> and <see cref="RowOffset"/> where they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  812. /// </summary>
  813. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  814. public void EnsureValidScrollOffsets ()
  815. {
  816. if (Table == null) {
  817. return;
  818. }
  819. ColumnOffset = Math.Max (Math.Min (ColumnOffset, Table.Columns.Count - 1), 0);
  820. RowOffset = Math.Max (Math.Min (RowOffset, Table.Rows.Count - 1), 0);
  821. }
  822. /// <summary>
  823. /// Updates <see cref="SelectedColumn"/>, <see cref="SelectedRow"/> and <see cref="MultiSelectedRegions"/> where they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  824. /// </summary>
  825. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  826. public void EnsureValidSelection ()
  827. {
  828. if (Table == null) {
  829. // Table doesn't exist, we should probably clear those selections
  830. MultiSelectedRegions.Clear ();
  831. return;
  832. }
  833. SelectedColumn = Math.Max (Math.Min (SelectedColumn, Table.Columns.Count - 1), 0);
  834. SelectedRow = Math.Max (Math.Min (SelectedRow, Table.Rows.Count - 1), 0);
  835. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  836. MultiSelectedRegions.Clear ();
  837. // evaluate
  838. foreach (var region in oldRegions) {
  839. // ignore regions entirely below current table state
  840. if (region.Rect.Top >= Table.Rows.Count)
  841. continue;
  842. // ignore regions entirely too far right of table columns
  843. if (region.Rect.Left >= Table.Columns.Count)
  844. continue;
  845. // ensure region's origin exists
  846. region.Origin = new Point (
  847. Math.Max (Math.Min (region.Origin.X, Table.Columns.Count - 1), 0),
  848. Math.Max (Math.Min (region.Origin.Y, Table.Rows.Count - 1), 0));
  849. // ensure regions do not go over edge of table bounds
  850. region.Rect = Rect.FromLTRB (region.Rect.Left,
  851. region.Rect.Top,
  852. Math.Max (Math.Min (region.Rect.Right, Table.Columns.Count), 0),
  853. Math.Max (Math.Min (region.Rect.Bottom, Table.Rows.Count), 0)
  854. );
  855. MultiSelectedRegions.Push (region);
  856. }
  857. }
  858. /// <summary>
  859. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  860. /// </summary>
  861. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  862. public void EnsureSelectedCellIsVisible ()
  863. {
  864. if (Table == null || Table.Columns.Count <= 0) {
  865. return;
  866. }
  867. var columnsToRender = CalculateViewport (Bounds).ToArray ();
  868. var headerHeight = GetHeaderHeightIfAny ();
  869. //if we have scrolled too far to the left
  870. if (SelectedColumn < columnsToRender.Min (r => r.Column.Ordinal)) {
  871. ColumnOffset = SelectedColumn;
  872. }
  873. //if we have scrolled too far to the right
  874. if (SelectedColumn > columnsToRender.Max (r => r.Column.Ordinal)) {
  875. ColumnOffset = SelectedColumn;
  876. }
  877. //if we have scrolled too far down
  878. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  879. RowOffset = SelectedRow;
  880. }
  881. //if we have scrolled too far up
  882. if (SelectedRow < RowOffset) {
  883. RowOffset = SelectedRow;
  884. }
  885. }
  886. /// <summary>
  887. /// Invokes the <see cref="SelectedCellChanged"/> event
  888. /// </summary>
  889. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args)
  890. {
  891. SelectedCellChanged?.Invoke (args);
  892. }
  893. /// <summary>
  894. /// Invokes the <see cref="CellActivated"/> event
  895. /// </summary>
  896. /// <param name="args"></param>
  897. protected virtual void OnCellActivated (CellActivatedEventArgs args)
  898. {
  899. CellActivated?.Invoke (args);
  900. }
  901. /// <summary>
  902. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  903. /// </summary>
  904. /// <param name="bounds"></param>
  905. /// <param name="padding"></param>
  906. /// <returns></returns>
  907. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  908. {
  909. if (Table == null)
  910. yield break;
  911. int usedSpace = 0;
  912. //if horizontal space is required at the start of the line (before the first header)
  913. if (Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  914. usedSpace += 1;
  915. int availableHorizontalSpace = bounds.Width;
  916. int rowsToRender = bounds.Height;
  917. // reserved for the headers row
  918. if (ShouldRenderHeaders ())
  919. rowsToRender -= GetHeaderHeight ();
  920. bool first = true;
  921. var lastColumn = Table.Columns.Cast<DataColumn> ().Last ();
  922. foreach (var col in Table.Columns.Cast<DataColumn> ().Skip (ColumnOffset)) {
  923. int startingIdxForCurrentHeader = usedSpace;
  924. var colStyle = Style.GetColumnStyleIfAny (col);
  925. int colWidth;
  926. // is there enough space for this column (and it's data)?
  927. usedSpace += colWidth = CalculateMaxCellWidth (col, rowsToRender, colStyle) + padding;
  928. // no (don't render it) unless its the only column we are render (that must be one massively wide column!)
  929. if (!first && usedSpace > availableHorizontalSpace)
  930. yield break;
  931. // there is space
  932. yield return new ColumnToRender (col, startingIdxForCurrentHeader,
  933. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  934. Math.Min (availableHorizontalSpace, colWidth),
  935. lastColumn == col);
  936. first = false;
  937. }
  938. }
  939. private bool ShouldRenderHeaders ()
  940. {
  941. if (Table == null || Table.Columns.Count == 0)
  942. return false;
  943. return Style.AlwaysShowHeaders || rowOffset == 0;
  944. }
  945. /// <summary>
  946. /// Returns the maximum of the <paramref name="col"/> name and the maximum length of data that will be rendered starting at <see cref="RowOffset"/> and rendering <paramref name="rowsToRender"/>
  947. /// </summary>
  948. /// <param name="col"></param>
  949. /// <param name="rowsToRender"></param>
  950. /// <param name="colStyle"></param>
  951. /// <returns></returns>
  952. private int CalculateMaxCellWidth (DataColumn col, int rowsToRender, ColumnStyle colStyle)
  953. {
  954. int spaceRequired = col.ColumnName.Sum (c => Rune.ColumnWidth (c));
  955. // if table has no rows
  956. if (RowOffset < 0)
  957. return spaceRequired;
  958. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows.Count; i++) {
  959. //expand required space if cell is bigger than the last biggest cell or header
  960. spaceRequired = Math.Max (spaceRequired, GetRepresentation (Table.Rows [i] [col], colStyle).Sum (c => Rune.ColumnWidth (c)));
  961. }
  962. // Don't require more space than the style allows
  963. if (colStyle != null) {
  964. // enforce maximum cell width based on style
  965. if (spaceRequired > colStyle.MaxWidth) {
  966. spaceRequired = colStyle.MaxWidth;
  967. }
  968. // enforce minimum cell width based on style
  969. if (spaceRequired < colStyle.MinWidth) {
  970. spaceRequired = colStyle.MinWidth;
  971. }
  972. }
  973. // enforce maximum cell width based on global table style
  974. if (spaceRequired > MaxCellWidth)
  975. spaceRequired = MaxCellWidth;
  976. return spaceRequired;
  977. }
  978. /// <summary>
  979. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  980. /// </summary>
  981. /// <param name="value"></param>
  982. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  983. /// <returns></returns>
  984. private string GetRepresentation (object value, ColumnStyle colStyle)
  985. {
  986. if (value == null || value == DBNull.Value) {
  987. return NullSymbol;
  988. }
  989. return colStyle != null ? colStyle.GetRepresentation (value) : value.ToString ();
  990. }
  991. /// <summary>
  992. /// Delegate for providing color to <see cref="TableView"/> cells based on the value being rendered
  993. /// </summary>
  994. /// <param name="args">Contains information about the cell for which color is needed</param>
  995. /// <returns></returns>
  996. public delegate ColorScheme CellColorGetterDelegate (CellColorGetterArgs args);
  997. /// <summary>
  998. /// Delegate for providing color for a whole row of a <see cref="TableView"/>
  999. /// </summary>
  1000. /// <param name="args"></param>
  1001. /// <returns></returns>
  1002. public delegate ColorScheme RowColorGetterDelegate (RowColorGetterArgs args);
  1003. #region Nested Types
  1004. /// <summary>
  1005. /// Describes how to render a given column in a <see cref="TableView"/> including <see cref="Alignment"/>
  1006. /// and textual representation of cells (e.g. date formats)
  1007. ///
  1008. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/tableview.html">See TableView Deep Dive for more information</a>.
  1009. /// </summary>
  1010. public class ColumnStyle {
  1011. /// <summary>
  1012. /// Defines the default alignment for all values rendered in this column. For custom alignment based on cell contents use <see cref="AlignmentGetter"/>.
  1013. /// </summary>
  1014. public TextAlignment Alignment { get; set; }
  1015. /// <summary>
  1016. /// Defines a delegate for returning custom alignment per cell based on cell values. When specified this will override <see cref="Alignment"/>
  1017. /// </summary>
  1018. public Func<object, TextAlignment> AlignmentGetter;
  1019. /// <summary>
  1020. /// Defines a delegate for returning custom representations of cell values. If not set then <see cref="object.ToString()"/> is used. Return values from your delegate may be truncated e.g. based on <see cref="MaxWidth"/>
  1021. /// </summary>
  1022. public Func<object, string> RepresentationGetter;
  1023. /// <summary>
  1024. /// Defines a delegate for returning a custom color scheme per cell based on cell values.
  1025. /// Return null for the default
  1026. /// </summary>
  1027. public CellColorGetterDelegate ColorGetter;
  1028. /// <summary>
  1029. /// Defines the format for values e.g. "yyyy-MM-dd" for dates
  1030. /// </summary>
  1031. public string Format { get; set; }
  1032. /// <summary>
  1033. /// Set the maximum width of the column in characters. This value will be ignored if more than the tables <see cref="TableView.MaxCellWidth"/>. Defaults to <see cref="TableView.DefaultMaxCellWidth"/>
  1034. /// </summary>
  1035. public int MaxWidth { get; set; } = TableView.DefaultMaxCellWidth;
  1036. /// <summary>
  1037. /// Set the minimum width of the column in characters. This value will be ignored if more than the tables <see cref="TableView.MaxCellWidth"/> or the <see cref="MaxWidth"/>
  1038. /// </summary>
  1039. public int MinWidth { get; set; }
  1040. /// <summary>
  1041. /// Returns the alignment for the cell based on <paramref name="cellValue"/> and <see cref="AlignmentGetter"/>/<see cref="Alignment"/>
  1042. /// </summary>
  1043. /// <param name="cellValue"></param>
  1044. /// <returns></returns>
  1045. public TextAlignment GetAlignment (object cellValue)
  1046. {
  1047. if (AlignmentGetter != null)
  1048. return AlignmentGetter (cellValue);
  1049. return Alignment;
  1050. }
  1051. /// <summary>
  1052. /// Returns the full string to render (which may be truncated if too long) that the current style says best represents the given <paramref name="value"/>
  1053. /// </summary>
  1054. /// <param name="value"></param>
  1055. /// <returns></returns>
  1056. public string GetRepresentation (object value)
  1057. {
  1058. if (!string.IsNullOrWhiteSpace (Format)) {
  1059. if (value is IFormattable f)
  1060. return f.ToString (Format, null);
  1061. }
  1062. if (RepresentationGetter != null)
  1063. return RepresentationGetter (value);
  1064. return value?.ToString ();
  1065. }
  1066. }
  1067. /// <summary>
  1068. /// Defines rendering options that affect how the table is displayed.
  1069. ///
  1070. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/tableview.html">See TableView Deep Dive for more information</a>.
  1071. /// </summary>
  1072. public class TableStyle {
  1073. /// <summary>
  1074. /// When scrolling down always lock the column headers in place as the first row of the table
  1075. /// </summary>
  1076. public bool AlwaysShowHeaders { get; set; } = false;
  1077. /// <summary>
  1078. /// True to render a solid line above the headers
  1079. /// </summary>
  1080. public bool ShowHorizontalHeaderOverline { get; set; } = true;
  1081. /// <summary>
  1082. /// True to render a solid line under the headers
  1083. /// </summary>
  1084. public bool ShowHorizontalHeaderUnderline { get; set; } = true;
  1085. /// <summary>
  1086. /// True to render a solid line vertical line between cells
  1087. /// </summary>
  1088. public bool ShowVerticalCellLines { get; set; } = true;
  1089. /// <summary>
  1090. /// True to render a solid line vertical line between headers
  1091. /// </summary>
  1092. public bool ShowVerticalHeaderLines { get; set; } = true;
  1093. /// <summary>
  1094. /// True to invert the colors of the first symbol of the selected cell in the <see cref="TableView"/>.
  1095. /// This gives the appearance of a cursor for when the <see cref="ConsoleDriver"/> doesn't otherwise show
  1096. /// this
  1097. /// </summary>
  1098. public bool InvertSelectedCellFirstCharacter { get; set; } = false;
  1099. /// <summary>
  1100. /// Collection of columns for which you want special rendering (e.g. custom column lengths, text alignment etc)
  1101. /// </summary>
  1102. public Dictionary<DataColumn, ColumnStyle> ColumnStyles { get; set; } = new Dictionary<DataColumn, ColumnStyle> ();
  1103. /// <summary>
  1104. /// Delegate for coloring specific rows in a different color. For cell color <see cref="ColumnStyle.ColorGetter"/>
  1105. /// </summary>
  1106. /// <value></value>
  1107. public RowColorGetterDelegate RowColorGetter {get;set;}
  1108. /// <summary>
  1109. /// Determines rendering when the last column in the table is visible but it's
  1110. /// content or <see cref="ColumnStyle.MaxWidth"/> is less than the remaining
  1111. /// space in the control. True (the default) will expand the column to fill
  1112. /// the remaining bounds of the control. False will draw a column ending line
  1113. /// and leave a blank column that cannot be selected in the remaining space.
  1114. /// </summary>
  1115. /// <value></value>
  1116. public bool ExpandLastColumn {get;set;} = true;
  1117. /// <summary>
  1118. /// Returns the entry from <see cref="ColumnStyles"/> for the given <paramref name="col"/> or null if no custom styling is defined for it
  1119. /// </summary>
  1120. /// <param name="col"></param>
  1121. /// <returns></returns>
  1122. public ColumnStyle GetColumnStyleIfAny (DataColumn col)
  1123. {
  1124. return ColumnStyles.TryGetValue (col, out ColumnStyle result) ? result : null;
  1125. }
  1126. /// <summary>
  1127. /// Returns an existing <see cref="ColumnStyle"/> for the given <paramref name="col"/> or creates a new one with default options
  1128. /// </summary>
  1129. /// <param name="col"></param>
  1130. /// <returns></returns>
  1131. public ColumnStyle GetOrCreateColumnStyle (DataColumn col)
  1132. {
  1133. if (!ColumnStyles.ContainsKey (col))
  1134. ColumnStyles.Add (col, new ColumnStyle ());
  1135. return ColumnStyles [col];
  1136. }
  1137. }
  1138. /// <summary>
  1139. /// Describes a desire to render a column at a given horizontal position in the UI
  1140. /// </summary>
  1141. internal class ColumnToRender {
  1142. /// <summary>
  1143. /// The column to render
  1144. /// </summary>
  1145. public DataColumn Column { get; set; }
  1146. /// <summary>
  1147. /// The horizontal position to begin rendering the column at
  1148. /// </summary>
  1149. public int X { get; set; }
  1150. /// <summary>
  1151. /// The width that the column should occupy as calculated by <see cref="CalculateViewport(Rect, int)"/>. Note that this includes
  1152. /// space for padding i.e. the separator between columns.
  1153. /// </summary>
  1154. public int Width { get; }
  1155. /// <summary>
  1156. /// True if this column is the very last column in the <see cref="Table"/> (not just the last visible column)
  1157. /// </summary>
  1158. public bool IsVeryLast { get; }
  1159. public ColumnToRender (DataColumn col, int x, int width, bool isVeryLast)
  1160. {
  1161. Column = col;
  1162. X = x;
  1163. Width = width;
  1164. IsVeryLast = isVeryLast;
  1165. }
  1166. }
  1167. /// <summary>
  1168. /// Arguments for a <see cref="CellColorGetterDelegate"/>. Describes a cell for which a rendering
  1169. /// <see cref="ColorScheme"/> is being sought
  1170. /// </summary>
  1171. public class CellColorGetterArgs {
  1172. /// <summary>
  1173. /// The data table hosted by the <see cref="TableView"/> control.
  1174. /// </summary>
  1175. public DataTable Table { get; }
  1176. /// <summary>
  1177. /// The index of the row in <see cref="Table"/> for which color is needed
  1178. /// </summary>
  1179. public int RowIndex { get; }
  1180. /// <summary>
  1181. /// The index of column in <see cref="Table"/> for which color is needed
  1182. /// </summary>
  1183. public int ColIdex { get; }
  1184. /// <summary>
  1185. /// The hard typed value being rendered in the cell for which color is needed
  1186. /// </summary>
  1187. public object CellValue { get; }
  1188. /// <summary>
  1189. /// The textual representation of <see cref="CellValue"/> (what will actually be drawn to the screen)
  1190. /// </summary>
  1191. public string Representation { get; }
  1192. /// <summary>
  1193. /// the color scheme that is going to be used to render the cell if no cell specific color scheme is returned
  1194. /// </summary>
  1195. public ColorScheme RowScheme { get; }
  1196. internal CellColorGetterArgs (DataTable table, int rowIdx, int colIdx, object cellValue, string representation, ColorScheme rowScheme)
  1197. {
  1198. Table = table;
  1199. RowIndex = rowIdx;
  1200. ColIdex = colIdx;
  1201. CellValue = cellValue;
  1202. Representation = representation;
  1203. RowScheme = rowScheme;
  1204. }
  1205. }
  1206. /// <summary>
  1207. /// Arguments for <see cref="RowColorGetterDelegate"/>. Describes a row of data in a <see cref="DataTable"/>
  1208. /// for which <see cref="ColorScheme"/> is sought.
  1209. /// </summary>
  1210. public class RowColorGetterArgs {
  1211. /// <summary>
  1212. /// The data table hosted by the <see cref="TableView"/> control.
  1213. /// </summary>
  1214. public DataTable Table { get; }
  1215. /// <summary>
  1216. /// The index of the row in <see cref="Table"/> for which color is needed
  1217. /// </summary>
  1218. public int RowIndex { get; }
  1219. internal RowColorGetterArgs (DataTable table, int rowIdx)
  1220. {
  1221. Table = table;
  1222. RowIndex = rowIdx;
  1223. }
  1224. }
  1225. /// <summary>
  1226. /// Defines the event arguments for <see cref="TableView.SelectedCellChanged"/>
  1227. /// </summary>
  1228. public class SelectedCellChangedEventArgs : EventArgs {
  1229. /// <summary>
  1230. /// The current table to which the new indexes refer. May be null e.g. if selection change is the result of clearing the table from the view
  1231. /// </summary>
  1232. /// <value></value>
  1233. public DataTable Table { get; }
  1234. /// <summary>
  1235. /// The previous selected column index. May be invalid e.g. when the selection has been changed as a result of replacing the existing Table with a smaller one
  1236. /// </summary>
  1237. /// <value></value>
  1238. public int OldCol { get; }
  1239. /// <summary>
  1240. /// The newly selected column index.
  1241. /// </summary>
  1242. /// <value></value>
  1243. public int NewCol { get; }
  1244. /// <summary>
  1245. /// The previous selected row index. May be invalid e.g. when the selection has been changed as a result of deleting rows from the table
  1246. /// </summary>
  1247. /// <value></value>
  1248. public int OldRow { get; }
  1249. /// <summary>
  1250. /// The newly selected row index.
  1251. /// </summary>
  1252. /// <value></value>
  1253. public int NewRow { get; }
  1254. /// <summary>
  1255. /// Creates a new instance of arguments describing a change in selected cell in a <see cref="TableView"/>
  1256. /// </summary>
  1257. /// <param name="t"></param>
  1258. /// <param name="oldCol"></param>
  1259. /// <param name="newCol"></param>
  1260. /// <param name="oldRow"></param>
  1261. /// <param name="newRow"></param>
  1262. public SelectedCellChangedEventArgs (DataTable t, int oldCol, int newCol, int oldRow, int newRow)
  1263. {
  1264. Table = t;
  1265. OldCol = oldCol;
  1266. NewCol = newCol;
  1267. OldRow = oldRow;
  1268. NewRow = newRow;
  1269. }
  1270. }
  1271. /// <summary>
  1272. /// Describes a selected region of the table
  1273. /// </summary>
  1274. public class TableSelection {
  1275. /// <summary>
  1276. /// Corner of the <see cref="Rect"/> where selection began
  1277. /// </summary>
  1278. /// <value></value>
  1279. public Point Origin { get; set; }
  1280. /// <summary>
  1281. /// Area selected
  1282. /// </summary>
  1283. /// <value></value>
  1284. public Rect Rect { get; set; }
  1285. /// <summary>
  1286. /// Creates a new selected area starting at the origin corner and covering the provided rectangular area
  1287. /// </summary>
  1288. /// <param name="origin"></param>
  1289. /// <param name="rect"></param>
  1290. public TableSelection (Point origin, Rect rect)
  1291. {
  1292. Origin = origin;
  1293. Rect = rect;
  1294. }
  1295. }
  1296. #endregion
  1297. }
  1298. }