TableView.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering the view.
  124. /// </summary>
  125. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  126. public int ColumnOffset {
  127. get => columnOffset;
  128. //try to prevent this being set to an out of bounds column
  129. set => columnOffset = Table == null ? 0 :Math.Max (0,Math.Min (Table.Columns.Count - 1, value));
  130. }
  131. /// <summary>
  132. /// 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.
  133. /// </summary>
  134. public int RowOffset {
  135. get => rowOffset;
  136. set => rowOffset = Table == null ? 0 : Math.Max (0,Math.Min (Table.Rows.Count - 1, value));
  137. }
  138. /// <summary>
  139. /// The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected
  140. /// </summary>
  141. public int SelectedColumn {
  142. get => selectedColumn;
  143. //try to prevent this being set to an out of bounds column
  144. set => selectedColumn = Table == null ? 0 : Math.Min (Table.Columns.Count - 1, Math.Max (0, value));
  145. }
  146. /// <summary>
  147. /// The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected
  148. /// </summary>
  149. public int SelectedRow {
  150. get => selectedRow;
  151. set => selectedRow = Table == null ? 0 : Math.Min (Table.Rows.Count - 1, Math.Max (0, value));
  152. }
  153. /// <summary>
  154. /// The maximum number of characters to render in any given column. This prevents one long column from pushing out all the others
  155. /// </summary>
  156. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  157. /// <summary>
  158. /// The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/>
  159. /// </summary>
  160. public string NullSymbol { get; set; } = "-";
  161. /// <summary>
  162. /// The symbol to add after each cell value and header value to visually seperate values (if not using vertical gridlines)
  163. /// </summary>
  164. public char SeparatorSymbol { get; set; } = ' ';
  165. /// <summary>
  166. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  167. /// </summary>
  168. /// <param name="table">The table to display in the control</param>
  169. public TableView (DataTable table) : this ()
  170. {
  171. this.Table = table;
  172. }
  173. /// <summary>
  174. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
  175. /// </summary>
  176. public TableView () : base ()
  177. {
  178. CanFocus = true;
  179. }
  180. ///<inheritdoc/>
  181. public override void Redraw (Rect bounds)
  182. {
  183. Move (0, 0);
  184. var frame = Frame;
  185. // What columns to render at what X offset in viewport
  186. var columnsToRender = CalculateViewport(bounds).ToArray();
  187. Driver.SetAttribute (ColorScheme.Normal);
  188. //invalidate current row (prevents scrolling around leaving old characters in the frame
  189. Driver.AddStr (new string (' ', bounds.Width));
  190. int line = 0;
  191. if(ShouldRenderHeaders()){
  192. // Render something like:
  193. /*
  194. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  195. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  196. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  197. */
  198. if(Style.ShowHorizontalHeaderOverline){
  199. RenderHeaderOverline(line,bounds.Width,columnsToRender);
  200. line++;
  201. }
  202. RenderHeaderMidline(line,columnsToRender);
  203. line++;
  204. if(Style.ShowHorizontalHeaderUnderline){
  205. RenderHeaderUnderline(line,bounds.Width,columnsToRender);
  206. line++;
  207. }
  208. }
  209. //render the cells
  210. for (; line < frame.Height; line++) {
  211. ClearLine(line,bounds.Width);
  212. //work out what Row to render
  213. var rowToRender = RowOffset + (line - GetHeaderHeight());
  214. //if we have run off the end of the table
  215. if ( Table == null || rowToRender >= Table.Rows.Count || rowToRender < 0)
  216. continue;
  217. RenderRow(line,rowToRender,columnsToRender);
  218. }
  219. }
  220. /// <summary>
  221. /// Clears a line of the console by filling it with spaces
  222. /// </summary>
  223. /// <param name="row"></param>
  224. /// <param name="width"></param>
  225. private void ClearLine(int row, int width)
  226. {
  227. Move (0, row);
  228. Driver.SetAttribute (ColorScheme.Normal);
  229. Driver.AddStr (new string (' ', width));
  230. }
  231. /// <summary>
  232. /// Returns the amount of vertical space required to display the header
  233. /// </summary>
  234. /// <returns></returns>
  235. private int GetHeaderHeight()
  236. {
  237. int heightRequired = 1;
  238. if(Style.ShowHorizontalHeaderOverline)
  239. heightRequired++;
  240. if(Style.ShowHorizontalHeaderUnderline)
  241. heightRequired++;
  242. return heightRequired;
  243. }
  244. private void RenderHeaderOverline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  245. {
  246. // Renders a line above table headers (when visible) like:
  247. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  248. for(int c = 0;c< availableWidth;c++) {
  249. var rune = Driver.HLine;
  250. if (Style.ShowVerticalHeaderLines){
  251. if(c == 0){
  252. rune = Driver.ULCorner;
  253. }
  254. // if the next column is the start of a header
  255. else if(columnsToRender.Any(r=>r.X == c+1)){
  256. rune = Driver.TopTee;
  257. }
  258. else if(c == availableWidth -1){
  259. rune = Driver.URCorner;
  260. }
  261. }
  262. AddRuneAt(Driver,c,row,rune);
  263. }
  264. }
  265. private void RenderHeaderMidline(int row, ColumnToRender[] columnsToRender)
  266. {
  267. // Renders something like:
  268. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  269. ClearLine(row,Bounds.Width);
  270. //render start of line
  271. if(style.ShowVerticalHeaderLines)
  272. AddRune(0,row,Driver.VLine);
  273. for(int i =0 ; i<columnsToRender.Length;i++) {
  274. var current = columnsToRender[i];
  275. var availableWidthForCell = GetCellWidth(columnsToRender,i);
  276. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  277. var colName = current.Column.ColumnName;
  278. RenderSeparator(current.X-1,row,true);
  279. Move (current.X, row);
  280. Driver.AddStr(TruncateOrPad(colName,colName,availableWidthForCell ,colStyle));
  281. }
  282. //render end of line
  283. if(style.ShowVerticalHeaderLines)
  284. AddRune(Bounds.Width-1,row,Driver.VLine);
  285. }
  286. /// <summary>
  287. /// Calculates how much space is available to render index <paramref name="i"/> of the <paramref name="columnsToRender"/> given the remaining horizontal space
  288. /// </summary>
  289. /// <param name="columnsToRender"></param>
  290. /// <param name="i"></param>
  291. private int GetCellWidth (ColumnToRender [] columnsToRender, int i)
  292. {
  293. var current = columnsToRender[i];
  294. var next = i+1 < columnsToRender.Length ? columnsToRender[i+1] : null;
  295. if(next == null) {
  296. // cell can fill to end of the line
  297. return Bounds.Width - current.X;
  298. }
  299. else {
  300. // cell can fill up to next cell start
  301. return next.X - current.X;
  302. }
  303. }
  304. private void RenderHeaderUnderline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  305. {
  306. // Renders a line below the table headers (when visible) like:
  307. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  308. for(int c = 0;c< availableWidth;c++) {
  309. var rune = Driver.HLine;
  310. if (Style.ShowVerticalHeaderLines){
  311. if(c == 0){
  312. rune = Style.ShowVerticalCellLines ? Driver.LeftTee : Driver.LLCorner;
  313. }
  314. // if the next column is the start of a header
  315. else if(columnsToRender.Any(r=>r.X == c+1)){
  316. /*TODO: is ┼ symbol in Driver?*/
  317. rune = Style.ShowVerticalCellLines ? '┼' :Driver.BottomTee;
  318. }
  319. else if(c == availableWidth -1){
  320. rune = Style.ShowVerticalCellLines ? Driver.RightTee : Driver.LRCorner;
  321. }
  322. }
  323. AddRuneAt(Driver,c,row,rune);
  324. }
  325. }
  326. private void RenderRow(int row, int rowToRender, ColumnToRender[] columnsToRender)
  327. {
  328. //render start of line
  329. if(style.ShowVerticalCellLines)
  330. AddRune(0,row,Driver.VLine);
  331. // Render cells for each visible header for the current row
  332. for(int i=0;i< columnsToRender.Length ;i++) {
  333. var current = columnsToRender[i];
  334. var availableWidthForCell = GetCellWidth(columnsToRender,i);
  335. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  336. // move to start of cell (in line with header positions)
  337. Move (current.X, row);
  338. // Set color scheme based on whether the current cell is the selected one
  339. bool isSelectedCell = rowToRender == SelectedRow && current.Column.Ordinal == SelectedColumn;
  340. Driver.SetAttribute (isSelectedCell ? ColorScheme.HotFocus : ColorScheme.Normal);
  341. var val = Table.Rows [rowToRender][current.Column];
  342. // Render the (possibly truncated) cell value
  343. var representation = GetRepresentation(val,colStyle);
  344. Driver.AddStr (TruncateOrPad(val,representation,availableWidthForCell,colStyle));
  345. // Reset color scheme to normal and render the vertical line (or space) at the end of the cell
  346. Driver.SetAttribute (ColorScheme.Normal);
  347. RenderSeparator(current.X-1,row,false);
  348. }
  349. //render end of line
  350. if(style.ShowVerticalCellLines)
  351. AddRune(Bounds.Width-1,row,Driver.VLine);
  352. }
  353. private void RenderSeparator(int col, int row,bool isHeader)
  354. {
  355. if(col<0)
  356. return;
  357. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  358. Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
  359. AddRune(col,row,symbol);
  360. }
  361. void AddRuneAt (ConsoleDriver d,int col, int row, Rune ch)
  362. {
  363. Move (col, row);
  364. d.AddRune (ch);
  365. }
  366. /// <summary>
  367. /// 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)
  368. /// </summary>
  369. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  370. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  371. /// <param name="availableHorizontalSpace"></param>
  372. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  373. /// <returns></returns>
  374. private string TruncateOrPad (object originalCellValue,string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  375. {
  376. if (string.IsNullOrEmpty (representation))
  377. return representation;
  378. // if value is not wide enough
  379. if(representation.Length < availableHorizontalSpace) {
  380. // pad it out with spaces to the given alignment
  381. int toPad = availableHorizontalSpace - (representation.Length+1 /*leave 1 space for cell boundary*/);
  382. switch(colStyle?.GetAlignment(originalCellValue) ?? TextAlignment.Left) {
  383. case TextAlignment.Left :
  384. return representation + new string(' ',toPad);
  385. case TextAlignment.Right :
  386. return new string(' ',toPad) + representation;
  387. // TODO: With single line cells, centered and justified are the same right?
  388. case TextAlignment.Centered :
  389. case TextAlignment.Justified :
  390. return
  391. new string(' ',(int)Math.Floor(toPad/2.0)) + // round down
  392. representation +
  393. new string(' ',(int)Math.Ceiling(toPad/2.0)) ; // round up
  394. }
  395. }
  396. // value is too wide
  397. return representation.Substring (0, availableHorizontalSpace);
  398. }
  399. /// <inheritdoc/>
  400. public override bool ProcessKey (KeyEvent keyEvent)
  401. {
  402. switch (keyEvent.Key) {
  403. case Key.CursorLeft:
  404. SelectedColumn--;
  405. Update ();
  406. break;
  407. case Key.CursorRight:
  408. SelectedColumn++;
  409. Update ();
  410. break;
  411. case Key.CursorDown:
  412. SelectedRow++;
  413. Update ();
  414. break;
  415. case Key.CursorUp:
  416. SelectedRow--;
  417. Update ();
  418. break;
  419. case Key.PageUp:
  420. SelectedRow -= Frame.Height;
  421. Update ();
  422. break;
  423. case Key.PageDown:
  424. SelectedRow += Frame.Height;
  425. Update ();
  426. break;
  427. case Key.Home | Key.CtrlMask:
  428. SelectedRow = 0;
  429. SelectedColumn = 0;
  430. Update ();
  431. break;
  432. case Key.Home:
  433. SelectedColumn = 0;
  434. Update ();
  435. break;
  436. case Key.End | Key.CtrlMask:
  437. //jump to end of table
  438. SelectedRow = Table == null ? 0 : Table.Rows.Count - 1;
  439. SelectedColumn = Table == null ? 0 : Table.Columns.Count - 1;
  440. Update ();
  441. break;
  442. case Key.End:
  443. //jump to end of row
  444. SelectedColumn = Table == null ? 0 : Table.Columns.Count - 1;
  445. Update ();
  446. break;
  447. default:
  448. // Not a keystroke we care about
  449. return false;
  450. }
  451. PositionCursor ();
  452. return true;
  453. }
  454. ///<inheritdoc/>
  455. public override bool MouseEvent (MouseEvent me)
  456. {
  457. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  458. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp)
  459. return false;
  460. if (!HasFocus && CanFocus) {
  461. SetFocus ();
  462. }
  463. if (Table == null) {
  464. return false;
  465. }
  466. if (me.Flags == MouseFlags.WheeledDown) {
  467. RowOffset++;
  468. EnsureValidScrollOffsets();
  469. SetNeedsDisplay();
  470. return true;
  471. } else if (me.Flags == MouseFlags.WheeledUp) {
  472. RowOffset--;
  473. EnsureValidScrollOffsets();
  474. SetNeedsDisplay();
  475. return true;
  476. }
  477. if(me.Flags == MouseFlags.Button1Clicked) {
  478. var viewPort = CalculateViewport(Bounds);
  479. var headerHeight = GetHeaderHeight();
  480. var col = viewPort.LastOrDefault(c=>c.X < me.OfX);
  481. var rowIdx = RowOffset - headerHeight + me.OfY;
  482. if(col != null && rowIdx >= 0) {
  483. SelectedRow = rowIdx;
  484. SelectedColumn = col.Column.Ordinal;
  485. Update();
  486. }
  487. }
  488. return false;
  489. }
  490. /// <summary>
  491. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  492. /// </summary>
  493. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  494. public void Update()
  495. {
  496. if(Table == null) {
  497. SetNeedsDisplay ();
  498. return;
  499. }
  500. EnsureValidScrollOffsets();
  501. EnsureValidSelection();
  502. EnsureSelectedCellIsVisible();
  503. SetNeedsDisplay ();
  504. }
  505. /// <summary>
  506. /// 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.
  507. /// </summary>
  508. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  509. public void EnsureValidScrollOffsets ()
  510. {
  511. if(Table == null){
  512. return;
  513. }
  514. ColumnOffset = Math.Max(Math.Min(ColumnOffset,Table.Columns.Count -1),0);
  515. RowOffset = Math.Max(Math.Min(RowOffset,Table.Rows.Count -1),0);
  516. }
  517. /// <summary>
  518. /// 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.
  519. /// </summary>
  520. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  521. public void EnsureValidSelection ()
  522. {
  523. if(Table == null){
  524. return;
  525. }
  526. SelectedColumn = Math.Max(Math.Min(SelectedColumn,Table.Columns.Count -1),0);
  527. SelectedRow = Math.Max(Math.Min(SelectedRow,Table.Rows.Count -1),0);
  528. }
  529. /// <summary>
  530. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  531. /// </summary>
  532. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  533. public void EnsureSelectedCellIsVisible ()
  534. {
  535. if(Table == null || Table.Columns.Count <= 0){
  536. return;
  537. }
  538. var columnsToRender = CalculateViewport (Bounds).ToArray();
  539. var headerHeight = GetHeaderHeight();
  540. //if we have scrolled too far to the left
  541. if (SelectedColumn < columnsToRender.Min (r => r.Column.Ordinal)) {
  542. ColumnOffset = SelectedColumn;
  543. }
  544. //if we have scrolled too far to the right
  545. if (SelectedColumn > columnsToRender.Max (r=> r.Column.Ordinal)) {
  546. ColumnOffset = SelectedColumn;
  547. }
  548. //if we have scrolled too far down
  549. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  550. RowOffset = SelectedRow;
  551. }
  552. //if we have scrolled too far up
  553. if (SelectedRow < RowOffset) {
  554. RowOffset = SelectedRow;
  555. }
  556. }
  557. /// <summary>
  558. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  559. /// </summary>
  560. /// <param name="bounds"></param>
  561. /// <param name="padding"></param>
  562. /// <returns></returns>
  563. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  564. {
  565. if(Table == null)
  566. yield break;
  567. int usedSpace = 0;
  568. //if horizontal space is required at the start of the line (before the first header)
  569. if(Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  570. usedSpace+=1;
  571. int availableHorizontalSpace = bounds.Width;
  572. int rowsToRender = bounds.Height;
  573. // reserved for the headers row
  574. if(ShouldRenderHeaders())
  575. rowsToRender -= GetHeaderHeight();
  576. bool first = true;
  577. foreach (var col in Table.Columns.Cast<DataColumn>().Skip (ColumnOffset)) {
  578. int startingIdxForCurrentHeader = usedSpace;
  579. var colStyle = Style.GetColumnStyleIfAny(col);
  580. // is there enough space for this column (and it's data)?
  581. usedSpace += CalculateMaxCellWidth (col, rowsToRender,colStyle) + padding;
  582. // no (don't render it) unless its the only column we are render (that must be one massively wide column!)
  583. if (!first && usedSpace > availableHorizontalSpace)
  584. yield break;
  585. // there is space
  586. yield return new ColumnToRender(col, startingIdxForCurrentHeader);
  587. first=false;
  588. }
  589. }
  590. private bool ShouldRenderHeaders()
  591. {
  592. if(Table == null || Table.Columns.Count == 0)
  593. return false;
  594. return Style.AlwaysShowHeaders || rowOffset == 0;
  595. }
  596. /// <summary>
  597. /// 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"/>
  598. /// </summary>
  599. /// <param name="col"></param>
  600. /// <param name="rowsToRender"></param>
  601. /// <param name="colStyle"></param>
  602. /// <returns></returns>
  603. private int CalculateMaxCellWidth(DataColumn col, int rowsToRender,ColumnStyle colStyle)
  604. {
  605. int spaceRequired = col.ColumnName.Length;
  606. // if table has no rows
  607. if(RowOffset < 0)
  608. return spaceRequired;
  609. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows.Count; i++) {
  610. //expand required space if cell is bigger than the last biggest cell or header
  611. spaceRequired = Math.Max (spaceRequired, GetRepresentation(Table.Rows [i][col],colStyle).Length);
  612. }
  613. // Don't require more space than the style allows
  614. if(colStyle != null){
  615. // enforce maximum cell width based on style
  616. if(spaceRequired > colStyle.MaxWidth) {
  617. spaceRequired = colStyle.MaxWidth;
  618. }
  619. // enforce minimum cell width based on style
  620. if(spaceRequired < colStyle.MinWidth) {
  621. spaceRequired = colStyle.MinWidth;
  622. }
  623. }
  624. // enforce maximum cell width based on global table style
  625. if(spaceRequired > MaxCellWidth)
  626. spaceRequired = MaxCellWidth;
  627. return spaceRequired;
  628. }
  629. /// <summary>
  630. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  631. /// </summary>
  632. /// <param name="value"></param>
  633. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  634. /// <returns></returns>
  635. private string GetRepresentation(object value,ColumnStyle colStyle)
  636. {
  637. if (value == null || value == DBNull.Value) {
  638. return NullSymbol;
  639. }
  640. return colStyle != null ? colStyle.GetRepresentation(value): value.ToString();
  641. }
  642. }
  643. /// <summary>
  644. /// Describes a desire to render a column at a given horizontal position in the UI
  645. /// </summary>
  646. internal class ColumnToRender {
  647. /// <summary>
  648. /// The column to render
  649. /// </summary>
  650. public DataColumn Column {get;set;}
  651. /// <summary>
  652. /// The horizontal position to begin rendering the column at
  653. /// </summary>
  654. public int X{get;set;}
  655. public ColumnToRender (DataColumn col, int x)
  656. {
  657. Column = col;
  658. X = x;
  659. }
  660. }
  661. }