TableView.cs 43 KB

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