TableView.cs 61 KB

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