TableView.cs 71 KB

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