TableView.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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. /// Describes how to render a given column in a <see cref="TableView"/> including <see cref="Alignment"/> and textual representation of cells (e.g. date formats)
  9. /// </summary>
  10. public class ColumnStyle {
  11. /// <summary>
  12. /// Defines the default alignment for all values rendered in this column. For custom alignment based on cell contents use <see cref="AlignmentGetter"/>.
  13. /// </summary>
  14. public TextAlignment Alignment {get;set;}
  15. /// <summary>
  16. /// Defines a delegate for returning custom alignment per cell based on cell values. When specified this will override <see cref="Alignment"/>
  17. /// </summary>
  18. public Func<object,TextAlignment> AlignmentGetter;
  19. /// <summary>
  20. /// 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"/>
  21. /// </summary>
  22. public Func<object,string> RepresentationGetter;
  23. /// <summary>
  24. /// Defines the format for values e.g. "yyyy-MM-dd" for dates
  25. /// </summary>
  26. public string Format{get;set;}
  27. /// <summary>
  28. /// 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"/>
  29. /// </summary>
  30. public int MaxWidth {get;set;} = TableView.DefaultMaxCellWidth;
  31. /// <summary>
  32. /// 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"/>
  33. /// </summary>
  34. public int MinWidth {get;set;}
  35. /// <summary>
  36. /// Returns the alignment for the cell based on <paramref name="cellValue"/> and <see cref="AlignmentGetter"/>/<see cref="Alignment"/>
  37. /// </summary>
  38. /// <param name="cellValue"></param>
  39. /// <returns></returns>
  40. public TextAlignment GetAlignment(object cellValue)
  41. {
  42. if(AlignmentGetter != null)
  43. return AlignmentGetter(cellValue);
  44. return Alignment;
  45. }
  46. /// <summary>
  47. /// 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"/>
  48. /// </summary>
  49. /// <param name="value"></param>
  50. /// <returns></returns>
  51. public string GetRepresentation (object value)
  52. {
  53. if(!string.IsNullOrWhiteSpace(Format)) {
  54. if(value is IFormattable f)
  55. return f.ToString(Format,null);
  56. }
  57. if(RepresentationGetter != null)
  58. return RepresentationGetter(value);
  59. return value?.ToString();
  60. }
  61. }
  62. /// <summary>
  63. /// Defines rendering options that affect how the table is displayed
  64. /// </summary>
  65. public class TableStyle {
  66. /// <summary>
  67. /// When scrolling down always lock the column headers in place as the first row of the table
  68. /// </summary>
  69. public bool AlwaysShowHeaders {get;set;} = false;
  70. /// <summary>
  71. /// True to render a solid line above the headers
  72. /// </summary>
  73. public bool ShowHorizontalHeaderOverline {get;set;} = true;
  74. /// <summary>
  75. /// True to render a solid line under the headers
  76. /// </summary>
  77. public bool ShowHorizontalHeaderUnderline {get;set;} = true;
  78. /// <summary>
  79. /// True to render a solid line vertical line between cells
  80. /// </summary>
  81. public bool ShowVerticalCellLines {get;set;} = true;
  82. /// <summary>
  83. /// True to render a solid line vertical line between headers
  84. /// </summary>
  85. public bool ShowVerticalHeaderLines {get;set;} = true;
  86. /// <summary>
  87. /// Collection of columns for which you want special rendering (e.g. custom column lengths, text alignment etc)
  88. /// </summary>
  89. public Dictionary<DataColumn,ColumnStyle> ColumnStyles {get;set; } = new Dictionary<DataColumn, ColumnStyle>();
  90. /// <summary>
  91. /// Returns the entry from <see cref="ColumnStyles"/> for the given <paramref name="col"/> or null if no custom styling is defined for it
  92. /// </summary>
  93. /// <param name="col"></param>
  94. /// <returns></returns>
  95. public ColumnStyle GetColumnStyleIfAny (DataColumn col)
  96. {
  97. return ColumnStyles.TryGetValue(col,out ColumnStyle result) ? result : null;
  98. }
  99. }
  100. /// <summary>
  101. /// View for tabular data based on a <see cref="DataTable"/>
  102. /// </summary>
  103. public class TableView : View {
  104. private int columnOffset;
  105. private int rowOffset;
  106. private int selectedRow;
  107. private int selectedColumn;
  108. private DataTable table;
  109. private TableStyle style = new TableStyle();
  110. /// <summary>
  111. /// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
  112. /// </summary>
  113. public const int DefaultMaxCellWidth = 100;
  114. /// <summary>
  115. /// The data table to render in the view. Setting this property automatically updates and redraws the control.
  116. /// </summary>
  117. public DataTable Table { get => table; set {table = value; Update(); } }
  118. /// <summary>
  119. /// Contains options for changing how the table is rendered
  120. /// </summary>
  121. public TableStyle Style { get => style; set {style = value; Update(); } }
  122. /// <summary>
  123. /// True to select the entire row at once. False to select individual cells. Defaults to false
  124. /// </summary>
  125. public bool FullRowSelect {get;set;}
  126. /// <summary>
  127. /// True to allow regions to be selected
  128. /// </summary>
  129. /// <value></value>
  130. public bool MultiSelect {get;set;} = true;
  131. /// <summary>
  132. /// 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)
  133. /// </summary>
  134. /// <returns></returns>
  135. public Stack<TableSelection> MultiSelectedRegions {get;} = new Stack<TableSelection>();
  136. /// <summary>
  137. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering the view.
  138. /// </summary>
  139. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  140. public int ColumnOffset {
  141. get => columnOffset;
  142. //try to prevent this being set to an out of bounds column
  143. set => columnOffset = Table == null ? 0 :Math.Max (0,Math.Min (Table.Columns.Count - 1, value));
  144. }
  145. /// <summary>
  146. /// 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.
  147. /// </summary>
  148. public int RowOffset {
  149. get => rowOffset;
  150. set => rowOffset = Table == null ? 0 : Math.Max (0,Math.Min (Table.Rows.Count - 1, value));
  151. }
  152. /// <summary>
  153. /// The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected
  154. /// </summary>
  155. public int SelectedColumn {
  156. get => selectedColumn;
  157. set {
  158. var oldValue = selectedColumn;
  159. //try to prevent this being set to an out of bounds column
  160. selectedColumn = Table == null ? 0 : Math.Min (Table.Columns.Count - 1, Math.Max (0, value));
  161. if(oldValue != selectedColumn)
  162. OnSelectedCellChanged(new SelectedCellChangedEventArgs(Table,oldValue,SelectedColumn,SelectedRow,SelectedRow));
  163. }
  164. }
  165. /// <summary>
  166. /// The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected
  167. /// </summary>
  168. public int SelectedRow {
  169. get => selectedRow;
  170. set {
  171. var oldValue = selectedRow;
  172. selectedRow = Table == null ? 0 : Math.Min (Table.Rows.Count - 1, Math.Max (0, value));
  173. if(oldValue != selectedRow)
  174. OnSelectedCellChanged(new SelectedCellChangedEventArgs(Table,SelectedColumn,SelectedColumn,oldValue,selectedRow));
  175. }
  176. }
  177. /// <summary>
  178. /// The maximum number of characters to render in any given column. This prevents one long column from pushing out all the others
  179. /// </summary>
  180. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  181. /// <summary>
  182. /// The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/>
  183. /// </summary>
  184. public string NullSymbol { get; set; } = "-";
  185. /// <summary>
  186. /// The symbol to add after each cell value and header value to visually seperate values (if not using vertical gridlines)
  187. /// </summary>
  188. public char SeparatorSymbol { get; set; } = ' ';
  189. /// <summary>
  190. /// This event is raised when the selected cell in the table changes.
  191. /// </summary>
  192. public event Action<SelectedCellChangedEventArgs> SelectedCellChanged;
  193. /// <summary>
  194. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  195. /// </summary>
  196. /// <param name="table">The table to display in the control</param>
  197. public TableView (DataTable table) : this ()
  198. {
  199. this.Table = table;
  200. }
  201. /// <summary>
  202. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
  203. /// </summary>
  204. public TableView () : base ()
  205. {
  206. CanFocus = true;
  207. }
  208. ///<inheritdoc/>
  209. public override void Redraw (Rect bounds)
  210. {
  211. Move (0, 0);
  212. var frame = Frame;
  213. // What columns to render at what X offset in viewport
  214. var columnsToRender = CalculateViewport(bounds).ToArray();
  215. Driver.SetAttribute (ColorScheme.Normal);
  216. //invalidate current row (prevents scrolling around leaving old characters in the frame
  217. Driver.AddStr (new string (' ', bounds.Width));
  218. int line = 0;
  219. if(ShouldRenderHeaders()){
  220. // Render something like:
  221. /*
  222. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  223. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  224. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  225. */
  226. if(Style.ShowHorizontalHeaderOverline){
  227. RenderHeaderOverline(line,bounds.Width,columnsToRender);
  228. line++;
  229. }
  230. RenderHeaderMidline(line,columnsToRender);
  231. line++;
  232. if(Style.ShowHorizontalHeaderUnderline){
  233. RenderHeaderUnderline(line,bounds.Width,columnsToRender);
  234. line++;
  235. }
  236. }
  237. int headerLinesConsumed = line;
  238. //render the cells
  239. for (; line < frame.Height; line++) {
  240. ClearLine(line,bounds.Width);
  241. //work out what Row to render
  242. var rowToRender = RowOffset + (line - headerLinesConsumed);
  243. //if we have run off the end of the table
  244. if ( Table == null || rowToRender >= Table.Rows.Count || rowToRender < 0)
  245. continue;
  246. RenderRow(line,rowToRender,columnsToRender);
  247. }
  248. }
  249. /// <summary>
  250. /// Clears a line of the console by filling it with spaces
  251. /// </summary>
  252. /// <param name="row"></param>
  253. /// <param name="width"></param>
  254. private void ClearLine(int row, int width)
  255. {
  256. Move (0, row);
  257. Driver.SetAttribute (ColorScheme.Normal);
  258. Driver.AddStr (new string (' ', width));
  259. }
  260. /// <summary>
  261. /// Returns the amount of vertical space required to display the header
  262. /// </summary>
  263. /// <returns></returns>
  264. private int GetHeaderHeight()
  265. {
  266. int heightRequired = 1;
  267. if(Style.ShowHorizontalHeaderOverline)
  268. heightRequired++;
  269. if(Style.ShowHorizontalHeaderUnderline)
  270. heightRequired++;
  271. return heightRequired;
  272. }
  273. private void RenderHeaderOverline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  274. {
  275. // Renders a line above table headers (when visible) like:
  276. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  277. for(int c = 0;c< availableWidth;c++) {
  278. var rune = Driver.HLine;
  279. if (Style.ShowVerticalHeaderLines){
  280. if(c == 0){
  281. rune = Driver.ULCorner;
  282. }
  283. // if the next column is the start of a header
  284. else if(columnsToRender.Any(r=>r.X == c+1)){
  285. rune = Driver.TopTee;
  286. }
  287. else if(c == availableWidth -1){
  288. rune = Driver.URCorner;
  289. }
  290. }
  291. AddRuneAt(Driver,c,row,rune);
  292. }
  293. }
  294. private void RenderHeaderMidline(int row, ColumnToRender[] columnsToRender)
  295. {
  296. // Renders something like:
  297. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  298. ClearLine(row,Bounds.Width);
  299. //render start of line
  300. if(style.ShowVerticalHeaderLines)
  301. AddRune(0,row,Driver.VLine);
  302. for(int i =0 ; i<columnsToRender.Length;i++) {
  303. var current = columnsToRender[i];
  304. var availableWidthForCell = GetCellWidth(columnsToRender,i);
  305. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  306. var colName = current.Column.ColumnName;
  307. RenderSeparator(current.X-1,row,true);
  308. Move (current.X, row);
  309. Driver.AddStr(TruncateOrPad(colName,colName,availableWidthForCell ,colStyle));
  310. }
  311. //render end of line
  312. if(style.ShowVerticalHeaderLines)
  313. AddRune(Bounds.Width-1,row,Driver.VLine);
  314. }
  315. /// <summary>
  316. /// Calculates how much space is available to render index <paramref name="i"/> of the <paramref name="columnsToRender"/> given the remaining horizontal space
  317. /// </summary>
  318. /// <param name="columnsToRender"></param>
  319. /// <param name="i"></param>
  320. private int GetCellWidth (ColumnToRender [] columnsToRender, int i)
  321. {
  322. var current = columnsToRender[i];
  323. var next = i+1 < columnsToRender.Length ? columnsToRender[i+1] : null;
  324. if(next == null) {
  325. // cell can fill to end of the line
  326. return Bounds.Width - current.X;
  327. }
  328. else {
  329. // cell can fill up to next cell start
  330. return next.X - current.X;
  331. }
  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. }
  348. else if(c == availableWidth -1){
  349. rune = Style.ShowVerticalCellLines ? Driver.RightTee : Driver.LRCorner;
  350. }
  351. }
  352. AddRuneAt(Driver,c,row,rune);
  353. }
  354. }
  355. private void RenderRow(int row, int rowToRender, ColumnToRender[] columnsToRender)
  356. {
  357. //render start of line
  358. if(style.ShowVerticalCellLines)
  359. AddRune(0,row,Driver.VLine);
  360. // Render cells for each visible header for the current row
  361. for(int i=0;i< columnsToRender.Length ;i++) {
  362. var current = columnsToRender[i];
  363. var availableWidthForCell = GetCellWidth(columnsToRender,i);
  364. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  365. // move to start of cell (in line with header positions)
  366. Move (current.X, row);
  367. // Set color scheme based on whether the current cell is the selected one
  368. bool isSelectedCell = IsSelected(current.Column.Ordinal,rowToRender);
  369. Driver.SetAttribute (isSelectedCell ? ColorScheme.HotFocus : ColorScheme.Normal);
  370. var val = Table.Rows [rowToRender][current.Column];
  371. // Render the (possibly truncated) cell value
  372. var representation = GetRepresentation(val,colStyle);
  373. Driver.AddStr (TruncateOrPad(val,representation,availableWidthForCell,colStyle));
  374. // 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
  375. if(!FullRowSelect)
  376. Driver.SetAttribute (ColorScheme.Normal);
  377. RenderSeparator(current.X-1,row,false);
  378. }
  379. //render end of line
  380. if(style.ShowVerticalCellLines)
  381. AddRune(Bounds.Width-1,row,Driver.VLine);
  382. }
  383. private void RenderSeparator(int col, int row,bool isHeader)
  384. {
  385. if(col<0)
  386. return;
  387. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  388. Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
  389. AddRune(col,row,symbol);
  390. }
  391. void AddRuneAt (ConsoleDriver d,int col, int row, Rune ch)
  392. {
  393. Move (col, row);
  394. d.AddRune (ch);
  395. }
  396. /// <summary>
  397. /// 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)
  398. /// </summary>
  399. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  400. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  401. /// <param name="availableHorizontalSpace"></param>
  402. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  403. /// <returns></returns>
  404. private string TruncateOrPad (object originalCellValue,string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  405. {
  406. if (string.IsNullOrEmpty (representation))
  407. return representation;
  408. // if value is not wide enough
  409. if(representation.Sum(c=>Rune.ColumnWidth(c)) < availableHorizontalSpace) {
  410. // pad it out with spaces to the given alignment
  411. int toPad = availableHorizontalSpace - (representation.Sum(c=>Rune.ColumnWidth(c)) +1 /*leave 1 space for cell boundary*/);
  412. switch(colStyle?.GetAlignment(originalCellValue) ?? TextAlignment.Left) {
  413. case TextAlignment.Left :
  414. return representation + new string(' ',toPad);
  415. case TextAlignment.Right :
  416. return new string(' ',toPad) + representation;
  417. // TODO: With single line cells, centered and justified are the same right?
  418. case TextAlignment.Centered :
  419. case TextAlignment.Justified :
  420. return
  421. new string(' ',(int)Math.Floor(toPad/2.0)) + // round down
  422. representation +
  423. new string(' ',(int)Math.Ceiling(toPad/2.0)) ; // round up
  424. }
  425. }
  426. // value is too wide
  427. return new string(representation.TakeWhile(c=>(availableHorizontalSpace-= Rune.ColumnWidth(c))>0).ToArray());
  428. }
  429. /// <inheritdoc/>
  430. public override bool ProcessKey (KeyEvent keyEvent)
  431. {
  432. switch (keyEvent.Key) {
  433. case Key.CursorLeft:
  434. case Key.ShiftMask | Key.CursorLeft:
  435. ChangeSelectionByOffset(-1,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  436. Update ();
  437. break;
  438. case Key.CursorRight:
  439. case Key.ShiftMask | Key.CursorRight:
  440. ChangeSelectionByOffset(1,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  441. Update ();
  442. break;
  443. case Key.CursorDown:
  444. case Key.ShiftMask | Key.CursorDown:
  445. ChangeSelectionByOffset(0,1,keyEvent.Key.HasFlag(Key.ShiftMask));
  446. Update ();
  447. break;
  448. case Key.CursorUp:
  449. case Key.ShiftMask | Key.CursorUp:
  450. ChangeSelectionByOffset(0,-1,keyEvent.Key.HasFlag(Key.ShiftMask));
  451. Update ();
  452. break;
  453. case Key.PageUp:
  454. SelectedRow -= Frame.Height;
  455. Update ();
  456. break;
  457. case Key.PageDown:
  458. SelectedRow += Frame.Height;
  459. Update ();
  460. break;
  461. case Key.Home | Key.CtrlMask:
  462. SelectedRow = 0;
  463. SelectedColumn = 0;
  464. Update ();
  465. break;
  466. case Key.Home:
  467. SelectedColumn = 0;
  468. Update ();
  469. break;
  470. case Key.End | Key.CtrlMask:
  471. //jump to end of table
  472. SelectedRow = Table == null ? 0 : Table.Rows.Count - 1;
  473. SelectedColumn = Table == null ? 0 : Table.Columns.Count - 1;
  474. Update ();
  475. break;
  476. case Key.End:
  477. //jump to end of row
  478. SelectedColumn = Table == null ? 0 : Table.Columns.Count - 1;
  479. Update ();
  480. break;
  481. default:
  482. // Not a keystroke we care about
  483. return false;
  484. }
  485. PositionCursor ();
  486. return true;
  487. }
  488. private void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  489. {
  490. if(!MultiSelect || !extendExistingSelection)
  491. MultiSelectedRegions.Clear();
  492. if(extendExistingSelection)
  493. {
  494. // If we are extending current selection but there isn't one
  495. if(MultiSelectedRegions.Count == 0)
  496. {
  497. // Create a new region between the old active cell and the new offset
  498. var rect = CreateTableSelection(SelectedColumn,SelectedRow,SelectedColumn+offsetX,SelectedRow+offsetY);
  499. MultiSelectedRegions.Push(rect);
  500. }
  501. else
  502. {
  503. // Extend the current head selection to include the new offset
  504. var head = MultiSelectedRegions.Pop();
  505. var newRect = CreateTableSelection(head.Origin.X,head.Origin.Y,SelectedColumn + offsetX,SelectedRow + offsetY);
  506. MultiSelectedRegions.Push(newRect);
  507. }
  508. }
  509. SelectedColumn += offsetX;
  510. SelectedRow += offsetY;
  511. }
  512. /// <summary>
  513. /// 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
  514. /// </summary>
  515. /// <param name="pt1X">Origin point for the selection in X</param>
  516. /// <param name="pt1Y">Origin point for the selection in Y</param>
  517. /// <param name="pt2X">End point for the selection in X</param>
  518. /// <param name="pt2Y">End point for the selection in Y</param>
  519. /// <returns></returns>
  520. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y)
  521. {
  522. var top = Math.Min(pt1Y,pt2Y);
  523. var bot = Math.Max(pt1Y,pt2Y);
  524. var left = Math.Min(pt1X,pt2X);
  525. var right = Math.Max(pt1X,pt2X);
  526. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  527. return new TableSelection(new Point(pt1X,pt1Y),new Rect(left,top,right-left + 1,bot-top + 1));
  528. }
  529. /// <summary>
  530. /// 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"/>)
  531. /// </summary>
  532. /// <param name="col"></param>
  533. /// <param name="row"></param>
  534. /// <returns></returns>
  535. public bool IsSelected(int col, int row)
  536. {
  537. // Cell is also selected if
  538. if(MultiSelect && MultiSelectedRegions.Any(r=>r.Rect.Contains(col,row)))
  539. return true;
  540. return row == SelectedRow &&
  541. (col == SelectedColumn || FullRowSelect);
  542. }
  543. /// <summary>
  544. /// 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
  545. /// </summary>
  546. public override void PositionCursor()
  547. {
  548. if(Table == null) {
  549. base.PositionCursor();
  550. return;
  551. }
  552. var screenPoint = CellToScreen(SelectedColumn,SelectedRow);
  553. if(screenPoint != null)
  554. Move(screenPoint.Value.X,screenPoint.Value.Y);
  555. }
  556. ///<inheritdoc/>
  557. public override bool MouseEvent (MouseEvent me)
  558. {
  559. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  560. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  561. me.Flags != MouseFlags.WheeledLeft && me.Flags != MouseFlags.WheeledRight)
  562. return false;
  563. if (!HasFocus && CanFocus) {
  564. SetFocus ();
  565. }
  566. if (Table == null) {
  567. return false;
  568. }
  569. // Scroll wheel flags
  570. switch(me.Flags)
  571. {
  572. case MouseFlags.WheeledDown:
  573. RowOffset++;
  574. EnsureValidScrollOffsets();
  575. SetNeedsDisplay();
  576. return true;
  577. case MouseFlags.WheeledUp:
  578. RowOffset--;
  579. EnsureValidScrollOffsets();
  580. SetNeedsDisplay();
  581. return true;
  582. case MouseFlags.WheeledRight:
  583. ColumnOffset++;
  584. EnsureValidScrollOffsets();
  585. SetNeedsDisplay();
  586. return true;
  587. case MouseFlags.WheeledLeft:
  588. ColumnOffset--;
  589. EnsureValidScrollOffsets();
  590. SetNeedsDisplay();
  591. return true;
  592. }
  593. if(me.Flags == MouseFlags.Button1Clicked) {
  594. var hit = ScreenToCell(me.OfX,me.OfY);
  595. if(hit != null) {
  596. SelectedRow = hit.Value.Y;
  597. SelectedColumn = hit.Value.X;
  598. Update();
  599. }
  600. }
  601. return false;
  602. }
  603. /// <summary>
  604. /// 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
  605. /// </summary>
  606. /// <param name="clientX">X offset from the top left of the control</param>
  607. /// <param name="clientY">Y offset from the top left of the control</param>
  608. /// <returns></returns>
  609. public Point? ScreenToCell (int clientX, int clientY)
  610. {
  611. if(Table == null)
  612. return null;
  613. var viewPort = CalculateViewport(Bounds);
  614. var headerHeight = ShouldRenderHeaders()? GetHeaderHeight():0;
  615. var col = viewPort.LastOrDefault(c=>c.X <= clientX);
  616. // Click is on the header section of rendered UI
  617. if(clientY < headerHeight)
  618. return null;
  619. var rowIdx = RowOffset - headerHeight + clientY;
  620. if(col != null && rowIdx >= 0) {
  621. return new Point(col.Column.Ordinal,rowIdx);
  622. }
  623. return null;
  624. }
  625. /// <summary>
  626. /// 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
  627. /// </summary>
  628. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for, use <see cref="DataColumn.Ordinal"/></param>
  629. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  630. /// <returns></returns>
  631. public Point? CellToScreen (int tableColumn, int tableRow)
  632. {
  633. if(Table == null)
  634. return null;
  635. var viewPort = CalculateViewport(Bounds);
  636. var headerHeight = ShouldRenderHeaders()? GetHeaderHeight():0;
  637. var colHit = viewPort.FirstOrDefault(c=>c.Column.Ordinal == tableColumn);
  638. // current column is outside the scroll area
  639. if(colHit == null)
  640. return null;
  641. // the cell is too far up above the current scroll area
  642. if(RowOffset > tableRow)
  643. return null;
  644. // the cell is way down below the scroll area and off the screen
  645. if(tableRow > RowOffset + (Bounds.Height - headerHeight))
  646. return null;
  647. return new Point(colHit.X,tableRow + headerHeight - RowOffset);
  648. }
  649. /// <summary>
  650. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  651. /// </summary>
  652. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  653. public void Update()
  654. {
  655. if(Table == null) {
  656. SetNeedsDisplay ();
  657. return;
  658. }
  659. EnsureValidScrollOffsets();
  660. EnsureValidSelection();
  661. EnsureSelectedCellIsVisible();
  662. SetNeedsDisplay ();
  663. }
  664. /// <summary>
  665. /// 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.
  666. /// </summary>
  667. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  668. public void EnsureValidScrollOffsets ()
  669. {
  670. if(Table == null){
  671. return;
  672. }
  673. ColumnOffset = Math.Max(Math.Min(ColumnOffset,Table.Columns.Count -1),0);
  674. RowOffset = Math.Max(Math.Min(RowOffset,Table.Rows.Count -1),0);
  675. }
  676. /// <summary>
  677. /// Updates <see cref="SelectedColumn"/> and <see cref="SelectedRow"/> 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.
  678. /// </summary>
  679. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  680. public void EnsureValidSelection ()
  681. {
  682. if(Table == null){
  683. return;
  684. }
  685. SelectedColumn = Math.Max(Math.Min(SelectedColumn,Table.Columns.Count -1),0);
  686. SelectedRow = Math.Max(Math.Min(SelectedRow,Table.Rows.Count -1),0);
  687. }
  688. /// <summary>
  689. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  690. /// </summary>
  691. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  692. public void EnsureSelectedCellIsVisible ()
  693. {
  694. if(Table == null || Table.Columns.Count <= 0){
  695. return;
  696. }
  697. var columnsToRender = CalculateViewport (Bounds).ToArray();
  698. var headerHeight = ShouldRenderHeaders()? GetHeaderHeight() : 0;
  699. //if we have scrolled too far to the left
  700. if (SelectedColumn < columnsToRender.Min (r => r.Column.Ordinal)) {
  701. ColumnOffset = SelectedColumn;
  702. }
  703. //if we have scrolled too far to the right
  704. if (SelectedColumn > columnsToRender.Max (r=> r.Column.Ordinal)) {
  705. ColumnOffset = SelectedColumn;
  706. }
  707. //if we have scrolled too far down
  708. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  709. RowOffset = SelectedRow;
  710. }
  711. //if we have scrolled too far up
  712. if (SelectedRow < RowOffset) {
  713. RowOffset = SelectedRow;
  714. }
  715. }
  716. /// <summary>
  717. /// Invokes the <see cref="SelectedCellChanged"/> event
  718. /// </summary>
  719. protected virtual void OnSelectedCellChanged(SelectedCellChangedEventArgs args)
  720. {
  721. SelectedCellChanged?.Invoke(args);
  722. }
  723. /// <summary>
  724. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  725. /// </summary>
  726. /// <param name="bounds"></param>
  727. /// <param name="padding"></param>
  728. /// <returns></returns>
  729. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  730. {
  731. if(Table == null)
  732. yield break;
  733. int usedSpace = 0;
  734. //if horizontal space is required at the start of the line (before the first header)
  735. if(Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  736. usedSpace+=1;
  737. int availableHorizontalSpace = bounds.Width;
  738. int rowsToRender = bounds.Height;
  739. // reserved for the headers row
  740. if(ShouldRenderHeaders())
  741. rowsToRender -= GetHeaderHeight();
  742. bool first = true;
  743. foreach (var col in Table.Columns.Cast<DataColumn>().Skip (ColumnOffset)) {
  744. int startingIdxForCurrentHeader = usedSpace;
  745. var colStyle = Style.GetColumnStyleIfAny(col);
  746. // is there enough space for this column (and it's data)?
  747. usedSpace += CalculateMaxCellWidth (col, rowsToRender,colStyle) + padding;
  748. // no (don't render it) unless its the only column we are render (that must be one massively wide column!)
  749. if (!first && usedSpace > availableHorizontalSpace)
  750. yield break;
  751. // there is space
  752. yield return new ColumnToRender(col, startingIdxForCurrentHeader);
  753. first=false;
  754. }
  755. }
  756. private bool ShouldRenderHeaders()
  757. {
  758. if(Table == null || Table.Columns.Count == 0)
  759. return false;
  760. return Style.AlwaysShowHeaders || rowOffset == 0;
  761. }
  762. /// <summary>
  763. /// 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"/>
  764. /// </summary>
  765. /// <param name="col"></param>
  766. /// <param name="rowsToRender"></param>
  767. /// <param name="colStyle"></param>
  768. /// <returns></returns>
  769. private int CalculateMaxCellWidth(DataColumn col, int rowsToRender,ColumnStyle colStyle)
  770. {
  771. int spaceRequired = col.ColumnName.Sum(c=>Rune.ColumnWidth(c));
  772. // if table has no rows
  773. if(RowOffset < 0)
  774. return spaceRequired;
  775. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows.Count; i++) {
  776. //expand required space if cell is bigger than the last biggest cell or header
  777. spaceRequired = Math.Max (spaceRequired, GetRepresentation(Table.Rows [i][col],colStyle).Sum(c=>Rune.ColumnWidth(c)));
  778. }
  779. // Don't require more space than the style allows
  780. if(colStyle != null){
  781. // enforce maximum cell width based on style
  782. if(spaceRequired > colStyle.MaxWidth) {
  783. spaceRequired = colStyle.MaxWidth;
  784. }
  785. // enforce minimum cell width based on style
  786. if(spaceRequired < colStyle.MinWidth) {
  787. spaceRequired = colStyle.MinWidth;
  788. }
  789. }
  790. // enforce maximum cell width based on global table style
  791. if(spaceRequired > MaxCellWidth)
  792. spaceRequired = MaxCellWidth;
  793. return spaceRequired;
  794. }
  795. /// <summary>
  796. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  797. /// </summary>
  798. /// <param name="value"></param>
  799. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  800. /// <returns></returns>
  801. private string GetRepresentation(object value,ColumnStyle colStyle)
  802. {
  803. if (value == null || value == DBNull.Value) {
  804. return NullSymbol;
  805. }
  806. return colStyle != null ? colStyle.GetRepresentation(value): value.ToString();
  807. }
  808. }
  809. /// <summary>
  810. /// Describes a desire to render a column at a given horizontal position in the UI
  811. /// </summary>
  812. internal class ColumnToRender {
  813. /// <summary>
  814. /// The column to render
  815. /// </summary>
  816. public DataColumn Column {get;set;}
  817. /// <summary>
  818. /// The horizontal position to begin rendering the column at
  819. /// </summary>
  820. public int X{get;set;}
  821. public ColumnToRender (DataColumn col, int x)
  822. {
  823. Column = col;
  824. X = x;
  825. }
  826. }
  827. /// <summary>
  828. /// Defines the event arguments for <see cref="TableView.SelectedCellChanged"/>
  829. /// </summary>
  830. public class SelectedCellChangedEventArgs : EventArgs
  831. {
  832. /// <summary>
  833. /// 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
  834. /// </summary>
  835. /// <value></value>
  836. public DataTable Table {get;}
  837. /// <summary>
  838. /// 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
  839. /// </summary>
  840. /// <value></value>
  841. public int OldCol {get;}
  842. /// <summary>
  843. /// The newly selected column index.
  844. /// </summary>
  845. /// <value></value>
  846. public int NewCol {get;}
  847. /// <summary>
  848. /// 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
  849. /// </summary>
  850. /// <value></value>
  851. public int OldRow {get;}
  852. /// <summary>
  853. /// The newly selected row index.
  854. /// </summary>
  855. /// <value></value>
  856. public int NewRow {get;}
  857. /// <summary>
  858. /// Creates a new instance of arguments describing a change in selected cell in a <see cref="TableView"/>
  859. /// </summary>
  860. /// <param name="t"></param>
  861. /// <param name="oldCol"></param>
  862. /// <param name="newCol"></param>
  863. /// <param name="oldRow"></param>
  864. /// <param name="newRow"></param>
  865. public SelectedCellChangedEventArgs(DataTable t, int oldCol, int newCol, int oldRow, int newRow)
  866. {
  867. Table = t;
  868. OldCol = oldCol;
  869. NewCol = newCol;
  870. OldRow = oldRow;
  871. NewRow = newRow;
  872. }
  873. }
  874. /// <summary>
  875. /// Describes a selected region of the table
  876. /// </summary>
  877. public class TableSelection{
  878. /// <summary>
  879. /// Corner of the <see cref="Rect"/> where selection began
  880. /// </summary>
  881. /// <value></value>
  882. public Point Origin{get;}
  883. /// <summary>
  884. /// Area selected
  885. /// </summary>
  886. /// <value></value>
  887. public Rect Rect { get; }
  888. /// <summary>
  889. /// Creates a new selected area starting at the origin corner and covering the provided rectangular area
  890. /// </summary>
  891. /// <param name="origin"></param>
  892. /// <param name="rect"></param>
  893. public TableSelection(Point origin, Rect rect)
  894. {
  895. Origin = origin;
  896. Rect = rect;
  897. }
  898. }
  899. }