TableView.cs 69 KB

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