TableView.cs 26 KB

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