TableView.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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. /// This event is raised when a cell is activated e.g. by double clicking or pressing <see cref="CellActivationKey"/>
  195. /// </summary>
  196. public event Action<CellActivatedEventArgs> CellActivated;
  197. /// <summary>
  198. /// The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.
  199. /// </summary>
  200. public Key CellActivationKey {get;set;} = Key.Enter;
  201. /// <summary>
  202. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  203. /// </summary>
  204. /// <param name="table">The table to display in the control</param>
  205. public TableView (DataTable table) : this ()
  206. {
  207. this.Table = table;
  208. }
  209. /// <summary>
  210. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
  211. /// </summary>
  212. public TableView () : base ()
  213. {
  214. CanFocus = true;
  215. }
  216. ///<inheritdoc/>
  217. public override void Redraw (Rect bounds)
  218. {
  219. Move (0, 0);
  220. var frame = Frame;
  221. // What columns to render at what X offset in viewport
  222. var columnsToRender = CalculateViewport(bounds).ToArray();
  223. Driver.SetAttribute (ColorScheme.Normal);
  224. //invalidate current row (prevents scrolling around leaving old characters in the frame
  225. Driver.AddStr (new string (' ', bounds.Width));
  226. int line = 0;
  227. if(ShouldRenderHeaders()){
  228. // Render something like:
  229. /*
  230. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  231. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  232. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  233. */
  234. if(Style.ShowHorizontalHeaderOverline){
  235. RenderHeaderOverline(line,bounds.Width,columnsToRender);
  236. line++;
  237. }
  238. RenderHeaderMidline(line,columnsToRender);
  239. line++;
  240. if(Style.ShowHorizontalHeaderUnderline){
  241. RenderHeaderUnderline(line,bounds.Width,columnsToRender);
  242. line++;
  243. }
  244. }
  245. int headerLinesConsumed = line;
  246. //render the cells
  247. for (; line < frame.Height; line++) {
  248. ClearLine(line,bounds.Width);
  249. //work out what Row to render
  250. var rowToRender = RowOffset + (line - headerLinesConsumed);
  251. //if we have run off the end of the table
  252. if ( Table == null || rowToRender >= Table.Rows.Count || rowToRender < 0)
  253. continue;
  254. RenderRow(line,rowToRender,columnsToRender);
  255. }
  256. }
  257. /// <summary>
  258. /// Clears a line of the console by filling it with spaces
  259. /// </summary>
  260. /// <param name="row"></param>
  261. /// <param name="width"></param>
  262. private void ClearLine(int row, int width)
  263. {
  264. Move (0, row);
  265. Driver.SetAttribute (ColorScheme.Normal);
  266. Driver.AddStr (new string (' ', width));
  267. }
  268. /// <summary>
  269. /// Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.
  270. /// </summary>
  271. /// <returns></returns>
  272. private int GetHeaderHeightIfAny()
  273. {
  274. return ShouldRenderHeaders()? GetHeaderHeight():0;
  275. }
  276. /// <summary>
  277. /// Returns the amount of vertical space required to display the header
  278. /// </summary>
  279. /// <returns></returns>
  280. private int GetHeaderHeight()
  281. {
  282. int heightRequired = 1;
  283. if(Style.ShowHorizontalHeaderOverline)
  284. heightRequired++;
  285. if(Style.ShowHorizontalHeaderUnderline)
  286. heightRequired++;
  287. return heightRequired;
  288. }
  289. private void RenderHeaderOverline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  290. {
  291. // Renders a line above table headers (when visible) like:
  292. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  293. for(int c = 0;c< availableWidth;c++) {
  294. var rune = Driver.HLine;
  295. if (Style.ShowVerticalHeaderLines){
  296. if(c == 0){
  297. rune = Driver.ULCorner;
  298. }
  299. // if the next column is the start of a header
  300. else if(columnsToRender.Any(r=>r.X == c+1)){
  301. rune = Driver.TopTee;
  302. }
  303. else if(c == availableWidth -1){
  304. rune = Driver.URCorner;
  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 availableWidthForCell = GetCellWidth(columnsToRender,i);
  321. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  322. var colName = current.Column.ColumnName;
  323. RenderSeparator(current.X-1,row,true);
  324. Move (current.X, row);
  325. Driver.AddStr(TruncateOrPad(colName,colName,availableWidthForCell ,colStyle));
  326. }
  327. //render end of line
  328. if(style.ShowVerticalHeaderLines)
  329. AddRune(Bounds.Width-1,row,Driver.VLine);
  330. }
  331. /// <summary>
  332. /// Calculates how much space is available to render index <paramref name="i"/> of the <paramref name="columnsToRender"/> given the remaining horizontal space
  333. /// </summary>
  334. /// <param name="columnsToRender"></param>
  335. /// <param name="i"></param>
  336. private int GetCellWidth (ColumnToRender [] columnsToRender, int i)
  337. {
  338. var current = columnsToRender[i];
  339. var next = i+1 < columnsToRender.Length ? columnsToRender[i+1] : null;
  340. if(next == null) {
  341. // cell can fill to end of the line
  342. return Bounds.Width - current.X;
  343. }
  344. else {
  345. // cell can fill up to next cell start
  346. return next.X - current.X;
  347. }
  348. }
  349. private void RenderHeaderUnderline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  350. {
  351. // Renders a line below the table headers (when visible) like:
  352. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  353. for(int c = 0;c< availableWidth;c++) {
  354. var rune = Driver.HLine;
  355. if (Style.ShowVerticalHeaderLines){
  356. if(c == 0){
  357. rune = Style.ShowVerticalCellLines ? Driver.LeftTee : Driver.LLCorner;
  358. }
  359. // if the next column is the start of a header
  360. else if(columnsToRender.Any(r=>r.X == c+1)){
  361. /*TODO: is ┼ symbol in Driver?*/
  362. rune = Style.ShowVerticalCellLines ? '┼' :Driver.BottomTee;
  363. }
  364. else if(c == availableWidth -1){
  365. rune = Style.ShowVerticalCellLines ? Driver.RightTee : Driver.LRCorner;
  366. }
  367. }
  368. AddRuneAt(Driver,c,row,rune);
  369. }
  370. }
  371. private void RenderRow(int row, int rowToRender, ColumnToRender[] columnsToRender)
  372. {
  373. //render start of line
  374. if(style.ShowVerticalCellLines)
  375. AddRune(0,row,Driver.VLine);
  376. // Render cells for each visible header for the current row
  377. for(int i=0;i< columnsToRender.Length ;i++) {
  378. var current = columnsToRender[i];
  379. var availableWidthForCell = GetCellWidth(columnsToRender,i);
  380. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  381. // move to start of cell (in line with header positions)
  382. Move (current.X, row);
  383. // Set color scheme based on whether the current cell is the selected one
  384. bool isSelectedCell = IsSelected(current.Column.Ordinal,rowToRender);
  385. Driver.SetAttribute (isSelectedCell ? ColorScheme.HotFocus : ColorScheme.Normal);
  386. var val = Table.Rows [rowToRender][current.Column];
  387. // Render the (possibly truncated) cell value
  388. var representation = GetRepresentation(val,colStyle);
  389. Driver.AddStr (TruncateOrPad(val,representation,availableWidthForCell,colStyle));
  390. // 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
  391. if(!FullRowSelect)
  392. Driver.SetAttribute (ColorScheme.Normal);
  393. RenderSeparator(current.X-1,row,false);
  394. }
  395. //render end of line
  396. if(style.ShowVerticalCellLines)
  397. AddRune(Bounds.Width-1,row,Driver.VLine);
  398. }
  399. private void RenderSeparator(int col, int row,bool isHeader)
  400. {
  401. if(col<0)
  402. return;
  403. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  404. Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
  405. AddRune(col,row,symbol);
  406. }
  407. void AddRuneAt (ConsoleDriver d,int col, int row, Rune ch)
  408. {
  409. Move (col, row);
  410. d.AddRune (ch);
  411. }
  412. /// <summary>
  413. /// 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)
  414. /// </summary>
  415. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  416. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  417. /// <param name="availableHorizontalSpace"></param>
  418. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  419. /// <returns></returns>
  420. private string TruncateOrPad (object originalCellValue,string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  421. {
  422. if (string.IsNullOrEmpty (representation))
  423. return representation;
  424. // if value is not wide enough
  425. if(representation.Sum(c=>Rune.ColumnWidth(c)) < availableHorizontalSpace) {
  426. // pad it out with spaces to the given alignment
  427. int toPad = availableHorizontalSpace - (representation.Sum(c=>Rune.ColumnWidth(c)) +1 /*leave 1 space for cell boundary*/);
  428. switch(colStyle?.GetAlignment(originalCellValue) ?? TextAlignment.Left) {
  429. case TextAlignment.Left :
  430. return representation + new string(' ',toPad);
  431. case TextAlignment.Right :
  432. return new string(' ',toPad) + representation;
  433. // TODO: With single line cells, centered and justified are the same right?
  434. case TextAlignment.Centered :
  435. case TextAlignment.Justified :
  436. return
  437. new string(' ',(int)Math.Floor(toPad/2.0)) + // round down
  438. representation +
  439. new string(' ',(int)Math.Ceiling(toPad/2.0)) ; // round up
  440. }
  441. }
  442. // value is too wide
  443. return new string(representation.TakeWhile(c=>(availableHorizontalSpace-= Rune.ColumnWidth(c))>0).ToArray());
  444. }
  445. /// <inheritdoc/>
  446. public override bool ProcessKey (KeyEvent keyEvent)
  447. {
  448. if(Table == null){
  449. PositionCursor ();
  450. return true;
  451. }
  452. if(keyEvent.Key == CellActivationKey && Table != null) {
  453. OnCellActivated(new CellActivatedEventArgs(Table,SelectedColumn,SelectedRow));
  454. return true;
  455. }
  456. switch (keyEvent.Key) {
  457. case Key.CursorLeft:
  458. case Key.CursorLeft | Key.ShiftMask:
  459. ChangeSelectionByOffset(-1,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  460. Update ();
  461. break;
  462. case Key.CursorRight:
  463. case Key.CursorRight | Key.ShiftMask:
  464. ChangeSelectionByOffset(1,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  465. Update ();
  466. break;
  467. case Key.CursorDown:
  468. case Key.CursorDown | Key.ShiftMask:
  469. ChangeSelectionByOffset(0,1,keyEvent.Key.HasFlag(Key.ShiftMask));
  470. Update ();
  471. break;
  472. case Key.CursorUp:
  473. case Key.CursorUp | Key.ShiftMask:
  474. ChangeSelectionByOffset(0,-1,keyEvent.Key.HasFlag(Key.ShiftMask));
  475. Update ();
  476. break;
  477. case Key.PageUp:
  478. case Key.PageUp | Key.ShiftMask:
  479. ChangeSelectionByOffset(0,-(Bounds.Height - GetHeaderHeightIfAny()),keyEvent.Key.HasFlag(Key.ShiftMask));
  480. Update ();
  481. break;
  482. case Key.PageDown:
  483. case Key.PageDown | Key.ShiftMask:
  484. ChangeSelectionByOffset(0,Bounds.Height - GetHeaderHeightIfAny(),keyEvent.Key.HasFlag(Key.ShiftMask));
  485. Update ();
  486. break;
  487. case Key.Home | Key.CtrlMask:
  488. case Key.Home | Key.CtrlMask | Key.ShiftMask:
  489. // jump to table origin
  490. SetSelection(0,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  491. Update ();
  492. break;
  493. case Key.Home:
  494. case Key.Home | Key.ShiftMask:
  495. // jump to start of line
  496. SetSelection(0,SelectedRow,keyEvent.Key.HasFlag(Key.ShiftMask));
  497. Update ();
  498. break;
  499. case Key.End | Key.CtrlMask:
  500. case Key.End | Key.CtrlMask | Key.ShiftMask:
  501. // jump to end of table
  502. SetSelection(Table.Columns.Count - 1, Table.Rows.Count - 1, keyEvent.Key.HasFlag(Key.ShiftMask));
  503. Update ();
  504. break;
  505. case Key.End:
  506. case Key.End | Key.ShiftMask:
  507. //jump to end of row
  508. SetSelection(Table.Columns.Count - 1,SelectedRow, keyEvent.Key.HasFlag(Key.ShiftMask));
  509. Update ();
  510. break;
  511. default:
  512. // Not a keystroke we care about
  513. return false;
  514. }
  515. PositionCursor ();
  516. return true;
  517. }
  518. /// <summary>
  519. /// 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"/>)
  520. /// </summary>
  521. /// <param name="col"></param>
  522. /// <param name="row"></param>
  523. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  524. public void SetSelection (int col, int row, bool extendExistingSelection)
  525. {
  526. if(!MultiSelect || !extendExistingSelection)
  527. MultiSelectedRegions.Clear();
  528. if(extendExistingSelection)
  529. {
  530. // If we are extending current selection but there isn't one
  531. if(MultiSelectedRegions.Count == 0)
  532. {
  533. // Create a new region between the old active cell and the new cell
  534. var rect = CreateTableSelection(SelectedColumn,SelectedRow,col,row);
  535. MultiSelectedRegions.Push(rect);
  536. }
  537. else
  538. {
  539. // Extend the current head selection to include the new cell
  540. var head = MultiSelectedRegions.Pop();
  541. var newRect = CreateTableSelection(head.Origin.X,head.Origin.Y,col,row);
  542. MultiSelectedRegions.Push(newRect);
  543. }
  544. }
  545. SelectedColumn = col;
  546. SelectedRow = row;
  547. }
  548. /// <summary>
  549. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  550. /// </summary>
  551. /// <param name="offsetX">Offset in number of columns</param>
  552. /// <param name="offsetY">Offset in number of rows</param>
  553. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  554. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  555. {
  556. SetSelection(SelectedColumn + offsetX, SelectedRow + offsetY,extendExistingSelection);
  557. }
  558. /// <summary>
  559. /// 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
  560. /// </summary>
  561. /// <param name="pt1X">Origin point for the selection in X</param>
  562. /// <param name="pt1Y">Origin point for the selection in Y</param>
  563. /// <param name="pt2X">End point for the selection in X</param>
  564. /// <param name="pt2Y">End point for the selection in Y</param>
  565. /// <returns></returns>
  566. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y)
  567. {
  568. var top = Math.Min(pt1Y,pt2Y);
  569. var bot = Math.Max(pt1Y,pt2Y);
  570. var left = Math.Min(pt1X,pt2X);
  571. var right = Math.Max(pt1X,pt2X);
  572. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  573. return new TableSelection(new Point(pt1X,pt1Y),new Rect(left,top,right-left + 1,bot-top + 1));
  574. }
  575. /// <summary>
  576. /// 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"/>)
  577. /// </summary>
  578. /// <param name="col"></param>
  579. /// <param name="row"></param>
  580. /// <returns></returns>
  581. public bool IsSelected(int col, int row)
  582. {
  583. // Cell is also selected if in any multi selection region
  584. if(MultiSelect && MultiSelectedRegions.Any(r=>r.Rect.Contains(col,row)))
  585. return true;
  586. // Cell is also selected if Y axis appears in any region (when FullRowSelect is enabled)
  587. if(FullRowSelect && MultiSelect && MultiSelectedRegions.Any(r=>r.Rect.Bottom> row && r.Rect.Top <= row))
  588. return true;
  589. return row == SelectedRow &&
  590. (col == SelectedColumn || FullRowSelect);
  591. }
  592. /// <summary>
  593. /// 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
  594. /// </summary>
  595. public override void PositionCursor()
  596. {
  597. if(Table == null) {
  598. base.PositionCursor();
  599. return;
  600. }
  601. var screenPoint = CellToScreen(SelectedColumn,SelectedRow);
  602. if(screenPoint != null)
  603. Move(screenPoint.Value.X,screenPoint.Value.Y);
  604. }
  605. ///<inheritdoc/>
  606. public override bool MouseEvent (MouseEvent me)
  607. {
  608. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  609. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  610. me.Flags != MouseFlags.WheeledLeft && me.Flags != MouseFlags.WheeledRight)
  611. return false;
  612. if (!HasFocus && CanFocus) {
  613. SetFocus ();
  614. }
  615. if (Table == null) {
  616. return false;
  617. }
  618. // Scroll wheel flags
  619. switch(me.Flags)
  620. {
  621. case MouseFlags.WheeledDown:
  622. RowOffset++;
  623. EnsureValidScrollOffsets();
  624. SetNeedsDisplay();
  625. return true;
  626. case MouseFlags.WheeledUp:
  627. RowOffset--;
  628. EnsureValidScrollOffsets();
  629. SetNeedsDisplay();
  630. return true;
  631. case MouseFlags.WheeledRight:
  632. ColumnOffset++;
  633. EnsureValidScrollOffsets();
  634. SetNeedsDisplay();
  635. return true;
  636. case MouseFlags.WheeledLeft:
  637. ColumnOffset--;
  638. EnsureValidScrollOffsets();
  639. SetNeedsDisplay();
  640. return true;
  641. }
  642. if(me.Flags.HasFlag(MouseFlags.Button1Clicked)) {
  643. var hit = ScreenToCell(me.OfX,me.OfY);
  644. if(hit != null) {
  645. SetSelection(hit.Value.X,hit.Value.Y,me.Flags.HasFlag(MouseFlags.ButtonShift));
  646. Update();
  647. }
  648. }
  649. // Double clicking a cell activates
  650. if(me.Flags == MouseFlags.Button1DoubleClicked) {
  651. var hit = ScreenToCell(me.OfX,me.OfY);
  652. if(hit!= null) {
  653. OnCellActivated(new CellActivatedEventArgs(Table,hit.Value.X,hit.Value.Y));
  654. }
  655. }
  656. return false;
  657. }
  658. /// <summary>
  659. /// 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
  660. /// </summary>
  661. /// <param name="clientX">X offset from the top left of the control</param>
  662. /// <param name="clientY">Y offset from the top left of the control</param>
  663. /// <returns></returns>
  664. public Point? ScreenToCell (int clientX, int clientY)
  665. {
  666. if(Table == null)
  667. return null;
  668. var viewPort = CalculateViewport(Bounds);
  669. var headerHeight = GetHeaderHeightIfAny();
  670. var col = viewPort.LastOrDefault(c=>c.X <= clientX);
  671. // Click is on the header section of rendered UI
  672. if(clientY < headerHeight)
  673. return null;
  674. var rowIdx = RowOffset - headerHeight + clientY;
  675. if(col != null && rowIdx >= 0) {
  676. return new Point(col.Column.Ordinal,rowIdx);
  677. }
  678. return null;
  679. }
  680. /// <summary>
  681. /// 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
  682. /// </summary>
  683. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for, use <see cref="DataColumn.Ordinal"/></param>
  684. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  685. /// <returns></returns>
  686. public Point? CellToScreen (int tableColumn, int tableRow)
  687. {
  688. if(Table == null)
  689. return null;
  690. var viewPort = CalculateViewport(Bounds);
  691. var headerHeight = GetHeaderHeightIfAny();
  692. var colHit = viewPort.FirstOrDefault(c=>c.Column.Ordinal == tableColumn);
  693. // current column is outside the scroll area
  694. if(colHit == null)
  695. return null;
  696. // the cell is too far up above the current scroll area
  697. if(RowOffset > tableRow)
  698. return null;
  699. // the cell is way down below the scroll area and off the screen
  700. if(tableRow > RowOffset + (Bounds.Height - headerHeight))
  701. return null;
  702. return new Point(colHit.X,tableRow + headerHeight - RowOffset);
  703. }
  704. /// <summary>
  705. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  706. /// </summary>
  707. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  708. public void Update()
  709. {
  710. if(Table == null) {
  711. SetNeedsDisplay ();
  712. return;
  713. }
  714. EnsureValidScrollOffsets();
  715. EnsureValidSelection();
  716. EnsureSelectedCellIsVisible();
  717. SetNeedsDisplay ();
  718. }
  719. /// <summary>
  720. /// 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.
  721. /// </summary>
  722. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  723. public void EnsureValidScrollOffsets ()
  724. {
  725. if(Table == null){
  726. return;
  727. }
  728. ColumnOffset = Math.Max(Math.Min(ColumnOffset,Table.Columns.Count -1),0);
  729. RowOffset = Math.Max(Math.Min(RowOffset,Table.Rows.Count -1),0);
  730. }
  731. /// <summary>
  732. /// 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.
  733. /// </summary>
  734. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  735. public void EnsureValidSelection ()
  736. {
  737. if(Table == null){
  738. return;
  739. }
  740. SelectedColumn = Math.Max(Math.Min(SelectedColumn,Table.Columns.Count -1),0);
  741. SelectedRow = Math.Max(Math.Min(SelectedRow,Table.Rows.Count -1),0);
  742. }
  743. /// <summary>
  744. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  745. /// </summary>
  746. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  747. public void EnsureSelectedCellIsVisible ()
  748. {
  749. if(Table == null || Table.Columns.Count <= 0){
  750. return;
  751. }
  752. var columnsToRender = CalculateViewport (Bounds).ToArray();
  753. var headerHeight = GetHeaderHeightIfAny();
  754. //if we have scrolled too far to the left
  755. if (SelectedColumn < columnsToRender.Min (r => r.Column.Ordinal)) {
  756. ColumnOffset = SelectedColumn;
  757. }
  758. //if we have scrolled too far to the right
  759. if (SelectedColumn > columnsToRender.Max (r=> r.Column.Ordinal)) {
  760. ColumnOffset = SelectedColumn;
  761. }
  762. //if we have scrolled too far down
  763. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  764. RowOffset = SelectedRow;
  765. }
  766. //if we have scrolled too far up
  767. if (SelectedRow < RowOffset) {
  768. RowOffset = SelectedRow;
  769. }
  770. }
  771. /// <summary>
  772. /// Invokes the <see cref="SelectedCellChanged"/> event
  773. /// </summary>
  774. protected virtual void OnSelectedCellChanged(SelectedCellChangedEventArgs args)
  775. {
  776. SelectedCellChanged?.Invoke(args);
  777. }
  778. /// <summary>
  779. /// Invokes the <see cref="CellActivated"/> event
  780. /// </summary>
  781. /// <param name="args"></param>
  782. protected virtual void OnCellActivated (CellActivatedEventArgs args)
  783. {
  784. CellActivated?.Invoke(args);
  785. }
  786. /// <summary>
  787. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  788. /// </summary>
  789. /// <param name="bounds"></param>
  790. /// <param name="padding"></param>
  791. /// <returns></returns>
  792. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  793. {
  794. if(Table == null)
  795. yield break;
  796. int usedSpace = 0;
  797. //if horizontal space is required at the start of the line (before the first header)
  798. if(Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  799. usedSpace+=1;
  800. int availableHorizontalSpace = bounds.Width;
  801. int rowsToRender = bounds.Height;
  802. // reserved for the headers row
  803. if(ShouldRenderHeaders())
  804. rowsToRender -= GetHeaderHeight();
  805. bool first = true;
  806. foreach (var col in Table.Columns.Cast<DataColumn>().Skip (ColumnOffset)) {
  807. int startingIdxForCurrentHeader = usedSpace;
  808. var colStyle = Style.GetColumnStyleIfAny(col);
  809. // is there enough space for this column (and it's data)?
  810. usedSpace += CalculateMaxCellWidth (col, rowsToRender,colStyle) + padding;
  811. // no (don't render it) unless its the only column we are render (that must be one massively wide column!)
  812. if (!first && usedSpace > availableHorizontalSpace)
  813. yield break;
  814. // there is space
  815. yield return new ColumnToRender(col, startingIdxForCurrentHeader);
  816. first=false;
  817. }
  818. }
  819. private bool ShouldRenderHeaders()
  820. {
  821. if(Table == null || Table.Columns.Count == 0)
  822. return false;
  823. return Style.AlwaysShowHeaders || rowOffset == 0;
  824. }
  825. /// <summary>
  826. /// 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"/>
  827. /// </summary>
  828. /// <param name="col"></param>
  829. /// <param name="rowsToRender"></param>
  830. /// <param name="colStyle"></param>
  831. /// <returns></returns>
  832. private int CalculateMaxCellWidth(DataColumn col, int rowsToRender,ColumnStyle colStyle)
  833. {
  834. int spaceRequired = col.ColumnName.Sum(c=>Rune.ColumnWidth(c));
  835. // if table has no rows
  836. if(RowOffset < 0)
  837. return spaceRequired;
  838. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows.Count; i++) {
  839. //expand required space if cell is bigger than the last biggest cell or header
  840. spaceRequired = Math.Max (spaceRequired, GetRepresentation(Table.Rows [i][col],colStyle).Sum(c=>Rune.ColumnWidth(c)));
  841. }
  842. // Don't require more space than the style allows
  843. if(colStyle != null){
  844. // enforce maximum cell width based on style
  845. if(spaceRequired > colStyle.MaxWidth) {
  846. spaceRequired = colStyle.MaxWidth;
  847. }
  848. // enforce minimum cell width based on style
  849. if(spaceRequired < colStyle.MinWidth) {
  850. spaceRequired = colStyle.MinWidth;
  851. }
  852. }
  853. // enforce maximum cell width based on global table style
  854. if(spaceRequired > MaxCellWidth)
  855. spaceRequired = MaxCellWidth;
  856. return spaceRequired;
  857. }
  858. /// <summary>
  859. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  860. /// </summary>
  861. /// <param name="value"></param>
  862. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  863. /// <returns></returns>
  864. private string GetRepresentation(object value,ColumnStyle colStyle)
  865. {
  866. if (value == null || value == DBNull.Value) {
  867. return NullSymbol;
  868. }
  869. return colStyle != null ? colStyle.GetRepresentation(value): value.ToString();
  870. }
  871. }
  872. /// <summary>
  873. /// Describes a desire to render a column at a given horizontal position in the UI
  874. /// </summary>
  875. internal class ColumnToRender {
  876. /// <summary>
  877. /// The column to render
  878. /// </summary>
  879. public DataColumn Column {get;set;}
  880. /// <summary>
  881. /// The horizontal position to begin rendering the column at
  882. /// </summary>
  883. public int X{get;set;}
  884. public ColumnToRender (DataColumn col, int x)
  885. {
  886. Column = col;
  887. X = x;
  888. }
  889. }
  890. /// <summary>
  891. /// Defines the event arguments for <see cref="TableView.SelectedCellChanged"/>
  892. /// </summary>
  893. public class SelectedCellChangedEventArgs : EventArgs
  894. {
  895. /// <summary>
  896. /// 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
  897. /// </summary>
  898. /// <value></value>
  899. public DataTable Table {get;}
  900. /// <summary>
  901. /// 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
  902. /// </summary>
  903. /// <value></value>
  904. public int OldCol {get;}
  905. /// <summary>
  906. /// The newly selected column index.
  907. /// </summary>
  908. /// <value></value>
  909. public int NewCol {get;}
  910. /// <summary>
  911. /// 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
  912. /// </summary>
  913. /// <value></value>
  914. public int OldRow {get;}
  915. /// <summary>
  916. /// The newly selected row index.
  917. /// </summary>
  918. /// <value></value>
  919. public int NewRow {get;}
  920. /// <summary>
  921. /// Creates a new instance of arguments describing a change in selected cell in a <see cref="TableView"/>
  922. /// </summary>
  923. /// <param name="t"></param>
  924. /// <param name="oldCol"></param>
  925. /// <param name="newCol"></param>
  926. /// <param name="oldRow"></param>
  927. /// <param name="newRow"></param>
  928. public SelectedCellChangedEventArgs(DataTable t, int oldCol, int newCol, int oldRow, int newRow)
  929. {
  930. Table = t;
  931. OldCol = oldCol;
  932. NewCol = newCol;
  933. OldRow = oldRow;
  934. NewRow = newRow;
  935. }
  936. }
  937. /// <summary>
  938. /// Describes a selected region of the table
  939. /// </summary>
  940. public class TableSelection
  941. {
  942. /// <summary>
  943. /// Corner of the <see cref="Rect"/> where selection began
  944. /// </summary>
  945. /// <value></value>
  946. public Point Origin{get;}
  947. /// <summary>
  948. /// Area selected
  949. /// </summary>
  950. /// <value></value>
  951. public Rect Rect { get; }
  952. /// <summary>
  953. /// Creates a new selected area starting at the origin corner and covering the provided rectangular area
  954. /// </summary>
  955. /// <param name="origin"></param>
  956. /// <param name="rect"></param>
  957. public TableSelection(Point origin, Rect rect)
  958. {
  959. Origin = origin;
  960. Rect = rect;
  961. }
  962. }
  963. /// <summary>
  964. /// Defines the event arguments for <see cref="TableView.CellActivated"/> event
  965. /// </summary>
  966. public class CellActivatedEventArgs : EventArgs
  967. {
  968. /// <summary>
  969. /// 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
  970. /// </summary>
  971. /// <value></value>
  972. public DataTable Table {get;}
  973. /// <summary>
  974. /// The column index of the <see cref="Table"/> cell that is being activated
  975. /// </summary>
  976. /// <value></value>
  977. public int Col {get;}
  978. /// <summary>
  979. /// The row index of the <see cref="Table"/> cell that is being activated
  980. /// </summary>
  981. /// <value></value>
  982. public int Row {get;}
  983. /// <summary>
  984. /// Creates a new instance of arguments describing a cell being activated in <see cref="TableView"/>
  985. /// </summary>
  986. /// <param name="t"></param>
  987. /// <param name="col"></param>
  988. /// <param name="row"></param>
  989. public CellActivatedEventArgs(DataTable t, int col, int row)
  990. {
  991. Table = t;
  992. Col = col;
  993. Row = row;
  994. }
  995. }
  996. }