TableView.cs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. using System.Text;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Linq;
  7. namespace Terminal.Gui {
  8. /// <summary>
  9. /// Delegate for providing color to <see cref="TableView"/> cells based on the value being rendered
  10. /// </summary>
  11. /// <param name="args">Contains information about the cell for which color is needed</param>
  12. /// <returns></returns>
  13. public delegate ColorScheme CellColorGetterDelegate (CellColorGetterArgs args);
  14. /// <summary>
  15. /// Delegate for providing color for a whole row of a <see cref="TableView"/>
  16. /// </summary>
  17. /// <param name="args"></param>
  18. /// <returns></returns>
  19. public delegate ColorScheme RowColorGetterDelegate (RowColorGetterArgs args);
  20. /// <summary>
  21. /// View for tabular data based on a <see cref="ITableSource"/>.
  22. ///
  23. /// <a href="../docs/tableview.md">See TableView Deep Dive for more information</a>.
  24. /// </summary>
  25. public class TableView : View {
  26. private int columnOffset;
  27. private int rowOffset;
  28. private int selectedRow;
  29. private int selectedColumn;
  30. private ITableSource table;
  31. private TableStyle style = new TableStyle ();
  32. // TODO: Update to use Key instead of KeyCode
  33. private KeyCode cellActivationKey = KeyCode.Enter;
  34. Point? scrollLeftPoint;
  35. Point? scrollRightPoint;
  36. /// <summary>
  37. /// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
  38. /// </summary>
  39. public const int DefaultMaxCellWidth = 100;
  40. /// <summary>
  41. /// The default minimum cell width for <see cref="ColumnStyle.MinAcceptableWidth"/>
  42. /// </summary>
  43. public const int DefaultMinAcceptableWidth = 100;
  44. /// <summary>
  45. /// The data table to render in the view. Setting this property automatically updates and redraws the control.
  46. /// </summary>
  47. public ITableSource Table {
  48. get => table;
  49. set {
  50. table = value;
  51. Update ();
  52. }
  53. }
  54. /// <summary>
  55. /// Contains options for changing how the table is rendered
  56. /// </summary>
  57. public TableStyle Style { get => style; set { style = value; Update (); } }
  58. /// <summary>
  59. /// True to select the entire row at once. False to select individual cells. Defaults to false
  60. /// </summary>
  61. public bool FullRowSelect { get; set; }
  62. /// <summary>
  63. /// True to allow regions to be selected
  64. /// </summary>
  65. /// <value></value>
  66. public bool MultiSelect { get; set; } = true;
  67. /// <summary>
  68. /// 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)
  69. /// </summary>
  70. /// <returns></returns>
  71. public Stack<TableSelection> MultiSelectedRegions { get; private set; } = new Stack<TableSelection> ();
  72. /// <summary>
  73. /// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering the view.
  74. /// </summary>
  75. /// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
  76. public int ColumnOffset {
  77. get => columnOffset;
  78. //try to prevent this being set to an out of bounds column
  79. set => columnOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Columns - 1, value));
  80. }
  81. /// <summary>
  82. /// 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.
  83. /// </summary>
  84. public int RowOffset {
  85. get => rowOffset;
  86. set => rowOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Rows - 1, value));
  87. }
  88. /// <summary>
  89. /// The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected
  90. /// </summary>
  91. public int SelectedColumn {
  92. get => selectedColumn;
  93. set {
  94. var oldValue = selectedColumn;
  95. //try to prevent this being set to an out of bounds column
  96. selectedColumn = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Columns - 1, Math.Max (0, value));
  97. if (oldValue != selectedColumn)
  98. OnSelectedCellChanged (new SelectedCellChangedEventArgs (Table, oldValue, SelectedColumn, SelectedRow, SelectedRow));
  99. }
  100. }
  101. /// <summary>
  102. /// The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected
  103. /// </summary>
  104. public int SelectedRow {
  105. get => selectedRow;
  106. set {
  107. var oldValue = selectedRow;
  108. selectedRow = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Rows - 1, Math.Max (0, value));
  109. if (oldValue != selectedRow)
  110. OnSelectedCellChanged (new SelectedCellChangedEventArgs (Table, SelectedColumn, SelectedColumn, oldValue, selectedRow));
  111. }
  112. }
  113. /// <summary>
  114. /// The minimum number of characters to render in any given column.
  115. /// </summary>
  116. public int MinCellWidth { get; set; }
  117. /// <summary>
  118. /// The maximum number of characters to render in any given column. This prevents one long column from pushing out all the others
  119. /// </summary>
  120. public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
  121. /// <summary>
  122. /// The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/>
  123. /// </summary>
  124. public string NullSymbol { get; set; } = "-";
  125. /// <summary>
  126. /// The symbol to add after each cell value and header value to visually seperate values (if not using vertical gridlines)
  127. /// </summary>
  128. public char SeparatorSymbol { get; set; } = ' ';
  129. /// <summary>
  130. /// This event is raised when the selected cell in the table changes.
  131. /// </summary>
  132. public event EventHandler<SelectedCellChangedEventArgs> SelectedCellChanged;
  133. /// <summary>
  134. /// This event is raised when a cell is activated e.g. by double clicking or pressing <see cref="CellActivationKey"/>
  135. /// </summary>
  136. public event EventHandler<CellActivatedEventArgs> CellActivated;
  137. /// <summary>
  138. /// This event is raised when a cell is toggled (see <see cref="Command.ToggleChecked"/>
  139. /// </summary>
  140. public event EventHandler<CellToggledEventArgs> CellToggled;
  141. // TODO: Update to use Key instead of KeyCode
  142. /// <summary>
  143. /// The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.
  144. /// </summary>
  145. public KeyCode CellActivationKey {
  146. get => cellActivationKey;
  147. set {
  148. if (cellActivationKey != value) {
  149. KeyBindings.Replace (cellActivationKey, value);
  150. // of API user is mixing and matching old and new methods of keybinding then they may have lost
  151. // the old binding (e.g. with ClearKeybindings) so KeyBindings.Replace alone will fail
  152. KeyBindings.Add (value, Command.Accept);
  153. cellActivationKey = value;
  154. }
  155. }
  156. }
  157. /// <summary>
  158. /// Navigator for cycling the selected item in the table by typing.
  159. /// Set to null to disable this feature.
  160. /// </summary>
  161. public CollectionNavigatorBase CollectionNavigator { get; set; }
  162. /// <summary>
  163. /// Initializes a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
  164. /// </summary>
  165. /// <param name="table">The table to display in the control</param>
  166. public TableView (ITableSource table) : this ()
  167. {
  168. this.Table = table;
  169. }
  170. /// <summary>
  171. /// Initializes a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
  172. /// </summary>
  173. public TableView () : base ()
  174. {
  175. CanFocus = true;
  176. this.CollectionNavigator = new TableCollectionNavigator (this);
  177. // Things this view knows how to do
  178. AddCommand (Command.Right, () => { ChangeSelectionByOffset (1, 0, false); return true; });
  179. AddCommand (Command.Left, () => { ChangeSelectionByOffset (-1, 0, false); return true; });
  180. AddCommand (Command.LineUp, () => { ChangeSelectionByOffset (0, -1, false); return true; });
  181. AddCommand (Command.LineDown, () => { ChangeSelectionByOffset (0, 1, false); return true; });
  182. AddCommand (Command.PageUp, () => { PageUp (false); return true; });
  183. AddCommand (Command.PageDown, () => { PageDown (false); return true; });
  184. AddCommand (Command.LeftHome, () => { ChangeSelectionToStartOfRow (false); return true; });
  185. AddCommand (Command.RightEnd, () => { ChangeSelectionToEndOfRow (false); return true; });
  186. AddCommand (Command.TopHome, () => { ChangeSelectionToStartOfTable (false); return true; });
  187. AddCommand (Command.BottomEnd, () => { ChangeSelectionToEndOfTable (false); return true; });
  188. AddCommand (Command.RightExtend, () => { ChangeSelectionByOffset (1, 0, true); return true; });
  189. AddCommand (Command.LeftExtend, () => { ChangeSelectionByOffset (-1, 0, true); return true; });
  190. AddCommand (Command.LineUpExtend, () => { ChangeSelectionByOffset (0, -1, true); return true; });
  191. AddCommand (Command.LineDownExtend, () => { ChangeSelectionByOffset (0, 1, true); return true; });
  192. AddCommand (Command.PageUpExtend, () => { PageUp (true); return true; });
  193. AddCommand (Command.PageDownExtend, () => { PageDown (true); return true; });
  194. AddCommand (Command.LeftHomeExtend, () => { ChangeSelectionToStartOfRow (true); return true; });
  195. AddCommand (Command.RightEndExtend, () => { ChangeSelectionToEndOfRow (true); return true; });
  196. AddCommand (Command.TopHomeExtend, () => { ChangeSelectionToStartOfTable (true); return true; });
  197. AddCommand (Command.BottomEndExtend, () => { ChangeSelectionToEndOfTable (true); return true; });
  198. AddCommand (Command.SelectAll, () => { SelectAll (); return true; });
  199. AddCommand (Command.Accept, () => { OnCellActivated (new CellActivatedEventArgs (Table, SelectedColumn, SelectedRow)); return true; });
  200. AddCommand (Command.ToggleChecked, () => { ToggleCurrentCellSelection (); return true; });
  201. // Default keybindings for this view
  202. KeyBindings.Add (KeyCode.CursorLeft, Command.Left);
  203. KeyBindings.Add (KeyCode.CursorRight, Command.Right);
  204. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  205. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  206. KeyBindings.Add (KeyCode.PageUp, Command.PageUp);
  207. KeyBindings.Add (KeyCode.PageDown, Command.PageDown);
  208. KeyBindings.Add (KeyCode.Home, Command.LeftHome);
  209. KeyBindings.Add (KeyCode.End, Command.RightEnd);
  210. KeyBindings.Add (KeyCode.Home | KeyCode.CtrlMask, Command.TopHome);
  211. KeyBindings.Add (KeyCode.End | KeyCode.CtrlMask, Command.BottomEnd);
  212. KeyBindings.Add (KeyCode.CursorLeft | KeyCode.ShiftMask, Command.LeftExtend);
  213. KeyBindings.Add (KeyCode.CursorRight | KeyCode.ShiftMask, Command.RightExtend);
  214. KeyBindings.Add (KeyCode.CursorUp | KeyCode.ShiftMask, Command.LineUpExtend);
  215. KeyBindings.Add (KeyCode.CursorDown | KeyCode.ShiftMask, Command.LineDownExtend);
  216. KeyBindings.Add (KeyCode.PageUp | KeyCode.ShiftMask, Command.PageUpExtend);
  217. KeyBindings.Add (KeyCode.PageDown | KeyCode.ShiftMask, Command.PageDownExtend);
  218. KeyBindings.Add (KeyCode.Home | KeyCode.ShiftMask, Command.LeftHomeExtend);
  219. KeyBindings.Add (KeyCode.End | KeyCode.ShiftMask, Command.RightEndExtend);
  220. KeyBindings.Add (KeyCode.Home | KeyCode.CtrlMask | KeyCode.ShiftMask, Command.TopHomeExtend);
  221. KeyBindings.Add (KeyCode.End | KeyCode.CtrlMask | KeyCode.ShiftMask, Command.BottomEndExtend);
  222. KeyBindings.Add (KeyCode.A | KeyCode.CtrlMask, Command.SelectAll);
  223. KeyBindings.Add (CellActivationKey, Command.Accept);
  224. }
  225. ///<inheritdoc/>
  226. public override void OnDrawContent (Rect contentArea)
  227. {
  228. base.OnDrawContent (contentArea);
  229. Move (0, 0);
  230. scrollRightPoint = null;
  231. scrollLeftPoint = null;
  232. // What columns to render at what X offset in viewport
  233. var columnsToRender = CalculateViewport (Bounds).ToArray ();
  234. Driver.SetAttribute (GetNormalColor ());
  235. //invalidate current row (prevents scrolling around leaving old characters in the frame
  236. Driver.AddStr (new string (' ', Bounds.Width));
  237. int line = 0;
  238. if (ShouldRenderHeaders ()) {
  239. // Render something like:
  240. /*
  241. ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  242. │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  243. └────────────────────┴──────────┴───────────┴──────────────┴─────────┘
  244. */
  245. if (Style.ShowHorizontalHeaderOverline) {
  246. RenderHeaderOverline (line, Bounds.Width, columnsToRender);
  247. line++;
  248. }
  249. if (Style.ShowHeaders) {
  250. RenderHeaderMidline (line, columnsToRender);
  251. line++;
  252. }
  253. if (Style.ShowHorizontalHeaderUnderline) {
  254. RenderHeaderUnderline (line, Bounds.Width, columnsToRender);
  255. line++;
  256. }
  257. }
  258. int headerLinesConsumed = line;
  259. //render the cells
  260. for (; line < Bounds.Height; line++) {
  261. ClearLine (line, Bounds.Width);
  262. //work out what Row to render
  263. var rowToRender = RowOffset + (line - headerLinesConsumed);
  264. //if we have run off the end of the table
  265. if (TableIsNullOrInvisible () || rowToRender < 0)
  266. continue;
  267. // No more data
  268. if (rowToRender >= Table.Rows) {
  269. if (rowToRender == Table.Rows && Style.ShowHorizontalBottomline) {
  270. RenderBottomLine (line, Bounds.Width, columnsToRender);
  271. }
  272. continue;
  273. }
  274. RenderRow (line, rowToRender, columnsToRender);
  275. }
  276. }
  277. /// <summary>
  278. /// Clears a line of the console by filling it with spaces
  279. /// </summary>
  280. /// <param name="row"></param>
  281. /// <param name="width"></param>
  282. private void ClearLine (int row, int width)
  283. {
  284. Move (0, row);
  285. Driver.SetAttribute (GetNormalColor ());
  286. Driver.AddStr (new string (' ', width));
  287. }
  288. /// <summary>
  289. /// Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.
  290. /// </summary>
  291. /// <returns></returns>
  292. internal int GetHeaderHeightIfAny ()
  293. {
  294. return ShouldRenderHeaders () ? GetHeaderHeight () : 0;
  295. }
  296. /// <summary>
  297. /// Returns the amount of vertical space required to display the header
  298. /// </summary>
  299. /// <returns></returns>
  300. internal int GetHeaderHeight ()
  301. {
  302. int heightRequired = Style.ShowHeaders ? 1 : 0;
  303. if (Style.ShowHorizontalHeaderOverline)
  304. heightRequired++;
  305. if (Style.ShowHorizontalHeaderUnderline)
  306. heightRequired++;
  307. return heightRequired;
  308. }
  309. private void RenderHeaderOverline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  310. {
  311. // Renders a line above table headers (when visible) like:
  312. // ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
  313. for (int c = 0; c < availableWidth; c++) {
  314. var rune = CM.Glyphs.HLine;
  315. if (Style.ShowVerticalHeaderLines) {
  316. if (c == 0) {
  317. rune = CM.Glyphs.ULCorner;
  318. }
  319. // if the next column is the start of a header
  320. else if (columnsToRender.Any (r => r.X == c + 1)) {
  321. rune = CM.Glyphs.TopTee;
  322. } else if (c == availableWidth - 1) {
  323. rune = CM.Glyphs.URCorner;
  324. }
  325. // if the next console column is the lastcolumns end
  326. else if (Style.ExpandLastColumn == false &&
  327. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
  328. rune = CM.Glyphs.TopTee;
  329. }
  330. }
  331. AddRuneAt (Driver, c, row, rune);
  332. }
  333. }
  334. private void RenderHeaderMidline (int row, ColumnToRender [] columnsToRender)
  335. {
  336. // Renders something like:
  337. // │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
  338. ClearLine (row, Bounds.Width);
  339. //render start of line
  340. if (style.ShowVerticalHeaderLines)
  341. AddRune (0, row, CM.Glyphs.VLine);
  342. for (int i = 0; i < columnsToRender.Length; i++) {
  343. var current = columnsToRender [i];
  344. var colStyle = Style.GetColumnStyleIfAny (current.Column);
  345. var colName = table.ColumnNames [current.Column];
  346. RenderSeparator (current.X - 1, row, true);
  347. Move (current.X, row);
  348. Driver.AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
  349. if (Style.ExpandLastColumn == false && current.IsVeryLast) {
  350. RenderSeparator (current.X + current.Width - 1, row, true);
  351. }
  352. }
  353. //render end of line
  354. if (style.ShowVerticalHeaderLines)
  355. AddRune (Bounds.Width - 1, row, CM.Glyphs.VLine);
  356. }
  357. private void RenderHeaderUnderline (int row, int availableWidth, ColumnToRender [] columnsToRender)
  358. {
  359. /*
  360. * First lets work out if we should be rendering scroll indicators
  361. */
  362. // are there are visible columns to the left that have been pushed
  363. // off the screen due to horizontal scrolling?
  364. bool moreColumnsToLeft = ColumnOffset > 0;
  365. // if we moved left would we find a new column (or are they all invisible?)
  366. if (!TryGetNearestVisibleColumn (ColumnOffset - 1, false, false, out _)) {
  367. moreColumnsToLeft = false;
  368. }
  369. // are there visible columns to the right that have not yet been reached?
  370. // lets find out, what is the column index of the last column we are rendering
  371. int lastColumnIdxRendered = ColumnOffset + columnsToRender.Length - 1;
  372. // are there more valid indexes?
  373. bool moreColumnsToRight = lastColumnIdxRendered < Table.Columns;
  374. // if we went right from the last column would we find a new visible column?
  375. if (!TryGetNearestVisibleColumn (lastColumnIdxRendered + 1, true, false, out _)) {
  376. // no we would not
  377. moreColumnsToRight = false;
  378. }
  379. /*
  380. * Now lets draw the line itself
  381. */
  382. // Renders a line below the table headers (when visible) like:
  383. // ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
  384. for (int c = 0; c < availableWidth; c++) {
  385. // Start by assuming we just draw a straight line the
  386. // whole way but update to instead draw a header indicator
  387. // or scroll arrow etc
  388. var rune = CM.Glyphs.HLine;
  389. if (Style.ShowVerticalHeaderLines) {
  390. if (c == 0) {
  391. // for first character render line
  392. rune = Style.ShowVerticalCellLines ? CM.Glyphs.LeftTee : CM.Glyphs.LLCorner;
  393. // unless we have horizontally scrolled along
  394. // in which case render an arrow, to indicate user
  395. // can scroll left
  396. if (Style.ShowHorizontalScrollIndicators && moreColumnsToLeft) {
  397. rune = CM.Glyphs.LeftArrow;
  398. scrollLeftPoint = new Point (c, row);
  399. }
  400. }
  401. // if the next column is the start of a header
  402. else if (columnsToRender.Any (r => r.X == c + 1)) {
  403. /*TODO: is ┼ symbol in Driver?*/
  404. rune = Style.ShowVerticalCellLines ? CM.Glyphs.Cross : CM.Glyphs.BottomTee;
  405. } else if (c == availableWidth - 1) {
  406. // for the last character in the table
  407. rune = Style.ShowVerticalCellLines ? CM.Glyphs.RightTee : CM.Glyphs.LRCorner;
  408. // unless there is more of the table we could horizontally
  409. // scroll along to see. In which case render an arrow,
  410. // to indicate user can scroll right
  411. if (Style.ShowHorizontalScrollIndicators && moreColumnsToRight) {
  412. rune = CM.Glyphs.RightArrow;
  413. scrollRightPoint = new Point (c, row);
  414. }
  415. }
  416. // if the next console column is the lastcolumns end
  417. else if (Style.ExpandLastColumn == false &&
  418. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
  419. rune = Style.ShowVerticalCellLines ? CM.Glyphs.Cross : CM.Glyphs.BottomTee;
  420. }
  421. }
  422. AddRuneAt (Driver, c, row, rune);
  423. }
  424. }
  425. private void RenderBottomLine (int row, int availableWidth, ColumnToRender [] columnsToRender)
  426. {
  427. // Renders a line at the bottom of the table after all the data like:
  428. // └─────────────────────────────────┴──────────┴──────┴──────────┴────────┴────────────────────────────────────────────┘
  429. for (int c = 0; c < availableWidth; c++) {
  430. // Start by assuming we just draw a straight line the
  431. // whole way but update to instead draw BottomTee / Corner etc
  432. var rune = CM.Glyphs.HLine;
  433. if (Style.ShowVerticalCellLines) {
  434. if (c == 0) {
  435. // for first character render line
  436. rune = CM.Glyphs.LLCorner;
  437. } else if (columnsToRender.Any (r => r.X == c + 1)) {
  438. // if the next column is the start of a header
  439. rune = CM.Glyphs.BottomTee;
  440. } else if (c == availableWidth - 1) {
  441. // for the last character in the table
  442. rune = CM.Glyphs.LRCorner;
  443. } else if (Style.ExpandLastColumn == false &&
  444. columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
  445. // if the next console column is the lastcolumns end
  446. rune = CM.Glyphs.BottomTee;
  447. }
  448. }
  449. AddRuneAt (Driver, c, row, rune);
  450. }
  451. }
  452. private void RenderRow (int row, int rowToRender, ColumnToRender [] columnsToRender)
  453. {
  454. var focused = HasFocus;
  455. var rowScheme = (Style.RowColorGetter?.Invoke (
  456. new RowColorGetterArgs (Table, rowToRender))) ?? ColorScheme;
  457. //start by clearing the entire line
  458. Move (0, row);
  459. Attribute color;
  460. if (FullRowSelect && IsSelected (0, rowToRender)) {
  461. color = focused ? rowScheme.Focus : rowScheme.HotNormal;
  462. } else {
  463. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  464. }
  465. Driver.SetAttribute (color);
  466. Driver.AddStr (new string (' ', Bounds.Width));
  467. // Render cells for each visible header for the current row
  468. for (int i = 0; i < columnsToRender.Length; i++) {
  469. var current = columnsToRender [i];
  470. var colStyle = Style.GetColumnStyleIfAny (current.Column);
  471. // move to start of cell (in line with header positions)
  472. Move (current.X, row);
  473. // Set color scheme based on whether the current cell is the selected one
  474. bool isSelectedCell = IsSelected (current.Column, rowToRender);
  475. var val = Table [rowToRender, current.Column];
  476. // Render the (possibly truncated) cell value
  477. var representation = GetRepresentation (val, colStyle);
  478. // to get the colour scheme
  479. var colorSchemeGetter = colStyle?.ColorGetter;
  480. ColorScheme scheme;
  481. if (colorSchemeGetter != null) {
  482. // user has a delegate for defining row color per cell, call it
  483. scheme = colorSchemeGetter (
  484. new CellColorGetterArgs (Table, rowToRender, current.Column, val, representation, rowScheme));
  485. // if users custom color getter returned null, use the row scheme
  486. if (scheme == null) {
  487. scheme = rowScheme;
  488. }
  489. } else {
  490. // There is no custom cell coloring delegate so use the scheme for the row
  491. scheme = rowScheme;
  492. }
  493. Attribute cellColor;
  494. if (isSelectedCell) {
  495. cellColor = focused ? scheme.Focus : scheme.HotNormal;
  496. } else {
  497. cellColor = Enabled ? scheme.Normal : scheme.Disabled;
  498. }
  499. var render = TruncateOrPad (val, representation, current.Width, colStyle);
  500. // While many cells can be selected (see MultiSelectedRegions) only one cell is the primary (drives navigation etc)
  501. bool isPrimaryCell = current.Column == selectedColumn && rowToRender == selectedRow;
  502. RenderCell (cellColor, render, isPrimaryCell);
  503. // Reset color scheme to normal for drawing separators if we drew text with custom scheme
  504. if (scheme != rowScheme) {
  505. if (isSelectedCell) {
  506. color = focused ? rowScheme.Focus : rowScheme.HotNormal;
  507. } else {
  508. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  509. }
  510. Driver.SetAttribute (color);
  511. }
  512. // 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
  513. if (!FullRowSelect)
  514. Driver.SetAttribute (Enabled ? rowScheme.Normal : rowScheme.Disabled);
  515. if (style.AlwaysUseNormalColorForVerticalCellLines && style.ShowVerticalCellLines) {
  516. Driver.SetAttribute (rowScheme.Normal);
  517. }
  518. RenderSeparator (current.X - 1, row, false);
  519. if (Style.ExpandLastColumn == false && current.IsVeryLast) {
  520. RenderSeparator (current.X + current.Width - 1, row, false);
  521. }
  522. }
  523. if (style.ShowVerticalCellLines) {
  524. Driver.SetAttribute (rowScheme.Normal);
  525. //render start and end of line
  526. AddRune (0, row, CM.Glyphs.VLine);
  527. AddRune (Bounds.Width - 1, row, CM.Glyphs.VLine);
  528. }
  529. }
  530. /// <summary>
  531. /// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to
  532. /// with <see cref="ConsoleDriver.AddStr(string)"/>. The driver will already be
  533. /// in the correct place when rendering and you must render the full <paramref name="render"/>
  534. /// or the view will not look right. For simpler provision of color use <see cref="ColumnStyle.ColorGetter"/>
  535. /// For changing the content that is rendered use <see cref="ColumnStyle.RepresentationGetter"/>
  536. /// </summary>
  537. /// <param name="cellColor"></param>
  538. /// <param name="render"></param>
  539. /// <param name="isPrimaryCell"></param>
  540. protected virtual void RenderCell (Attribute cellColor, string render, bool isPrimaryCell)
  541. {
  542. // If the cell is the selected col/row then draw the first rune in inverted colors
  543. // this allows the user to track which cell is the active one during a multi cell
  544. // selection or in full row select mode
  545. if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell) {
  546. if (render.Length > 0) {
  547. // invert the color of the current cell for the first character
  548. Driver.SetAttribute (new Attribute (cellColor.Background, cellColor.Foreground));
  549. Driver.AddRune ((Rune)render [0]);
  550. if (render.Length > 1) {
  551. Driver.SetAttribute (cellColor);
  552. Driver.AddStr (render.Substring (1));
  553. }
  554. }
  555. } else {
  556. Driver.SetAttribute (cellColor);
  557. Driver.AddStr (render);
  558. }
  559. }
  560. private void RenderSeparator (int col, int row, bool isHeader)
  561. {
  562. if (col < 0)
  563. return;
  564. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  565. Rune symbol = renderLines ? CM.Glyphs.VLine : (Rune)SeparatorSymbol;
  566. AddRune (col, row, symbol);
  567. }
  568. void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
  569. {
  570. Move (col, row);
  571. d.AddRune (ch);
  572. }
  573. /// <summary>
  574. /// 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)
  575. /// </summary>
  576. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  577. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  578. /// <param name="availableHorizontalSpace"></param>
  579. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  580. /// <returns></returns>
  581. private string TruncateOrPad (object originalCellValue, string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  582. {
  583. if (string.IsNullOrEmpty (representation))
  584. return new string (' ', availableHorizontalSpace);
  585. // if value is not wide enough
  586. if (representation.EnumerateRunes ().Sum (c => c.GetColumns ()) < availableHorizontalSpace) {
  587. // pad it out with spaces to the given alignment
  588. int toPad = availableHorizontalSpace - (representation.EnumerateRunes ().Sum (c => c.GetColumns ()) + 1 /*leave 1 space for cell boundary*/);
  589. switch (colStyle?.GetAlignment (originalCellValue) ?? TextAlignment.Left) {
  590. case TextAlignment.Left:
  591. return representation + new string (' ', toPad);
  592. case TextAlignment.Right:
  593. return new string (' ', toPad) + representation;
  594. // TODO: With single line cells, centered and justified are the same right?
  595. case TextAlignment.Centered:
  596. case TextAlignment.Justified:
  597. return
  598. new string (' ', (int)Math.Floor (toPad / 2.0)) + // round down
  599. representation +
  600. new string (' ', (int)Math.Ceiling (toPad / 2.0)); // round up
  601. }
  602. }
  603. // value is too wide
  604. return new string (representation.TakeWhile (c => (availableHorizontalSpace -= ((Rune)c).GetColumns ()) > 0).ToArray ());
  605. }
  606. /// <inheritdoc/>
  607. public override bool OnProcessKeyDown (Key keyEvent)
  608. {
  609. if (TableIsNullOrInvisible ()) {
  610. PositionCursor ();
  611. return false;
  612. }
  613. if (CollectionNavigator != null &&
  614. this.HasFocus &&
  615. Table.Rows != 0 &&
  616. Terminal.Gui.CollectionNavigator.IsCompatibleKey (keyEvent) &&
  617. !keyEvent.KeyCode.HasFlag (KeyCode.CtrlMask) &&
  618. !keyEvent.KeyCode.HasFlag (KeyCode.AltMask) &&
  619. Rune.IsLetterOrDigit ((Rune)keyEvent)) {
  620. return CycleToNextTableEntryBeginningWith (keyEvent);
  621. }
  622. return false;
  623. }
  624. private bool CycleToNextTableEntryBeginningWith (Key keyEvent)
  625. {
  626. var row = SelectedRow;
  627. // There is a multi select going on and not just for the current row
  628. if (GetAllSelectedCells ().Any (c => c.Y != row)) {
  629. return false;
  630. }
  631. int match = CollectionNavigator.GetNextMatchingItem (row, (char)keyEvent);
  632. if (match != -1) {
  633. SelectedRow = match;
  634. EnsureValidSelection ();
  635. EnsureSelectedCellIsVisible ();
  636. PositionCursor ();
  637. SetNeedsDisplay ();
  638. return true;
  639. }
  640. return false;
  641. }
  642. /// <summary>
  643. /// 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"/>)
  644. /// </summary>
  645. /// <param name="col"></param>
  646. /// <param name="row"></param>
  647. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  648. public void SetSelection (int col, int row, bool extendExistingSelection)
  649. {
  650. // if we are trying to increase the column index then
  651. // we are moving right otherwise we are moving left
  652. bool lookRight = col > selectedColumn;
  653. col = GetNearestVisibleColumn (col, lookRight, true);
  654. if (!MultiSelect || !extendExistingSelection) {
  655. ClearMultiSelectedRegions (true);
  656. }
  657. if (extendExistingSelection) {
  658. // If we are extending current selection but there isn't one
  659. if (MultiSelectedRegions.Count == 0 || MultiSelectedRegions.All (m => m.IsToggled)) {
  660. // Create a new region between the old active cell and the new cell
  661. var rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  662. MultiSelectedRegions.Push (rect);
  663. } else {
  664. // Extend the current head selection to include the new cell
  665. var head = MultiSelectedRegions.Pop ();
  666. var newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  667. MultiSelectedRegions.Push (newRect);
  668. }
  669. }
  670. SelectedColumn = col;
  671. SelectedRow = row;
  672. }
  673. private void ClearMultiSelectedRegions (bool keepToggledSelections)
  674. {
  675. if (!keepToggledSelections) {
  676. MultiSelectedRegions.Clear ();
  677. return;
  678. }
  679. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  680. MultiSelectedRegions.Clear ();
  681. foreach (var region in oldRegions) {
  682. if (region.IsToggled) {
  683. MultiSelectedRegions.Push (region);
  684. }
  685. }
  686. }
  687. /// <summary>
  688. /// Unions the current selected cell (and/or regions) with the provided cell and makes
  689. /// it the active one.
  690. /// </summary>
  691. /// <param name="col"></param>
  692. /// <param name="row"></param>
  693. private void UnionSelection (int col, int row)
  694. {
  695. if (!MultiSelect || TableIsNullOrInvisible ()) {
  696. return;
  697. }
  698. EnsureValidSelection ();
  699. var oldColumn = SelectedColumn;
  700. var oldRow = SelectedRow;
  701. // move us to the new cell
  702. SelectedColumn = col;
  703. SelectedRow = row;
  704. MultiSelectedRegions.Push (
  705. CreateTableSelection (col, row)
  706. );
  707. // if the old cell was not part of a rectangular select
  708. // or otherwise selected we need to retain it in the selection
  709. if (!IsSelected (oldColumn, oldRow)) {
  710. MultiSelectedRegions.Push (
  711. CreateTableSelection (oldColumn, oldRow)
  712. );
  713. }
  714. }
  715. /// <summary>
  716. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  717. /// </summary>
  718. /// <param name="offsetX">Offset in number of columns</param>
  719. /// <param name="offsetY">Offset in number of rows</param>
  720. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  721. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  722. {
  723. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
  724. Update ();
  725. }
  726. /// <summary>
  727. /// Moves the selection up by one page
  728. /// </summary>
  729. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  730. public void PageUp (bool extend)
  731. {
  732. ChangeSelectionByOffset (0, -(Bounds.Height - GetHeaderHeightIfAny ()), extend);
  733. Update ();
  734. }
  735. /// <summary>
  736. /// Moves the selection down by one page
  737. /// </summary>
  738. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  739. public void PageDown (bool extend)
  740. {
  741. ChangeSelectionByOffset (0, Bounds.Height - GetHeaderHeightIfAny (), extend);
  742. Update ();
  743. }
  744. /// <summary>
  745. /// Moves or extends the selection to the first cell in the table (0,0).
  746. /// If <see cref="FullRowSelect"/> is enabled then selection instead moves
  747. /// to (<see cref="SelectedColumn"/>,0) i.e. no horizontal scrolling.
  748. /// </summary>
  749. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  750. public void ChangeSelectionToStartOfTable (bool extend)
  751. {
  752. SetSelection (FullRowSelect ? SelectedColumn : 0, 0, extend);
  753. Update ();
  754. }
  755. /// <summary>
  756. /// Moves or extends the selection to the final cell in the table (nX,nY).
  757. /// If <see cref="FullRowSelect"/> is enabled then selection instead moves
  758. /// to (<see cref="SelectedColumn"/>,nY) i.e. no horizontal scrolling.
  759. /// </summary>
  760. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  761. public void ChangeSelectionToEndOfTable (bool extend)
  762. {
  763. var finalColumn = Table.Columns - 1;
  764. SetSelection (FullRowSelect ? SelectedColumn : finalColumn, Table.Rows - 1, extend);
  765. Update ();
  766. }
  767. /// <summary>
  768. /// Moves or extends the selection to the last cell in the current row
  769. /// </summary>
  770. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  771. public void ChangeSelectionToEndOfRow (bool extend)
  772. {
  773. SetSelection (Table.Columns - 1, SelectedRow, extend);
  774. Update ();
  775. }
  776. /// <summary>
  777. /// Moves or extends the selection to the first cell in the current row
  778. /// </summary>
  779. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  780. public void ChangeSelectionToStartOfRow (bool extend)
  781. {
  782. SetSelection (0, SelectedRow, extend);
  783. Update ();
  784. }
  785. /// <summary>
  786. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old selection regions)
  787. /// </summary>
  788. public void SelectAll ()
  789. {
  790. if (TableIsNullOrInvisible () || !MultiSelect || Table.Rows == 0)
  791. return;
  792. ClearMultiSelectedRegions (true);
  793. // 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
  794. MultiSelectedRegions.Push (new TableSelection (new Point (SelectedColumn, SelectedRow), new Rect (0, 0, Table.Columns, table.Rows)));
  795. Update ();
  796. }
  797. /// <summary>
  798. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the selected cell
  799. /// </summary>
  800. /// <returns></returns>
  801. public IEnumerable<Point> GetAllSelectedCells ()
  802. {
  803. if (TableIsNullOrInvisible () || Table.Rows == 0) {
  804. return Enumerable.Empty<Point> ();
  805. }
  806. EnsureValidSelection ();
  807. var toReturn = new HashSet<Point> ();
  808. // If there are one or more rectangular selections
  809. if (MultiSelect && MultiSelectedRegions.Any ()) {
  810. // 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
  811. var yMin = MultiSelectedRegions.Min (r => r.Rect.Top);
  812. var yMax = MultiSelectedRegions.Max (r => r.Rect.Bottom);
  813. var xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rect.Left);
  814. var xMax = FullRowSelect ? Table.Columns : MultiSelectedRegions.Max (r => r.Rect.Right);
  815. for (int y = yMin; y < yMax; y++) {
  816. for (int x = xMin; x < xMax; x++) {
  817. if (IsSelected (x, y)) {
  818. toReturn.Add (new Point (x, y));
  819. }
  820. }
  821. }
  822. }
  823. // if there are no region selections then it is just the active cell
  824. // if we are selecting the full row
  825. if (FullRowSelect) {
  826. // all cells in active row are selected
  827. for (int x = 0; x < Table.Columns; x++) {
  828. toReturn.Add (new Point (x, SelectedRow));
  829. }
  830. } else {
  831. // Not full row select and no multi selections
  832. toReturn.Add (new Point (SelectedColumn, SelectedRow));
  833. }
  834. return toReturn;
  835. }
  836. /// <summary>
  837. /// 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
  838. /// </summary>
  839. /// <param name="pt1X">Origin point for the selection in X</param>
  840. /// <param name="pt1Y">Origin point for the selection in Y</param>
  841. /// <param name="pt2X">End point for the selection in X</param>
  842. /// <param name="pt2Y">End point for the selection in Y</param>
  843. /// <param name="toggle">True if selection is result of <see cref="Command.ToggleChecked"/></param>
  844. /// <returns></returns>
  845. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y, bool toggle = false)
  846. {
  847. var top = Math.Max (Math.Min (pt1Y, pt2Y), 0);
  848. var bot = Math.Max (Math.Max (pt1Y, pt2Y), 0);
  849. var left = Math.Max (Math.Min (pt1X, pt2X), 0);
  850. var right = Math.Max (Math.Max (pt1X, pt2X), 0);
  851. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  852. return new TableSelection (new Point (pt1X, pt1Y), new Rect (left, top, right - left + 1, bot - top + 1)) {
  853. IsToggled = toggle
  854. };
  855. }
  856. private void ToggleCurrentCellSelection ()
  857. {
  858. var e = new CellToggledEventArgs (Table, selectedColumn, selectedRow);
  859. OnCellToggled (e);
  860. if (e.Cancel) {
  861. return;
  862. }
  863. if (!MultiSelect) {
  864. return;
  865. }
  866. var regions = GetMultiSelectedRegionsContaining (selectedColumn, selectedRow).ToArray ();
  867. var toggles = regions.Where (s => s.IsToggled).ToArray ();
  868. // Toggle it off
  869. if (toggles.Any ()) {
  870. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  871. MultiSelectedRegions.Clear ();
  872. foreach (var region in oldRegions) {
  873. if (!toggles.Contains (region))
  874. MultiSelectedRegions.Push (region);
  875. }
  876. } else {
  877. // user is toggling selection within a rectangular
  878. // select. So toggle the full region
  879. if (regions.Any ()) {
  880. foreach (var r in regions) {
  881. r.IsToggled = true;
  882. }
  883. } else {
  884. // Toggle on a single cell selection
  885. MultiSelectedRegions.Push (
  886. CreateTableSelection (selectedColumn, SelectedRow, selectedColumn, selectedRow, true)
  887. );
  888. }
  889. }
  890. }
  891. /// <summary>
  892. /// Returns a single point as a <see cref="TableSelection"/>
  893. /// </summary>
  894. /// <param name="x"></param>
  895. /// <param name="y"></param>
  896. /// <returns></returns>
  897. private TableSelection CreateTableSelection (int x, int y)
  898. {
  899. return CreateTableSelection (x, y, x, y);
  900. }
  901. /// <summary>
  902. /// <para>
  903. /// 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"/>).
  904. /// </para>
  905. /// <remarks>Returns <see langword="false"/> if <see cref="ColumnStyle.Visible"/> is <see langword="false"/>.</remarks>
  906. /// </summary>
  907. /// <param name="col"></param>
  908. /// <param name="row"></param>
  909. /// <returns></returns>
  910. public bool IsSelected (int col, int row)
  911. {
  912. if (!IsColumnVisible (col)) {
  913. return false;
  914. }
  915. if (GetMultiSelectedRegionsContaining (col, row).Any ()) {
  916. return true;
  917. }
  918. return row == SelectedRow &&
  919. (col == SelectedColumn || FullRowSelect);
  920. }
  921. private IEnumerable<TableSelection> GetMultiSelectedRegionsContaining (int col, int row)
  922. {
  923. if (!MultiSelect) {
  924. return Enumerable.Empty<TableSelection> ();
  925. }
  926. if (FullRowSelect) {
  927. return MultiSelectedRegions.Where (r => r.Rect.Bottom > row && r.Rect.Top <= row);
  928. } else {
  929. return MultiSelectedRegions.Where (r => r.Rect.Contains (col, row));
  930. }
  931. }
  932. /// <summary>
  933. /// Returns true if the given <paramref name="columnIndex"/> indexes a visible
  934. /// column otherwise false. Returns false for indexes that are out of bounds.
  935. /// </summary>
  936. /// <param name="columnIndex"></param>
  937. /// <returns></returns>
  938. private bool IsColumnVisible (int columnIndex)
  939. {
  940. // if the column index provided is out of bounds
  941. if (columnIndex < 0 || columnIndex >= table.Columns) {
  942. return false;
  943. }
  944. return this.Style.GetColumnStyleIfAny (columnIndex)?.Visible ?? true;
  945. }
  946. /// <summary>
  947. /// 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
  948. /// </summary>
  949. public override void PositionCursor ()
  950. {
  951. if (TableIsNullOrInvisible ()) {
  952. base.PositionCursor ();
  953. return;
  954. }
  955. var screenPoint = CellToScreen (SelectedColumn, SelectedRow);
  956. if (screenPoint != null)
  957. Move (screenPoint.Value.X, screenPoint.Value.Y);
  958. }
  959. ///<inheritdoc/>
  960. public override bool MouseEvent (MouseEvent me)
  961. {
  962. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  963. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  964. me.Flags != MouseFlags.WheeledLeft && me.Flags != MouseFlags.WheeledRight)
  965. return false;
  966. if (!HasFocus && CanFocus) {
  967. SetFocus ();
  968. }
  969. if (TableIsNullOrInvisible ()) {
  970. return false;
  971. }
  972. // Scroll wheel flags
  973. switch (me.Flags) {
  974. case MouseFlags.WheeledDown:
  975. RowOffset++;
  976. EnsureValidScrollOffsets ();
  977. SetNeedsDisplay ();
  978. return true;
  979. case MouseFlags.WheeledUp:
  980. RowOffset--;
  981. EnsureValidScrollOffsets ();
  982. SetNeedsDisplay ();
  983. return true;
  984. case MouseFlags.WheeledRight:
  985. ColumnOffset++;
  986. EnsureValidScrollOffsets ();
  987. SetNeedsDisplay ();
  988. return true;
  989. case MouseFlags.WheeledLeft:
  990. ColumnOffset--;
  991. EnsureValidScrollOffsets ();
  992. SetNeedsDisplay ();
  993. return true;
  994. }
  995. var boundsX = me.X;
  996. var boundsY = me.Y;
  997. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  998. if (scrollLeftPoint != null
  999. && scrollLeftPoint.Value.X == boundsX
  1000. && scrollLeftPoint.Value.Y == boundsY) {
  1001. ColumnOffset--;
  1002. EnsureValidScrollOffsets ();
  1003. SetNeedsDisplay ();
  1004. }
  1005. if (scrollRightPoint != null
  1006. && scrollRightPoint.Value.X == boundsX
  1007. && scrollRightPoint.Value.Y == boundsY) {
  1008. ColumnOffset++;
  1009. EnsureValidScrollOffsets ();
  1010. SetNeedsDisplay ();
  1011. }
  1012. var hit = ScreenToCell (boundsX, boundsY);
  1013. if (hit != null) {
  1014. if (MultiSelect && HasControlOrAlt (me)) {
  1015. UnionSelection (hit.Value.X, hit.Value.Y);
  1016. } else {
  1017. SetSelection (hit.Value.X, hit.Value.Y, me.Flags.HasFlag (MouseFlags.ButtonShift));
  1018. }
  1019. Update ();
  1020. }
  1021. }
  1022. // Double clicking a cell activates
  1023. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  1024. var hit = ScreenToCell (boundsX, boundsY);
  1025. if (hit != null) {
  1026. OnCellActivated (new CellActivatedEventArgs (Table, hit.Value.X, hit.Value.Y));
  1027. }
  1028. }
  1029. return false;
  1030. }
  1031. private bool HasControlOrAlt (MouseEvent me)
  1032. {
  1033. return me.Flags.HasFlag (MouseFlags.ButtonAlt) || me.Flags.HasFlag (MouseFlags.ButtonCtrl);
  1034. }
  1035. /// <summary>.
  1036. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point
  1037. /// on the screen (relative to the control client area). Returns null if the point is
  1038. /// in the header, no table is loaded or outside the control bounds.
  1039. /// </summary>
  1040. /// <param name="clientX">X offset from the top left of the control.</param>
  1041. /// <param name="clientY">Y offset from the top left of the control.</param>
  1042. /// <returns>Cell clicked or null.</returns>
  1043. public Point? ScreenToCell (int clientX, int clientY)
  1044. {
  1045. return ScreenToCell (clientX, clientY, out _, out _);
  1046. }
  1047. /// <summary>.
  1048. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point
  1049. /// on the screen (relative to the control client area). Returns null if the point is
  1050. /// in the header, no table is loaded or outside the control bounds.
  1051. /// </summary>
  1052. /// <param name="clientX">X offset from the top left of the control.</param>
  1053. /// <param name="clientY">Y offset from the top left of the control.</param>
  1054. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  1055. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny)
  1056. {
  1057. return ScreenToCell (clientX, clientY, out headerIfAny, out _);
  1058. }
  1059. /// <summary>.
  1060. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point
  1061. /// on the screen (relative to the control client area). Returns null if the point is
  1062. /// in the header, no table is loaded or outside the control bounds.
  1063. /// </summary>
  1064. /// <param name="clientX">X offset from the top left of the control.</param>
  1065. /// <param name="clientY">Y offset from the top left of the control.</param>
  1066. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  1067. /// <param name="offsetX">The horizontal offset of the click within the returned cell.</param>
  1068. public Point? ScreenToCell (int clientX, int clientY, out int? headerIfAny, out int? offsetX)
  1069. {
  1070. headerIfAny = null;
  1071. offsetX = null;
  1072. if (TableIsNullOrInvisible ()) {
  1073. return null;
  1074. }
  1075. var viewPort = CalculateViewport (Bounds);
  1076. var headerHeight = GetHeaderHeightIfAny ();
  1077. var col = viewPort.LastOrDefault (c => c.X <= clientX);
  1078. // Click is on the header section of rendered UI
  1079. if (clientY < headerHeight) {
  1080. headerIfAny = col?.Column;
  1081. offsetX = col != null ? clientX - col.X : null;
  1082. return null;
  1083. }
  1084. var rowIdx = RowOffset - headerHeight + clientY;
  1085. // if click is off bottom of the rows don't give an
  1086. // invalid index back to user!
  1087. if (rowIdx >= Table.Rows) {
  1088. return null;
  1089. }
  1090. if (col != null && rowIdx >= 0) {
  1091. offsetX = clientX - col.X;
  1092. return new Point (col.Column, rowIdx);
  1093. }
  1094. return null;
  1095. }
  1096. /// <summary>
  1097. /// 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
  1098. /// </summary>
  1099. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for</param>
  1100. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  1101. /// <returns></returns>
  1102. public Point? CellToScreen (int tableColumn, int tableRow)
  1103. {
  1104. if (TableIsNullOrInvisible ())
  1105. return null;
  1106. var viewPort = CalculateViewport (Bounds);
  1107. var headerHeight = GetHeaderHeightIfAny ();
  1108. var colHit = viewPort.FirstOrDefault (c => c.Column == tableColumn);
  1109. // current column is outside the scroll area
  1110. if (colHit == null)
  1111. return null;
  1112. // the cell is too far up above the current scroll area
  1113. if (RowOffset > tableRow)
  1114. return null;
  1115. // the cell is way down below the scroll area and off the screen
  1116. if (tableRow > RowOffset + (Bounds.Height - headerHeight))
  1117. return null;
  1118. return new Point (colHit.X, tableRow + headerHeight - RowOffset);
  1119. }
  1120. /// <summary>
  1121. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  1122. /// </summary>
  1123. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  1124. public void Update ()
  1125. {
  1126. if (!IsInitialized || TableIsNullOrInvisible ()) {
  1127. SetNeedsDisplay ();
  1128. return;
  1129. }
  1130. EnsureValidScrollOffsets ();
  1131. EnsureValidSelection ();
  1132. EnsureSelectedCellIsVisible ();
  1133. SetNeedsDisplay ();
  1134. }
  1135. /// <summary>
  1136. /// 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.
  1137. /// </summary>
  1138. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  1139. public void EnsureValidScrollOffsets ()
  1140. {
  1141. if (TableIsNullOrInvisible ()) {
  1142. return;
  1143. }
  1144. ColumnOffset = Math.Max (Math.Min (ColumnOffset, Table.Columns - 1), 0);
  1145. RowOffset = Math.Max (Math.Min (RowOffset, Table.Rows - 1), 0);
  1146. }
  1147. /// <summary>
  1148. /// 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.
  1149. /// </summary>
  1150. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  1151. public void EnsureValidSelection ()
  1152. {
  1153. if (TableIsNullOrInvisible ()) {
  1154. // Table doesn't exist, we should probably clear those selections
  1155. ClearMultiSelectedRegions (false);
  1156. return;
  1157. }
  1158. SelectedColumn = Math.Max (Math.Min (SelectedColumn, Table.Columns - 1), 0);
  1159. SelectedRow = Math.Max (Math.Min (SelectedRow, Table.Rows - 1), 0);
  1160. // If SelectedColumn is invisible move it to a visible one
  1161. SelectedColumn = GetNearestVisibleColumn (SelectedColumn, lookRight: true, true);
  1162. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1163. MultiSelectedRegions.Clear ();
  1164. // evaluate
  1165. foreach (var region in oldRegions) {
  1166. // ignore regions entirely below current table state
  1167. if (region.Rect.Top >= Table.Rows)
  1168. continue;
  1169. // ignore regions entirely too far right of table columns
  1170. if (region.Rect.Left >= Table.Columns)
  1171. continue;
  1172. // ensure region's origin exists
  1173. region.Origin = new Point (
  1174. Math.Max (Math.Min (region.Origin.X, Table.Columns - 1), 0),
  1175. Math.Max (Math.Min (region.Origin.Y, Table.Rows - 1), 0));
  1176. // ensure regions do not go over edge of table bounds
  1177. region.Rect = Rect.FromLTRB (region.Rect.Left,
  1178. region.Rect.Top,
  1179. Math.Max (Math.Min (region.Rect.Right, Table.Columns), 0),
  1180. Math.Max (Math.Min (region.Rect.Bottom, Table.Rows), 0)
  1181. );
  1182. MultiSelectedRegions.Push (region);
  1183. }
  1184. }
  1185. /// <summary>
  1186. /// Returns true if the <see cref="Table"/> is not set or all the
  1187. /// columns in the <see cref="Table"/> have an explicit
  1188. /// <see cref="ColumnStyle"/> that marks them <see cref="ColumnStyle.visible"/>
  1189. /// <see langword="false"/>.
  1190. /// </summary>
  1191. /// <returns></returns>
  1192. private bool TableIsNullOrInvisible ()
  1193. {
  1194. return Table == null ||
  1195. Table.Columns <= 0 ||
  1196. Enumerable.Range (0, Table.Columns).All (
  1197. c => (Style.GetColumnStyleIfAny (c)?.Visible ?? true) == false);
  1198. }
  1199. /// <summary>
  1200. /// Returns <paramref name="columnIndex"/> unless the <see cref="ColumnStyle.Visible"/> is false for
  1201. /// the indexed column. If so then the index returned is nudged to the nearest visible
  1202. /// column.
  1203. /// </summary>
  1204. /// <remarks>Returns <paramref name="columnIndex"/> unchanged if it is invalid (e.g. out of bounds).</remarks>
  1205. /// <param name="columnIndex">The input column index.</param>
  1206. /// <param name="lookRight">When nudging invisible selections look right first.
  1207. /// <see langword="true"/> to look right, <see langword="false"/> to look left.</param>
  1208. /// <param name="allowBumpingInOppositeDirection">If we cannot find anything visible when
  1209. /// looking in direction of <paramref name="lookRight"/> then should we look in the opposite
  1210. /// direction instead? Use true if you want to push a selection to a valid index no matter what.
  1211. /// Use false if you are primarily interested in learning about directional column visibility.</param>
  1212. private int GetNearestVisibleColumn (int columnIndex, bool lookRight, bool allowBumpingInOppositeDirection)
  1213. {
  1214. if (TryGetNearestVisibleColumn (columnIndex, lookRight, allowBumpingInOppositeDirection, out var answer)) {
  1215. return answer;
  1216. }
  1217. return columnIndex;
  1218. }
  1219. private bool TryGetNearestVisibleColumn (int columnIndex, bool lookRight, bool allowBumpingInOppositeDirection, out int idx)
  1220. {
  1221. // if the column index provided is out of bounds
  1222. if (columnIndex < 0 || columnIndex >= table.Columns) {
  1223. idx = columnIndex;
  1224. return false;
  1225. }
  1226. // get the column visibility by index (if no style visible is true)
  1227. bool [] columnVisibility =
  1228. Enumerable.Range (0, Table.Columns)
  1229. .Select (c => this.Style.GetColumnStyleIfAny (c)?.Visible ?? true)
  1230. .ToArray ();
  1231. // column is visible
  1232. if (columnVisibility [columnIndex]) {
  1233. idx = columnIndex;
  1234. return true;
  1235. }
  1236. int increment = lookRight ? 1 : -1;
  1237. // move in that direction
  1238. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment) {
  1239. // if we find a visible column
  1240. if (columnVisibility [i]) {
  1241. idx = i;
  1242. return true;
  1243. }
  1244. }
  1245. // Caller only wants to look in one direction and we did not find any
  1246. // visible columns in that direction
  1247. if (!allowBumpingInOppositeDirection) {
  1248. idx = columnIndex;
  1249. return false;
  1250. }
  1251. // Caller will let us look in the other direction so
  1252. // now look other way
  1253. increment = -increment;
  1254. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment) {
  1255. // if we find a visible column
  1256. if (columnVisibility [i]) {
  1257. idx = i;
  1258. return true;
  1259. }
  1260. }
  1261. // nothing seems to be visible so just return input index
  1262. idx = columnIndex;
  1263. return false;
  1264. }
  1265. /// <summary>
  1266. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  1267. /// </summary>
  1268. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  1269. public void EnsureSelectedCellIsVisible ()
  1270. {
  1271. if (Table == null || Table.Columns <= 0) {
  1272. return;
  1273. }
  1274. var columnsToRender = CalculateViewport (Bounds).ToArray ();
  1275. var headerHeight = GetHeaderHeightIfAny ();
  1276. //if we have scrolled too far to the left
  1277. if (SelectedColumn < columnsToRender.Min (r => r.Column)) {
  1278. ColumnOffset = SelectedColumn;
  1279. }
  1280. //if we have scrolled too far to the right
  1281. if (SelectedColumn > columnsToRender.Max (r => r.Column)) {
  1282. if (Style.SmoothHorizontalScrolling) {
  1283. // Scroll right 1 column at a time until the users selected column is visible
  1284. while (SelectedColumn > columnsToRender.Max (r => r.Column)) {
  1285. ColumnOffset++;
  1286. columnsToRender = CalculateViewport (Bounds).ToArray ();
  1287. // if we are already scrolled to the last column then break
  1288. // this will prevent any theoretical infinite loop
  1289. if (ColumnOffset >= Table.Columns - 1)
  1290. break;
  1291. }
  1292. } else {
  1293. ColumnOffset = SelectedColumn;
  1294. }
  1295. }
  1296. //if we have scrolled too far down
  1297. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  1298. RowOffset = SelectedRow - (Bounds.Height - headerHeight) + 1;
  1299. }
  1300. //if we have scrolled too far up
  1301. if (SelectedRow < RowOffset) {
  1302. RowOffset = SelectedRow;
  1303. }
  1304. }
  1305. /// <summary>
  1306. /// Invokes the <see cref="SelectedCellChanged"/> event
  1307. /// </summary>
  1308. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args)
  1309. {
  1310. SelectedCellChanged?.Invoke (this, args);
  1311. }
  1312. /// <summary>
  1313. /// Invokes the <see cref="CellActivated"/> event
  1314. /// </summary>
  1315. /// <param name="args"></param>
  1316. protected virtual void OnCellActivated (CellActivatedEventArgs args)
  1317. {
  1318. CellActivated?.Invoke (this, args);
  1319. }
  1320. /// <summary>
  1321. /// Invokes the <see cref="CellToggled"/> event
  1322. /// </summary>
  1323. /// <param name="args"></param>
  1324. protected virtual void OnCellToggled (CellToggledEventArgs args)
  1325. {
  1326. CellToggled?.Invoke (this, args);
  1327. }
  1328. /// <summary>
  1329. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  1330. /// </summary>
  1331. /// <param name="bounds"></param>
  1332. /// <param name="padding"></param>
  1333. /// <returns></returns>
  1334. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  1335. {
  1336. if (TableIsNullOrInvisible ()) {
  1337. return Enumerable.Empty<ColumnToRender> ();
  1338. }
  1339. var toReturn = new List<ColumnToRender> ();
  1340. int usedSpace = 0;
  1341. //if horizontal space is required at the start of the line (before the first header)
  1342. if (Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  1343. usedSpace += 1;
  1344. int availableHorizontalSpace = bounds.Width;
  1345. int rowsToRender = bounds.Height;
  1346. // reserved for the headers row
  1347. if (ShouldRenderHeaders ())
  1348. rowsToRender -= GetHeaderHeight ();
  1349. bool first = true;
  1350. var lastColumn = Table.Columns - 1;
  1351. // TODO : Maybe just a for loop?
  1352. foreach (var col in Enumerable.Range (0, Table.Columns).Skip (ColumnOffset)) {
  1353. int startingIdxForCurrentHeader = usedSpace;
  1354. var colStyle = Style.GetColumnStyleIfAny (col);
  1355. int colWidth;
  1356. // if column is not being rendered
  1357. if (colStyle?.Visible == false) {
  1358. // do not add it to the returned columns
  1359. continue;
  1360. }
  1361. // is there enough space for this column (and it's data)?
  1362. colWidth = CalculateMaxCellWidth (col, rowsToRender, colStyle) + padding;
  1363. if (MinCellWidth > 0 && colWidth < (MinCellWidth + padding)) {
  1364. if (MinCellWidth > MaxCellWidth) {
  1365. colWidth = MaxCellWidth + padding;
  1366. } else {
  1367. colWidth = MinCellWidth + padding;
  1368. }
  1369. }
  1370. // there is not enough space for this columns
  1371. // visible content
  1372. if (usedSpace + colWidth > availableHorizontalSpace) {
  1373. bool showColumn = false;
  1374. // if this column accepts flexible width rendering and
  1375. // is therefore happy rendering into less space
  1376. if (colStyle != null && colStyle.MinAcceptableWidth > 0 &&
  1377. // is there enough space to meet the MinAcceptableWidth
  1378. (availableHorizontalSpace - usedSpace) >= colStyle.MinAcceptableWidth) {
  1379. // show column and use use whatever space is
  1380. // left for rendering it
  1381. showColumn = true;
  1382. colWidth = availableHorizontalSpace - usedSpace;
  1383. }
  1384. // If its the only column we are able to render then
  1385. // accept it anyway (that must be one massively wide column!)
  1386. if (first) {
  1387. showColumn = true;
  1388. }
  1389. // no special exceptions and we are out of space
  1390. // so stop accepting new columns for the render area
  1391. if (!showColumn)
  1392. break;
  1393. }
  1394. usedSpace += colWidth;
  1395. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  1396. colWidth = Math.Min (availableHorizontalSpace, colWidth);
  1397. var isVeryLast = lastColumn == col;
  1398. // there is space
  1399. toReturn.Add (new ColumnToRender (col, startingIdxForCurrentHeader, colWidth, isVeryLast));
  1400. first = false;
  1401. }
  1402. if (Style.ExpandLastColumn) {
  1403. var last = toReturn.Last ();
  1404. last.Width = Math.Max (last.Width, availableHorizontalSpace - last.X);
  1405. }
  1406. return toReturn;
  1407. }
  1408. private bool ShouldRenderHeaders ()
  1409. {
  1410. if (TableIsNullOrInvisible ())
  1411. return false;
  1412. return Style.AlwaysShowHeaders || rowOffset == 0;
  1413. }
  1414. /// <summary>
  1415. /// 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"/>
  1416. /// </summary>
  1417. /// <param name="col"></param>
  1418. /// <param name="rowsToRender"></param>
  1419. /// <param name="colStyle"></param>
  1420. /// <returns></returns>
  1421. private int CalculateMaxCellWidth (int col, int rowsToRender, ColumnStyle colStyle)
  1422. {
  1423. int spaceRequired = table.ColumnNames [col].EnumerateRunes ().Sum (c => c.GetColumns ());
  1424. // if table has no rows
  1425. if (RowOffset < 0)
  1426. return spaceRequired;
  1427. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows; i++) {
  1428. //expand required space if cell is bigger than the last biggest cell or header
  1429. spaceRequired = Math.Max (
  1430. spaceRequired,
  1431. GetRepresentation (Table [i, col], colStyle).EnumerateRunes ().Sum (c => c.GetColumns ()));
  1432. }
  1433. // Don't require more space than the style allows
  1434. if (colStyle != null) {
  1435. // enforce maximum cell width based on style
  1436. if (spaceRequired > colStyle.MaxWidth) {
  1437. spaceRequired = colStyle.MaxWidth;
  1438. }
  1439. // enforce minimum cell width based on style
  1440. if (spaceRequired < colStyle.MinWidth) {
  1441. spaceRequired = colStyle.MinWidth;
  1442. }
  1443. }
  1444. // enforce maximum cell width based on global table style
  1445. if (spaceRequired > MaxCellWidth)
  1446. spaceRequired = MaxCellWidth;
  1447. return spaceRequired;
  1448. }
  1449. /// <summary>
  1450. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  1451. /// </summary>
  1452. /// <param name="value"></param>
  1453. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  1454. /// <returns></returns>
  1455. private string GetRepresentation (object value, ColumnStyle colStyle)
  1456. {
  1457. if (value == null || value == DBNull.Value) {
  1458. return NullSymbol;
  1459. }
  1460. return colStyle != null ? colStyle.GetRepresentation (value) : value.ToString ();
  1461. }
  1462. /// <summary>
  1463. /// Describes a desire to render a column at a given horizontal position in the UI
  1464. /// </summary>
  1465. internal class ColumnToRender {
  1466. /// <summary>
  1467. /// The column to render
  1468. /// </summary>
  1469. public int Column { get; set; }
  1470. /// <summary>
  1471. /// The horizontal position to begin rendering the column at
  1472. /// </summary>
  1473. public int X { get; set; }
  1474. /// <summary>
  1475. /// The width that the column should occupy as calculated by <see cref="CalculateViewport(Rect, int)"/>. Note that this includes
  1476. /// space for padding i.e. the separator between columns.
  1477. /// </summary>
  1478. public int Width { get; internal set; }
  1479. /// <summary>
  1480. /// True if this column is the very last column in the <see cref="Table"/> (not just the last visible column)
  1481. /// </summary>
  1482. public bool IsVeryLast { get; }
  1483. public ColumnToRender (int col, int x, int width, bool isVeryLast)
  1484. {
  1485. Column = col;
  1486. X = x;
  1487. Width = width;
  1488. IsVeryLast = isVeryLast;
  1489. }
  1490. }
  1491. }
  1492. }