TableView.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  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. /// View for tabular data based on a <see cref="DataTable"/>.
  9. ///
  10. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/tableview.html">See TableView Deep Dive for more information</a>.
  11. /// </summary>
  12. public class TableView : View {
  13. /// <summary>
  14. /// Defines the event arguments for <see cref="TableView.CellActivated"/> event
  15. /// </summary>
  16. public class CellActivatedEventArgs : EventArgs {
  17. /// <summary>
  18. /// The current table to which the new indexes refer. May be null e.g. if selection change is the result of clearing the table from the view
  19. /// </summary>
  20. /// <value></value>
  21. public DataTable Table { get; }
  22. /// <summary>
  23. /// The column index of the <see cref="Table"/> cell that is being activated
  24. /// </summary>
  25. /// <value></value>
  26. public int Col { get; }
  27. /// <summary>
  28. /// The row index of the <see cref="Table"/> cell that is being activated
  29. /// </summary>
  30. /// <value></value>
  31. public int Row { get; }
  32. /// <summary>
  33. /// Creates a new instance of arguments describing a cell being activated in <see cref="TableView"/>
  34. /// </summary>
  35. /// <param name="t"></param>
  36. /// <param name="col"></param>
  37. /// <param name="row"></param>
  38. public CellActivatedEventArgs (DataTable t, int col, int row)
  39. {
  40. Table = t;
  41. Col = col;
  42. Row = row;
  43. }
  44. }
  45. private int columnOffset;
  46. private int rowOffset;
  47. private int selectedRow;
  48. private int selectedColumn;
  49. private DataTable table;
  50. private TableStyle style = new TableStyle();
  51. /// <summary>
  52. /// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
  53. /// </summary>
  54. public const int DefaultMaxCellWidth = 100;
  55. /// <summary>
  56. /// The data table to render in the view. Setting this property automatically updates and redraws the control.
  57. /// </summary>
  58. public DataTable Table { get => table; set {table = value; Update(); } }
  59. /// <summary>
  60. /// Contains options for changing how the table is rendered
  61. /// </summary>
  62. public TableStyle Style { get => style; set {style = value; Update(); } }
  63. /// <summary>
  64. /// True to select the entire row at once. False to select individual cells. Defaults to false
  65. /// </summary>
  66. public bool FullRowSelect {get;set;}
  67. /// <summary>
  68. /// True to allow regions to be selected
  69. /// </summary>
  70. /// <value></value>
  71. public bool MultiSelect {get;set;} = true;
  72. /// <summary>
  73. /// When <see cref="MultiSelect"/> is enabled this property contain all rectangles of selected cells. Rectangles describe column/rows selected in <see cref="Table"/> (not screen coordinates)
  74. /// </summary>
  75. /// <returns></returns>
  76. public Stack<TableSelection> MultiSelectedRegions {get;} = new Stack<TableSelection>();
  77. /// <summary>
  78. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering the view.
  79. /// </summary>
  80. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  81. public int ColumnOffset {
  82. get => columnOffset;
  83. //try to prevent this being set to an out of bounds column
  84. set => columnOffset = Table == null ? 0 :Math.Max (0,Math.Min (Table.Columns.Count - 1, value));
  85. }
  86. /// <summary>
  87. /// 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.
  88. /// </summary>
  89. public int RowOffset {
  90. get => rowOffset;
  91. set => rowOffset = Table == null ? 0 : Math.Max (0,Math.Min (Table.Rows.Count - 1, value));
  92. }
  93. /// <summary>
  94. /// The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected
  95. /// </summary>
  96. public int SelectedColumn {
  97. get => selectedColumn;
  98. set {
  99. var oldValue = selectedColumn;
  100. //try to prevent this being set to an out of bounds column
  101. selectedColumn = Table == null ? 0 : Math.Min (Table.Columns.Count - 1, Math.Max (0, value));
  102. if(oldValue != selectedColumn)
  103. OnSelectedCellChanged(new SelectedCellChangedEventArgs(Table,oldValue,SelectedColumn,SelectedRow,SelectedRow));
  104. }
  105. }
  106. /// <summary>
  107. /// The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected
  108. /// </summary>
  109. public int SelectedRow {
  110. get => selectedRow;
  111. set {
  112. var oldValue = selectedRow;
  113. selectedRow = Table == null ? 0 : Math.Min (Table.Rows.Count - 1, Math.Max (0, value));
  114. if(oldValue != selectedRow)
  115. OnSelectedCellChanged(new SelectedCellChangedEventArgs(Table,SelectedColumn,SelectedColumn,oldValue,selectedRow));
  116. }
  117. }
  118. /// <summary>
  119. /// The maximum number of characters to render in any given column. This prevents one long column from pushing out all the others
  120. /// </summary>
  121. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  122. /// <summary>
  123. /// The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/>
  124. /// </summary>
  125. public string NullSymbol { get; set; } = "-";
  126. /// <summary>
  127. /// The symbol to add after each cell value and header value to visually seperate values (if not using vertical gridlines)
  128. /// </summary>
  129. public char SeparatorSymbol { get; set; } = ' ';
  130. /// <summary>
  131. /// This event is raised when the selected cell in the table changes.
  132. /// </summary>
  133. public event Action<SelectedCellChangedEventArgs> SelectedCellChanged;
  134. /// <summary>
  135. /// This event is raised when a cell is activated e.g. by double clicking or pressing <see cref="CellActivationKey"/>
  136. /// </summary>
  137. public event Action<CellActivatedEventArgs> CellActivated;
  138. /// <summary>
  139. /// The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.
  140. /// </summary>
  141. public Key CellActivationKey {get;set;} = Key.Enter;
  142. /// <summary>
  143. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  144. /// </summary>
  145. /// <param name="table">The table to display in the control</param>
  146. public TableView (DataTable table) : this ()
  147. {
  148. this.Table = table;
  149. }
  150. /// <summary>
  151. /// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
  152. /// </summary>
  153. public TableView () : base ()
  154. {
  155. CanFocus = true;
  156. }
  157. ///<inheritdoc/>
  158. public override void Redraw (Rect bounds)
  159. {
  160. Move (0, 0);
  161. var frame = Frame;
  162. // What columns to render at what X offset in viewport
  163. var columnsToRender = CalculateViewport(bounds).ToArray();
  164. Driver.SetAttribute (ColorScheme.Normal);
  165. //invalidate current row (prevents scrolling around leaving old characters in the frame
  166. Driver.AddStr (new string (' ', bounds.Width));
  167. int line = 0;
  168. if(ShouldRenderHeaders()){
  169. // Render something like:
  170. /*
  171. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  172. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  173. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  174. */
  175. if(Style.ShowHorizontalHeaderOverline){
  176. RenderHeaderOverline(line,bounds.Width,columnsToRender);
  177. line++;
  178. }
  179. RenderHeaderMidline(line,columnsToRender);
  180. line++;
  181. if(Style.ShowHorizontalHeaderUnderline){
  182. RenderHeaderUnderline(line,bounds.Width,columnsToRender);
  183. line++;
  184. }
  185. }
  186. int headerLinesConsumed = line;
  187. //render the cells
  188. for (; line < frame.Height; line++) {
  189. ClearLine(line,bounds.Width);
  190. //work out what Row to render
  191. var rowToRender = RowOffset + (line - headerLinesConsumed);
  192. //if we have run off the end of the table
  193. if ( Table == null || rowToRender >= Table.Rows.Count || rowToRender < 0)
  194. continue;
  195. RenderRow(line,rowToRender,columnsToRender);
  196. }
  197. }
  198. /// <summary>
  199. /// Clears a line of the console by filling it with spaces
  200. /// </summary>
  201. /// <param name="row"></param>
  202. /// <param name="width"></param>
  203. private void ClearLine(int row, int width)
  204. {
  205. Move (0, row);
  206. Driver.SetAttribute (ColorScheme.Normal);
  207. Driver.AddStr (new string (' ', width));
  208. }
  209. /// <summary>
  210. /// Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.
  211. /// </summary>
  212. /// <returns></returns>
  213. private int GetHeaderHeightIfAny()
  214. {
  215. return ShouldRenderHeaders()? GetHeaderHeight():0;
  216. }
  217. /// <summary>
  218. /// Returns the amount of vertical space required to display the header
  219. /// </summary>
  220. /// <returns></returns>
  221. private int GetHeaderHeight()
  222. {
  223. int heightRequired = 1;
  224. if(Style.ShowHorizontalHeaderOverline)
  225. heightRequired++;
  226. if(Style.ShowHorizontalHeaderUnderline)
  227. heightRequired++;
  228. return heightRequired;
  229. }
  230. private void RenderHeaderOverline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  231. {
  232. // Renders a line above table headers (when visible) like:
  233. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  234. for(int c = 0;c< availableWidth;c++) {
  235. var rune = Driver.HLine;
  236. if (Style.ShowVerticalHeaderLines){
  237. if(c == 0){
  238. rune = Driver.ULCorner;
  239. }
  240. // if the next column is the start of a header
  241. else if(columnsToRender.Any(r=>r.X == c+1)){
  242. rune = Driver.TopTee;
  243. }
  244. else if(c == availableWidth -1){
  245. rune = Driver.URCorner;
  246. }
  247. // if the next console column is the lastcolumns end
  248. else if ( Style.ExpandLastColumn == false &&
  249. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width-1 == c)) {
  250. rune = Driver.TopTee;
  251. }
  252. }
  253. AddRuneAt(Driver,c,row,rune);
  254. }
  255. }
  256. private void RenderHeaderMidline(int row, ColumnToRender[] columnsToRender)
  257. {
  258. // Renders something like:
  259. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  260. ClearLine(row,Bounds.Width);
  261. //render start of line
  262. if(style.ShowVerticalHeaderLines)
  263. AddRune(0,row,Driver.VLine);
  264. for(int i =0 ; i<columnsToRender.Length;i++) {
  265. var current = columnsToRender[i];
  266. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  267. var colName = current.Column.ColumnName;
  268. RenderSeparator(current.X-1,row,true);
  269. Move (current.X, row);
  270. Driver.AddStr(TruncateOrPad(colName,colName,current.Width ,colStyle));
  271. if (Style.ExpandLastColumn == false && current.IsVeryLast) {
  272. RenderSeparator (current.X + current.Width-1, row, true);
  273. }
  274. }
  275. //render end of line
  276. if (style.ShowVerticalHeaderLines)
  277. AddRune(Bounds.Width-1,row,Driver.VLine);
  278. }
  279. private void RenderHeaderUnderline(int row,int availableWidth, ColumnToRender[] columnsToRender)
  280. {
  281. // Renders a line below the table headers (when visible) like:
  282. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  283. for(int c = 0;c< availableWidth;c++) {
  284. var rune = Driver.HLine;
  285. if (Style.ShowVerticalHeaderLines){
  286. if(c == 0){
  287. rune = Style.ShowVerticalCellLines ? Driver.LeftTee : Driver.LLCorner;
  288. }
  289. // if the next column is the start of a header
  290. else if(columnsToRender.Any(r=>r.X == c+1)){
  291. /*TODO: is ┼ symbol in Driver?*/
  292. rune = Style.ShowVerticalCellLines ? '┼' :Driver.BottomTee;
  293. }
  294. else if(c == availableWidth -1){
  295. rune = Style.ShowVerticalCellLines ? Driver.RightTee : Driver.LRCorner;
  296. }
  297. // if the next console column is the lastcolumns end
  298. else if (Style.ExpandLastColumn == false &&
  299. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width-1 == c)) {
  300. rune = Style.ShowVerticalCellLines ? '┼' : Driver.BottomTee;
  301. }
  302. }
  303. AddRuneAt(Driver,c,row,rune);
  304. }
  305. }
  306. private void RenderRow(int row, int rowToRender, ColumnToRender[] columnsToRender)
  307. {
  308. //render start of line
  309. if(style.ShowVerticalCellLines)
  310. AddRune(0,row,Driver.VLine);
  311. //start by clearing the entire line
  312. Move (0,row);
  313. Driver.SetAttribute (FullRowSelect && IsSelected(0,rowToRender) ? ColorScheme.HotFocus : ColorScheme.Normal);
  314. Driver.AddStr (new string(' ',Bounds.Width));
  315. // Render cells for each visible header for the current row
  316. for(int i=0;i< columnsToRender.Length ;i++) {
  317. var current = columnsToRender[i];
  318. var colStyle = Style.GetColumnStyleIfAny(current.Column);
  319. // move to start of cell (in line with header positions)
  320. Move (current.X, row);
  321. // Set color scheme based on whether the current cell is the selected one
  322. bool isSelectedCell = IsSelected(current.Column.Ordinal,rowToRender);
  323. Driver.SetAttribute (isSelectedCell ? ColorScheme.HotFocus : ColorScheme.Normal);
  324. var val = Table.Rows [rowToRender][current.Column];
  325. // Render the (possibly truncated) cell value
  326. var representation = GetRepresentation(val,colStyle);
  327. Driver.AddStr (TruncateOrPad(val,representation, current.Width, colStyle));
  328. // If not in full row select mode always, reset color scheme to normal and render the vertical line (or space) at the end of the cell
  329. if(!FullRowSelect)
  330. Driver.SetAttribute (ColorScheme.Normal);
  331. RenderSeparator(current.X-1,row,false);
  332. if (Style.ExpandLastColumn == false && current.IsVeryLast) {
  333. RenderSeparator (current.X + current.Width-1, row, false);
  334. }
  335. }
  336. //render end of line
  337. if(style.ShowVerticalCellLines)
  338. AddRune(Bounds.Width-1,row,Driver.VLine);
  339. }
  340. private void RenderSeparator(int col, int row,bool isHeader)
  341. {
  342. if(col<0)
  343. return;
  344. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  345. Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
  346. AddRune(col,row,symbol);
  347. }
  348. void AddRuneAt (ConsoleDriver d,int col, int row, Rune ch)
  349. {
  350. Move (col, row);
  351. d.AddRune (ch);
  352. }
  353. /// <summary>
  354. /// 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)
  355. /// </summary>
  356. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  357. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  358. /// <param name="availableHorizontalSpace"></param>
  359. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  360. /// <returns></returns>
  361. private string TruncateOrPad (object originalCellValue,string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  362. {
  363. if (string.IsNullOrEmpty (representation))
  364. return representation;
  365. // if value is not wide enough
  366. if(representation.Sum(c=>Rune.ColumnWidth(c)) < availableHorizontalSpace) {
  367. // pad it out with spaces to the given alignment
  368. int toPad = availableHorizontalSpace - (representation.Sum(c=>Rune.ColumnWidth(c)) +1 /*leave 1 space for cell boundary*/);
  369. switch(colStyle?.GetAlignment(originalCellValue) ?? TextAlignment.Left) {
  370. case TextAlignment.Left :
  371. return representation + new string(' ',toPad);
  372. case TextAlignment.Right :
  373. return new string(' ',toPad) + representation;
  374. // TODO: With single line cells, centered and justified are the same right?
  375. case TextAlignment.Centered :
  376. case TextAlignment.Justified :
  377. return
  378. new string(' ',(int)Math.Floor(toPad/2.0)) + // round down
  379. representation +
  380. new string(' ',(int)Math.Ceiling(toPad/2.0)) ; // round up
  381. }
  382. }
  383. // value is too wide
  384. return new string(representation.TakeWhile(c=>(availableHorizontalSpace-= Rune.ColumnWidth(c))>0).ToArray());
  385. }
  386. /// <inheritdoc/>
  387. public override bool ProcessKey (KeyEvent keyEvent)
  388. {
  389. if(Table == null){
  390. PositionCursor ();
  391. return false;
  392. }
  393. if(keyEvent.Key == CellActivationKey && Table != null) {
  394. OnCellActivated(new CellActivatedEventArgs(Table,SelectedColumn,SelectedRow));
  395. return true;
  396. }
  397. switch (keyEvent.Key) {
  398. case Key.CursorLeft:
  399. case Key.CursorLeft | Key.ShiftMask:
  400. ChangeSelectionByOffset(-1,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  401. Update ();
  402. break;
  403. case Key.CursorRight:
  404. case Key.CursorRight | Key.ShiftMask:
  405. ChangeSelectionByOffset(1,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  406. Update ();
  407. break;
  408. case Key.CursorDown:
  409. case Key.CursorDown | Key.ShiftMask:
  410. ChangeSelectionByOffset(0,1,keyEvent.Key.HasFlag(Key.ShiftMask));
  411. Update ();
  412. break;
  413. case Key.CursorUp:
  414. case Key.CursorUp | Key.ShiftMask:
  415. ChangeSelectionByOffset(0,-1,keyEvent.Key.HasFlag(Key.ShiftMask));
  416. Update ();
  417. break;
  418. case Key.PageUp:
  419. case Key.PageUp | Key.ShiftMask:
  420. ChangeSelectionByOffset(0,-(Bounds.Height - GetHeaderHeightIfAny()),keyEvent.Key.HasFlag(Key.ShiftMask));
  421. Update ();
  422. break;
  423. case Key.PageDown:
  424. case Key.PageDown | Key.ShiftMask:
  425. ChangeSelectionByOffset(0,Bounds.Height - GetHeaderHeightIfAny(),keyEvent.Key.HasFlag(Key.ShiftMask));
  426. Update ();
  427. break;
  428. case Key.Home | Key.CtrlMask:
  429. case Key.Home | Key.CtrlMask | Key.ShiftMask:
  430. // jump to table origin
  431. SetSelection(0,0,keyEvent.Key.HasFlag(Key.ShiftMask));
  432. Update ();
  433. break;
  434. case Key.Home:
  435. case Key.Home | Key.ShiftMask:
  436. // jump to start of line
  437. SetSelection(0,SelectedRow,keyEvent.Key.HasFlag(Key.ShiftMask));
  438. Update ();
  439. break;
  440. case Key.End | Key.CtrlMask:
  441. case Key.End | Key.CtrlMask | Key.ShiftMask:
  442. // jump to end of table
  443. SetSelection(Table.Columns.Count - 1, Table.Rows.Count - 1, keyEvent.Key.HasFlag(Key.ShiftMask));
  444. Update ();
  445. break;
  446. case Key.A | Key.CtrlMask:
  447. SelectAll();
  448. Update ();
  449. break;
  450. case Key.End:
  451. case Key.End | Key.ShiftMask:
  452. //jump to end of row
  453. SetSelection(Table.Columns.Count - 1,SelectedRow, keyEvent.Key.HasFlag(Key.ShiftMask));
  454. Update ();
  455. break;
  456. default:
  457. // Not a keystroke we care about
  458. return false;
  459. }
  460. PositionCursor ();
  461. return true;
  462. }
  463. /// <summary>
  464. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  465. /// </summary>
  466. /// <param name="col"></param>
  467. /// <param name="row"></param>
  468. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  469. public void SetSelection (int col, int row, bool extendExistingSelection)
  470. {
  471. if(!MultiSelect || !extendExistingSelection)
  472. MultiSelectedRegions.Clear();
  473. if(extendExistingSelection)
  474. {
  475. // If we are extending current selection but there isn't one
  476. if(MultiSelectedRegions.Count == 0)
  477. {
  478. // Create a new region between the old active cell and the new cell
  479. var rect = CreateTableSelection(SelectedColumn,SelectedRow,col,row);
  480. MultiSelectedRegions.Push(rect);
  481. }
  482. else
  483. {
  484. // Extend the current head selection to include the new cell
  485. var head = MultiSelectedRegions.Pop();
  486. var newRect = CreateTableSelection(head.Origin.X,head.Origin.Y,col,row);
  487. MultiSelectedRegions.Push(newRect);
  488. }
  489. }
  490. SelectedColumn = col;
  491. SelectedRow = row;
  492. }
  493. /// <summary>
  494. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  495. /// </summary>
  496. /// <param name="offsetX">Offset in number of columns</param>
  497. /// <param name="offsetY">Offset in number of rows</param>
  498. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  499. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  500. {
  501. SetSelection(SelectedColumn + offsetX, SelectedRow + offsetY,extendExistingSelection);
  502. }
  503. /// <summary>
  504. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old selection regions)
  505. /// </summary>
  506. public void SelectAll()
  507. {
  508. if(Table == null || !MultiSelect || Table.Rows.Count == 0)
  509. return;
  510. MultiSelectedRegions.Clear();
  511. // Create a single region over entire table, set the origin of the selection to the active cell so that a followup spread selection e.g. shift-right behaves properly
  512. MultiSelectedRegions.Push(new TableSelection(new Point(SelectedColumn,SelectedRow), new Rect(0,0,Table.Columns.Count,table.Rows.Count)));
  513. Update();
  514. }
  515. /// <summary>
  516. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the selected cell
  517. /// </summary>
  518. /// <returns></returns>
  519. public IEnumerable<Point> GetAllSelectedCells()
  520. {
  521. if(Table == null || Table.Rows.Count == 0)
  522. yield break;
  523. EnsureValidSelection();
  524. // If there are one or more rectangular selections
  525. if(MultiSelect && MultiSelectedRegions.Any()){
  526. // Quiz any cells for whether they are selected. For performance we only need to check those between the top left and lower right vertex of selection regions
  527. var yMin = MultiSelectedRegions.Min(r=>r.Rect.Top);
  528. var yMax = MultiSelectedRegions.Max(r=>r.Rect.Bottom);
  529. var xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min(r=>r.Rect.Left);
  530. var xMax = FullRowSelect ? Table.Columns.Count : MultiSelectedRegions.Max(r=>r.Rect.Right);
  531. for(int y = yMin ; y < yMax ; y++)
  532. {
  533. for(int x = xMin ; x < xMax ; x++)
  534. {
  535. if(IsSelected(x,y)){
  536. yield return new Point(x,y);
  537. }
  538. }
  539. }
  540. }
  541. else{
  542. // if there are no region selections then it is just the active cell
  543. // if we are selecting the full row
  544. if(FullRowSelect)
  545. {
  546. // all cells in active row are selected
  547. for(int x =0;x<Table.Columns.Count;x++){
  548. yield return new Point(x,SelectedRow);
  549. }
  550. }
  551. else
  552. {
  553. // Not full row select and no multi selections
  554. yield return new Point(SelectedColumn,SelectedRow);
  555. }
  556. }
  557. }
  558. /// <summary>
  559. /// Returns a new rectangle between the two points with positive width/height regardless of relative positioning of the points. pt1 is always considered the <see cref="TableSelection.Origin"/> point
  560. /// </summary>
  561. /// <param name="pt1X">Origin point for the selection in X</param>
  562. /// <param name="pt1Y">Origin point for the selection in Y</param>
  563. /// <param name="pt2X">End point for the selection in X</param>
  564. /// <param name="pt2Y">End point for the selection in Y</param>
  565. /// <returns></returns>
  566. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y)
  567. {
  568. var top = Math.Min(pt1Y,pt2Y);
  569. var bot = Math.Max(pt1Y,pt2Y);
  570. var left = Math.Min(pt1X,pt2X);
  571. var right = Math.Max(pt1X,pt2X);
  572. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  573. return new TableSelection(new Point(pt1X,pt1Y),new Rect(left,top,right-left + 1,bot-top + 1));
  574. }
  575. /// <summary>
  576. /// Returns true if the given cell is selected either because it is the active cell or part of a multi cell selection (e.g. <see cref="FullRowSelect"/>)
  577. /// </summary>
  578. /// <param name="col"></param>
  579. /// <param name="row"></param>
  580. /// <returns></returns>
  581. public bool IsSelected(int col, int row)
  582. {
  583. // Cell is also selected if in any multi selection region
  584. if(MultiSelect && MultiSelectedRegions.Any(r=>r.Rect.Contains(col,row)))
  585. return true;
  586. // Cell is also selected if Y axis appears in any region (when FullRowSelect is enabled)
  587. if(FullRowSelect && MultiSelect && MultiSelectedRegions.Any(r=>r.Rect.Bottom> row && r.Rect.Top <= row))
  588. return true;
  589. return row == SelectedRow &&
  590. (col == SelectedColumn || FullRowSelect);
  591. }
  592. /// <summary>
  593. /// Positions the cursor in the area of the screen in which the start of the active cell is rendered. Calls base implementation if active cell is not visible due to scrolling or table is loaded etc
  594. /// </summary>
  595. public override void PositionCursor()
  596. {
  597. if(Table == null) {
  598. base.PositionCursor();
  599. return;
  600. }
  601. var screenPoint = CellToScreen(SelectedColumn,SelectedRow);
  602. if(screenPoint != null)
  603. Move(screenPoint.Value.X,screenPoint.Value.Y);
  604. }
  605. ///<inheritdoc/>
  606. public override bool MouseEvent (MouseEvent me)
  607. {
  608. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  609. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  610. me.Flags != MouseFlags.WheeledLeft && me.Flags != MouseFlags.WheeledRight)
  611. return false;
  612. if (!HasFocus && CanFocus) {
  613. SetFocus ();
  614. }
  615. if (Table == null) {
  616. return false;
  617. }
  618. // Scroll wheel flags
  619. switch(me.Flags)
  620. {
  621. case MouseFlags.WheeledDown:
  622. RowOffset++;
  623. EnsureValidScrollOffsets();
  624. SetNeedsDisplay();
  625. return true;
  626. case MouseFlags.WheeledUp:
  627. RowOffset--;
  628. EnsureValidScrollOffsets();
  629. SetNeedsDisplay();
  630. return true;
  631. case MouseFlags.WheeledRight:
  632. ColumnOffset++;
  633. EnsureValidScrollOffsets();
  634. SetNeedsDisplay();
  635. return true;
  636. case MouseFlags.WheeledLeft:
  637. ColumnOffset--;
  638. EnsureValidScrollOffsets();
  639. SetNeedsDisplay();
  640. return true;
  641. }
  642. if(me.Flags.HasFlag(MouseFlags.Button1Clicked)) {
  643. var hit = ScreenToCell(me.X,me.Y);
  644. if(hit != null) {
  645. SetSelection(hit.Value.X,hit.Value.Y,me.Flags.HasFlag(MouseFlags.ButtonShift));
  646. Update();
  647. }
  648. }
  649. // Double clicking a cell activates
  650. if(me.Flags == MouseFlags.Button1DoubleClicked) {
  651. var hit = ScreenToCell(me.X,me.Y);
  652. if(hit!= null) {
  653. OnCellActivated(new CellActivatedEventArgs(Table,hit.Value.X,hit.Value.Y));
  654. }
  655. }
  656. return false;
  657. }
  658. /// <summary>
  659. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point on the screen (relative to the control client area). Returns null if the point is in the header, no table is loaded or outside the control bounds
  660. /// </summary>
  661. /// <param name="clientX">X offset from the top left of the control</param>
  662. /// <param name="clientY">Y offset from the top left of the control</param>
  663. /// <returns></returns>
  664. public Point? ScreenToCell (int clientX, int clientY)
  665. {
  666. if(Table == null)
  667. return null;
  668. var viewPort = CalculateViewport(Bounds);
  669. var headerHeight = GetHeaderHeightIfAny();
  670. var col = viewPort.LastOrDefault(c=>c.X <= clientX);
  671. // Click is on the header section of rendered UI
  672. if(clientY < headerHeight)
  673. return null;
  674. var rowIdx = RowOffset - headerHeight + clientY;
  675. if(col != null && rowIdx >= 0) {
  676. return new Point(col.Column.Ordinal,rowIdx);
  677. }
  678. return null;
  679. }
  680. /// <summary>
  681. /// Returns the screen position (relative to the control client area) that the given cell is rendered or null if it is outside the current scroll area or no table is loaded
  682. /// </summary>
  683. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for, use <see cref="DataColumn.Ordinal"/></param>
  684. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  685. /// <returns></returns>
  686. public Point? CellToScreen (int tableColumn, int tableRow)
  687. {
  688. if(Table == null)
  689. return null;
  690. var viewPort = CalculateViewport(Bounds);
  691. var headerHeight = GetHeaderHeightIfAny();
  692. var colHit = viewPort.FirstOrDefault(c=>c.Column.Ordinal == tableColumn);
  693. // current column is outside the scroll area
  694. if(colHit == null)
  695. return null;
  696. // the cell is too far up above the current scroll area
  697. if(RowOffset > tableRow)
  698. return null;
  699. // the cell is way down below the scroll area and off the screen
  700. if(tableRow > RowOffset + (Bounds.Height - headerHeight))
  701. return null;
  702. return new Point(colHit.X,tableRow + headerHeight - RowOffset);
  703. }
  704. /// <summary>
  705. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  706. /// </summary>
  707. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  708. public void Update()
  709. {
  710. if(Table == null) {
  711. SetNeedsDisplay ();
  712. return;
  713. }
  714. EnsureValidScrollOffsets();
  715. EnsureValidSelection();
  716. EnsureSelectedCellIsVisible();
  717. SetNeedsDisplay ();
  718. }
  719. /// <summary>
  720. /// Updates <see cref="ColumnOffset"/> and <see cref="RowOffset"/> where they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  721. /// </summary>
  722. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  723. public void EnsureValidScrollOffsets ()
  724. {
  725. if(Table == null){
  726. return;
  727. }
  728. ColumnOffset = Math.Max(Math.Min(ColumnOffset,Table.Columns.Count -1),0);
  729. RowOffset = Math.Max(Math.Min(RowOffset,Table.Rows.Count -1),0);
  730. }
  731. /// <summary>
  732. /// Updates <see cref="SelectedColumn"/>, <see cref="SelectedRow"/> and <see cref="MultiSelectedRegions"/> where they are outside the bounds of the table (by adjusting them to the nearest existing cell). Has no effect if <see cref="Table"/> has not been set.
  733. /// </summary>
  734. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  735. public void EnsureValidSelection()
  736. {
  737. if(Table == null){
  738. // Table doesn't exist, we should probably clear those selections
  739. MultiSelectedRegions.Clear();
  740. return;
  741. }
  742. SelectedColumn = Math.Max(Math.Min(SelectedColumn,Table.Columns.Count -1),0);
  743. SelectedRow = Math.Max(Math.Min(SelectedRow,Table.Rows.Count -1),0);
  744. var oldRegions = MultiSelectedRegions.ToArray().Reverse();
  745. MultiSelectedRegions.Clear();
  746. // evaluate
  747. foreach(var region in oldRegions)
  748. {
  749. // ignore regions entirely below current table state
  750. if(region.Rect.Top >= Table.Rows.Count)
  751. continue;
  752. // ignore regions entirely too far right of table columns
  753. if(region.Rect.Left >= Table.Columns.Count)
  754. continue;
  755. // ensure region's origin exists
  756. region.Origin = new Point(
  757. Math.Max(Math.Min(region.Origin.X,Table.Columns.Count -1),0),
  758. Math.Max(Math.Min(region.Origin.Y,Table.Rows.Count -1),0));
  759. // ensure regions do not go over edge of table bounds
  760. region.Rect = Rect.FromLTRB(region.Rect.Left,
  761. region.Rect.Top,
  762. Math.Max(Math.Min(region.Rect.Right, Table.Columns.Count ),0),
  763. Math.Max(Math.Min(region.Rect.Bottom,Table.Rows.Count),0)
  764. );
  765. MultiSelectedRegions.Push(region);
  766. }
  767. }
  768. /// <summary>
  769. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  770. /// </summary>
  771. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  772. public void EnsureSelectedCellIsVisible ()
  773. {
  774. if(Table == null || Table.Columns.Count <= 0){
  775. return;
  776. }
  777. var columnsToRender = CalculateViewport (Bounds).ToArray();
  778. var headerHeight = GetHeaderHeightIfAny();
  779. //if we have scrolled too far to the left
  780. if (SelectedColumn < columnsToRender.Min (r => r.Column.Ordinal)) {
  781. ColumnOffset = SelectedColumn;
  782. }
  783. //if we have scrolled too far to the right
  784. if (SelectedColumn > columnsToRender.Max (r=> r.Column.Ordinal)) {
  785. ColumnOffset = SelectedColumn;
  786. }
  787. //if we have scrolled too far down
  788. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  789. RowOffset = SelectedRow;
  790. }
  791. //if we have scrolled too far up
  792. if (SelectedRow < RowOffset) {
  793. RowOffset = SelectedRow;
  794. }
  795. }
  796. /// <summary>
  797. /// Invokes the <see cref="SelectedCellChanged"/> event
  798. /// </summary>
  799. protected virtual void OnSelectedCellChanged(SelectedCellChangedEventArgs args)
  800. {
  801. SelectedCellChanged?.Invoke(args);
  802. }
  803. /// <summary>
  804. /// Invokes the <see cref="CellActivated"/> event
  805. /// </summary>
  806. /// <param name="args"></param>
  807. protected virtual void OnCellActivated (CellActivatedEventArgs args)
  808. {
  809. CellActivated?.Invoke(args);
  810. }
  811. /// <summary>
  812. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  813. /// </summary>
  814. /// <param name="bounds"></param>
  815. /// <param name="padding"></param>
  816. /// <returns></returns>
  817. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  818. {
  819. if(Table == null)
  820. yield break;
  821. int usedSpace = 0;
  822. //if horizontal space is required at the start of the line (before the first header)
  823. if(Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  824. usedSpace+=1;
  825. int availableHorizontalSpace = bounds.Width;
  826. int rowsToRender = bounds.Height;
  827. // reserved for the headers row
  828. if(ShouldRenderHeaders())
  829. rowsToRender -= GetHeaderHeight();
  830. bool first = true;
  831. var lastColumn = Table.Columns.Cast<DataColumn> ().Last ();
  832. foreach (var col in Table.Columns.Cast<DataColumn>().Skip (ColumnOffset)) {
  833. int startingIdxForCurrentHeader = usedSpace;
  834. var colStyle = Style.GetColumnStyleIfAny(col);
  835. int colWidth;
  836. // is there enough space for this column (and it's data)?
  837. usedSpace += colWidth = CalculateMaxCellWidth (col, rowsToRender,colStyle) + padding;
  838. // no (don't render it) unless its the only column we are render (that must be one massively wide column!)
  839. if (!first && usedSpace > availableHorizontalSpace)
  840. yield break;
  841. // there is space
  842. yield return new ColumnToRender(col, startingIdxForCurrentHeader,
  843. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  844. Math.Min(availableHorizontalSpace,colWidth),
  845. lastColumn == col);
  846. first=false;
  847. }
  848. }
  849. private bool ShouldRenderHeaders()
  850. {
  851. if(Table == null || Table.Columns.Count == 0)
  852. return false;
  853. return Style.AlwaysShowHeaders || rowOffset == 0;
  854. }
  855. /// <summary>
  856. /// 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"/>
  857. /// </summary>
  858. /// <param name="col"></param>
  859. /// <param name="rowsToRender"></param>
  860. /// <param name="colStyle"></param>
  861. /// <returns></returns>
  862. private int CalculateMaxCellWidth(DataColumn col, int rowsToRender,ColumnStyle colStyle)
  863. {
  864. int spaceRequired = col.ColumnName.Sum(c=>Rune.ColumnWidth(c));
  865. // if table has no rows
  866. if(RowOffset < 0)
  867. return spaceRequired;
  868. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows.Count; i++) {
  869. //expand required space if cell is bigger than the last biggest cell or header
  870. spaceRequired = Math.Max (spaceRequired, GetRepresentation(Table.Rows [i][col],colStyle).Sum(c=>Rune.ColumnWidth(c)));
  871. }
  872. // Don't require more space than the style allows
  873. if(colStyle != null){
  874. // enforce maximum cell width based on style
  875. if(spaceRequired > colStyle.MaxWidth) {
  876. spaceRequired = colStyle.MaxWidth;
  877. }
  878. // enforce minimum cell width based on style
  879. if(spaceRequired < colStyle.MinWidth) {
  880. spaceRequired = colStyle.MinWidth;
  881. }
  882. }
  883. // enforce maximum cell width based on global table style
  884. if(spaceRequired > MaxCellWidth)
  885. spaceRequired = MaxCellWidth;
  886. return spaceRequired;
  887. }
  888. /// <summary>
  889. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  890. /// </summary>
  891. /// <param name="value"></param>
  892. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  893. /// <returns></returns>
  894. private string GetRepresentation(object value,ColumnStyle colStyle)
  895. {
  896. if (value == null || value == DBNull.Value) {
  897. return NullSymbol;
  898. }
  899. return colStyle != null ? colStyle.GetRepresentation(value): value.ToString();
  900. }
  901. #region Nested Types
  902. /// <summary>
  903. /// Describes how to render a given column in a <see cref="TableView"/> including <see cref="Alignment"/>
  904. /// and textual representation of cells (e.g. date formats)
  905. ///
  906. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/tableview.html">See TableView Deep Dive for more information</a>.
  907. /// </summary>
  908. public class ColumnStyle {
  909. /// <summary>
  910. /// Defines the default alignment for all values rendered in this column. For custom alignment based on cell contents use <see cref="AlignmentGetter"/>.
  911. /// </summary>
  912. public TextAlignment Alignment { get; set; }
  913. /// <summary>
  914. /// Defines a delegate for returning custom alignment per cell based on cell values. When specified this will override <see cref="Alignment"/>
  915. /// </summary>
  916. public Func<object, TextAlignment> AlignmentGetter;
  917. /// <summary>
  918. /// 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"/>
  919. /// </summary>
  920. public Func<object, string> RepresentationGetter;
  921. /// <summary>
  922. /// Defines the format for values e.g. "yyyy-MM-dd" for dates
  923. /// </summary>
  924. public string Format { get; set; }
  925. /// <summary>
  926. /// 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"/>
  927. /// </summary>
  928. public int MaxWidth { get; set; } = TableView.DefaultMaxCellWidth;
  929. /// <summary>
  930. /// 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"/>
  931. /// </summary>
  932. public int MinWidth { get; set; }
  933. /// <summary>
  934. /// Returns the alignment for the cell based on <paramref name="cellValue"/> and <see cref="AlignmentGetter"/>/<see cref="Alignment"/>
  935. /// </summary>
  936. /// <param name="cellValue"></param>
  937. /// <returns></returns>
  938. public TextAlignment GetAlignment (object cellValue)
  939. {
  940. if (AlignmentGetter != null)
  941. return AlignmentGetter (cellValue);
  942. return Alignment;
  943. }
  944. /// <summary>
  945. /// 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"/>
  946. /// </summary>
  947. /// <param name="value"></param>
  948. /// <returns></returns>
  949. public string GetRepresentation (object value)
  950. {
  951. if (!string.IsNullOrWhiteSpace (Format)) {
  952. if (value is IFormattable f)
  953. return f.ToString (Format, null);
  954. }
  955. if (RepresentationGetter != null)
  956. return RepresentationGetter (value);
  957. return value?.ToString ();
  958. }
  959. }
  960. /// <summary>
  961. /// Defines rendering options that affect how the table is displayed.
  962. ///
  963. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/tableview.html">See TableView Deep Dive for more information</a>.
  964. /// </summary>
  965. public class TableStyle {
  966. /// <summary>
  967. /// When scrolling down always lock the column headers in place as the first row of the table
  968. /// </summary>
  969. public bool AlwaysShowHeaders { get; set; } = false;
  970. /// <summary>
  971. /// True to render a solid line above the headers
  972. /// </summary>
  973. public bool ShowHorizontalHeaderOverline { get; set; } = true;
  974. /// <summary>
  975. /// True to render a solid line under the headers
  976. /// </summary>
  977. public bool ShowHorizontalHeaderUnderline { get; set; } = true;
  978. /// <summary>
  979. /// True to render a solid line vertical line between cells
  980. /// </summary>
  981. public bool ShowVerticalCellLines { get; set; } = true;
  982. /// <summary>
  983. /// True to render a solid line vertical line between headers
  984. /// </summary>
  985. public bool ShowVerticalHeaderLines { get; set; } = true;
  986. /// <summary>
  987. /// Collection of columns for which you want special rendering (e.g. custom column lengths, text alignment etc)
  988. /// </summary>
  989. public Dictionary<DataColumn, ColumnStyle> ColumnStyles { get; set; } = new Dictionary<DataColumn, ColumnStyle> ();
  990. /// <summary>
  991. /// Determines rendering when the last column in the table is visible but it's
  992. /// content or <see cref="ColumnStyle.MaxWidth"/> is less than the remaining
  993. /// space in the control. True (the default) will expand the column to fill
  994. /// the remaining bounds of the control. False will draw a column ending line
  995. /// and leave a blank column that cannot be selected in the remaining space.
  996. /// </summary>
  997. /// <value></value>
  998. public bool ExpandLastColumn {get;set;} = true;
  999. /// <summary>
  1000. /// Returns the entry from <see cref="ColumnStyles"/> for the given <paramref name="col"/> or null if no custom styling is defined for it
  1001. /// </summary>
  1002. /// <param name="col"></param>
  1003. /// <returns></returns>
  1004. public ColumnStyle GetColumnStyleIfAny (DataColumn col)
  1005. {
  1006. return ColumnStyles.TryGetValue (col, out ColumnStyle result) ? result : null;
  1007. }
  1008. /// <summary>
  1009. /// Returns an existing <see cref="ColumnStyle"/> for the given <paramref name="col"/> or creates a new one with default options
  1010. /// </summary>
  1011. /// <param name="col"></param>
  1012. /// <returns></returns>
  1013. public ColumnStyle GetOrCreateColumnStyle (DataColumn col)
  1014. {
  1015. if (!ColumnStyles.ContainsKey (col))
  1016. ColumnStyles.Add (col, new ColumnStyle ());
  1017. return ColumnStyles [col];
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// Describes a desire to render a column at a given horizontal position in the UI
  1022. /// </summary>
  1023. internal class ColumnToRender {
  1024. /// <summary>
  1025. /// The column to render
  1026. /// </summary>
  1027. public DataColumn Column { get; set; }
  1028. /// <summary>
  1029. /// The horizontal position to begin rendering the column at
  1030. /// </summary>
  1031. public int X { get; set; }
  1032. /// <summary>
  1033. /// The width that the column should occupy as calculated by <see cref="CalculateViewport(Rect, int)"/>. Note that this includes
  1034. /// space for padding i.e. the separator between columns.
  1035. /// </summary>
  1036. public int Width { get; }
  1037. /// <summary>
  1038. /// True if this column is the very last column in the <see cref="Table"/> (not just the last visible column)
  1039. /// </summary>
  1040. public bool IsVeryLast { get; }
  1041. public ColumnToRender (DataColumn col, int x, int width, bool isVeryLast)
  1042. {
  1043. Column = col;
  1044. X = x;
  1045. Width = width;
  1046. IsVeryLast = isVeryLast;
  1047. }
  1048. }
  1049. /// <summary>
  1050. /// Defines the event arguments for <see cref="TableView.SelectedCellChanged"/>
  1051. /// </summary>
  1052. public class SelectedCellChangedEventArgs : EventArgs {
  1053. /// <summary>
  1054. /// The current table to which the new indexes refer. May be null e.g. if selection change is the result of clearing the table from the view
  1055. /// </summary>
  1056. /// <value></value>
  1057. public DataTable Table { get; }
  1058. /// <summary>
  1059. /// The previous selected column index. May be invalid e.g. when the selection has been changed as a result of replacing the existing Table with a smaller one
  1060. /// </summary>
  1061. /// <value></value>
  1062. public int OldCol { get; }
  1063. /// <summary>
  1064. /// The newly selected column index.
  1065. /// </summary>
  1066. /// <value></value>
  1067. public int NewCol { get; }
  1068. /// <summary>
  1069. /// The previous selected row index. May be invalid e.g. when the selection has been changed as a result of deleting rows from the table
  1070. /// </summary>
  1071. /// <value></value>
  1072. public int OldRow { get; }
  1073. /// <summary>
  1074. /// The newly selected row index.
  1075. /// </summary>
  1076. /// <value></value>
  1077. public int NewRow { get; }
  1078. /// <summary>
  1079. /// Creates a new instance of arguments describing a change in selected cell in a <see cref="TableView"/>
  1080. /// </summary>
  1081. /// <param name="t"></param>
  1082. /// <param name="oldCol"></param>
  1083. /// <param name="newCol"></param>
  1084. /// <param name="oldRow"></param>
  1085. /// <param name="newRow"></param>
  1086. public SelectedCellChangedEventArgs (DataTable t, int oldCol, int newCol, int oldRow, int newRow)
  1087. {
  1088. Table = t;
  1089. OldCol = oldCol;
  1090. NewCol = newCol;
  1091. OldRow = oldRow;
  1092. NewRow = newRow;
  1093. }
  1094. }
  1095. /// <summary>
  1096. /// Describes a selected region of the table
  1097. /// </summary>
  1098. public class TableSelection {
  1099. /// <summary>
  1100. /// Corner of the <see cref="Rect"/> where selection began
  1101. /// </summary>
  1102. /// <value></value>
  1103. public Point Origin { get; set; }
  1104. /// <summary>
  1105. /// Area selected
  1106. /// </summary>
  1107. /// <value></value>
  1108. public Rect Rect { get; set; }
  1109. /// <summary>
  1110. /// Creates a new selected area starting at the origin corner and covering the provided rectangular area
  1111. /// </summary>
  1112. /// <param name="origin"></param>
  1113. /// <param name="rect"></param>
  1114. public TableSelection (Point origin, Rect rect)
  1115. {
  1116. Origin = origin;
  1117. Rect = rect;
  1118. }
  1119. }
  1120. #endregion
  1121. }
  1122. }