TableView.cs 23 KB

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