TableView.cs 68 KB

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