TableView.cs 23 KB

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