TableView.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  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="DataTable"/>.
  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 partial class TableView : View {
  14. private int columnOffset;
  15. private int rowOffset;
  16. private int selectedRow;
  17. private int selectedColumn;
  18. private DataTable 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 DataTable 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.Count - 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.Count - 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.Count - 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.Count - 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 (DataTable 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. Move (0, 0);
  195. var frame = Frame;
  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 < frame.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.Count) {
  235. if(rowToRender == Table.Rows.Count && 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 = current.Column.ColumnName;
  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.Count;
  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. //render start of line
  426. if (style.ShowVerticalCellLines)
  427. AddRune (0, row, Driver.VLine);
  428. //start by clearing the entire line
  429. Move (0, row);
  430. Attribute color;
  431. if (FullRowSelect && IsSelected (0, rowToRender)) {
  432. color = focused ? rowScheme.HotFocus : rowScheme.HotNormal;
  433. } else {
  434. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  435. }
  436. Driver.SetAttribute (color);
  437. Driver.AddStr (new string (' ', Bounds.Width));
  438. // Render cells for each visible header for the current row
  439. for (int i = 0; i < columnsToRender.Length; i++) {
  440. var current = columnsToRender [i];
  441. var colStyle = Style.GetColumnStyleIfAny (current.Column);
  442. // move to start of cell (in line with header positions)
  443. Move (current.X, row);
  444. // Set color scheme based on whether the current cell is the selected one
  445. bool isSelectedCell = IsSelected (current.Column.Ordinal, rowToRender);
  446. var val = Table.Rows [rowToRender] [current.Column];
  447. // Render the (possibly truncated) cell value
  448. var representation = GetRepresentation (val, colStyle);
  449. // to get the colour scheme
  450. var colorSchemeGetter = colStyle?.ColorGetter;
  451. ColorScheme scheme;
  452. if (colorSchemeGetter != null) {
  453. // user has a delegate for defining row color per cell, call it
  454. scheme = colorSchemeGetter (
  455. new CellColorGetterArgs (Table, rowToRender, current.Column.Ordinal, val, representation, rowScheme));
  456. // if users custom color getter returned null, use the row scheme
  457. if (scheme == null) {
  458. scheme = rowScheme;
  459. }
  460. } else {
  461. // There is no custom cell coloring delegate so use the scheme for the row
  462. scheme = rowScheme;
  463. }
  464. Attribute cellColor;
  465. if (isSelectedCell) {
  466. cellColor = focused ? scheme.HotFocus : scheme.HotNormal;
  467. } else {
  468. cellColor = Enabled ? scheme.Normal : scheme.Disabled;
  469. }
  470. var render = TruncateOrPad (val, representation, current.Width, colStyle);
  471. // While many cells can be selected (see MultiSelectedRegions) only one cell is the primary (drives navigation etc)
  472. bool isPrimaryCell = current.Column.Ordinal == selectedColumn && rowToRender == selectedRow;
  473. RenderCell (cellColor, render, isPrimaryCell);
  474. // Reset color scheme to normal for drawing separators if we drew text with custom scheme
  475. if (scheme != rowScheme) {
  476. if (isSelectedCell) {
  477. color = focused ? rowScheme.HotFocus : rowScheme.HotNormal;
  478. } else {
  479. color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
  480. }
  481. Driver.SetAttribute (color);
  482. }
  483. // 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
  484. if (!FullRowSelect)
  485. Driver.SetAttribute (Enabled ? rowScheme.Normal : rowScheme.Disabled);
  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. //render end of line
  492. if (style.ShowVerticalCellLines)
  493. AddRune (Bounds.Width - 1, row, Driver.VLine);
  494. }
  495. /// <summary>
  496. /// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to
  497. /// with <see cref="ConsoleDriver.AddStr(ustring)"/>. The driver will already be
  498. /// in the correct place when rendering and you must render the full <paramref name="render"/>
  499. /// or the view will not look right. For simpler provision of color use <see cref="ColumnStyle.ColorGetter"/>
  500. /// For changing the content that is rendered use <see cref="ColumnStyle.RepresentationGetter"/>
  501. /// </summary>
  502. /// <param name="cellColor"></param>
  503. /// <param name="render"></param>
  504. /// <param name="isPrimaryCell"></param>
  505. protected virtual void RenderCell (Attribute cellColor, string render, bool isPrimaryCell)
  506. {
  507. // If the cell is the selected col/row then draw the first rune in inverted colors
  508. // this allows the user to track which cell is the active one during a multi cell
  509. // selection or in full row select mode
  510. if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell) {
  511. if (render.Length > 0) {
  512. // invert the color of the current cell for the first character
  513. Driver.SetAttribute (Driver.MakeAttribute (cellColor.Background, cellColor.Foreground));
  514. Driver.AddRune (render [0]);
  515. if (render.Length > 1) {
  516. Driver.SetAttribute (cellColor);
  517. Driver.AddStr (render.Substring (1));
  518. }
  519. }
  520. } else {
  521. Driver.SetAttribute (cellColor);
  522. Driver.AddStr (render);
  523. }
  524. }
  525. private void RenderSeparator (int col, int row, bool isHeader)
  526. {
  527. if (col < 0)
  528. return;
  529. var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
  530. Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
  531. AddRune (col, row, symbol);
  532. }
  533. void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
  534. {
  535. Move (col, row);
  536. d.AddRune (ch);
  537. }
  538. /// <summary>
  539. /// 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)
  540. /// </summary>
  541. /// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
  542. /// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
  543. /// <param name="availableHorizontalSpace"></param>
  544. /// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
  545. /// <returns></returns>
  546. private string TruncateOrPad (object originalCellValue, string representation, int availableHorizontalSpace, ColumnStyle colStyle)
  547. {
  548. if (string.IsNullOrEmpty (representation))
  549. return new string(' ',availableHorizontalSpace);
  550. // if value is not wide enough
  551. if (representation.Sum (c => Rune.ColumnWidth (c)) < availableHorizontalSpace) {
  552. // pad it out with spaces to the given alignment
  553. int toPad = availableHorizontalSpace - (representation.Sum (c => Rune.ColumnWidth (c)) + 1 /*leave 1 space for cell boundary*/);
  554. switch (colStyle?.GetAlignment (originalCellValue) ?? TextAlignment.Left) {
  555. case TextAlignment.Left:
  556. return representation + new string (' ', toPad);
  557. case TextAlignment.Right:
  558. return new string (' ', toPad) + representation;
  559. // TODO: With single line cells, centered and justified are the same right?
  560. case TextAlignment.Centered:
  561. case TextAlignment.Justified:
  562. return
  563. new string (' ', (int)Math.Floor (toPad / 2.0)) + // round down
  564. representation +
  565. new string (' ', (int)Math.Ceiling (toPad / 2.0)); // round up
  566. }
  567. }
  568. // value is too wide
  569. return new string (representation.TakeWhile (c => (availableHorizontalSpace -= Rune.ColumnWidth (c)) > 0).ToArray ());
  570. }
  571. /// <inheritdoc/>
  572. public override bool ProcessKey (KeyEvent keyEvent)
  573. {
  574. if (TableIsNullOrInvisible ()) {
  575. PositionCursor ();
  576. return false;
  577. }
  578. var result = InvokeKeybindings (keyEvent);
  579. if (result != null) {
  580. PositionCursor ();
  581. return true;
  582. }
  583. return false;
  584. }
  585. /// <summary>
  586. /// 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"/>)
  587. /// </summary>
  588. /// <param name="col"></param>
  589. /// <param name="row"></param>
  590. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  591. public void SetSelection (int col, int row, bool extendExistingSelection)
  592. {
  593. // if we are trying to increase the column index then
  594. // we are moving right otherwise we are moving left
  595. bool lookRight = col > selectedColumn;
  596. col = GetNearestVisibleColumn (col, lookRight, true);
  597. if (!MultiSelect || !extendExistingSelection) {
  598. ClearMultiSelectedRegions (true);
  599. }
  600. if (extendExistingSelection) {
  601. // If we are extending current selection but there isn't one
  602. if (MultiSelectedRegions.Count == 0 || MultiSelectedRegions.All(m=>m.IsToggled)) {
  603. // Create a new region between the old active cell and the new cell
  604. var rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
  605. MultiSelectedRegions.Push (rect);
  606. } else {
  607. // Extend the current head selection to include the new cell
  608. var head = MultiSelectedRegions.Pop ();
  609. var newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
  610. MultiSelectedRegions.Push (newRect);
  611. }
  612. }
  613. SelectedColumn = col;
  614. SelectedRow = row;
  615. }
  616. private void ClearMultiSelectedRegions (bool keepToggledSelections)
  617. {
  618. if (!keepToggledSelections) {
  619. MultiSelectedRegions.Clear ();
  620. return;
  621. }
  622. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  623. MultiSelectedRegions.Clear ();
  624. foreach (var region in oldRegions) {
  625. if (region.IsToggled) {
  626. MultiSelectedRegions.Push (region);
  627. }
  628. }
  629. }
  630. /// <summary>
  631. /// Unions the current selected cell (and/or regions) with the provided cell and makes
  632. /// it the active one.
  633. /// </summary>
  634. /// <param name="col"></param>
  635. /// <param name="row"></param>
  636. private void UnionSelection (int col, int row)
  637. {
  638. if (!MultiSelect || TableIsNullOrInvisible ()) {
  639. return;
  640. }
  641. EnsureValidSelection ();
  642. var oldColumn = SelectedColumn;
  643. var oldRow = SelectedRow;
  644. // move us to the new cell
  645. SelectedColumn = col;
  646. SelectedRow = row;
  647. MultiSelectedRegions.Push (
  648. CreateTableSelection (col, row)
  649. );
  650. // if the old cell was not part of a rectangular select
  651. // or otherwise selected we need to retain it in the selection
  652. if (!IsSelected (oldColumn, oldRow)) {
  653. MultiSelectedRegions.Push (
  654. CreateTableSelection (oldColumn, oldRow)
  655. );
  656. }
  657. }
  658. /// <summary>
  659. /// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally starting a box selection (see <see cref="MultiSelect"/>)
  660. /// </summary>
  661. /// <param name="offsetX">Offset in number of columns</param>
  662. /// <param name="offsetY">Offset in number of rows</param>
  663. /// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
  664. public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
  665. {
  666. SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
  667. Update ();
  668. }
  669. /// <summary>
  670. /// Moves the selection up by one page
  671. /// </summary>
  672. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  673. public void PageUp (bool extend)
  674. {
  675. ChangeSelectionByOffset (0, -(Bounds.Height - GetHeaderHeightIfAny ()), extend);
  676. Update ();
  677. }
  678. /// <summary>
  679. /// Moves the selection down by one page
  680. /// </summary>
  681. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  682. public void PageDown (bool extend)
  683. {
  684. ChangeSelectionByOffset (0, Bounds.Height - GetHeaderHeightIfAny (), extend);
  685. Update ();
  686. }
  687. /// <summary>
  688. /// Moves or extends the selection to the first cell in the table (0,0).
  689. /// If <see cref="FullRowSelect"/> is enabled then selection instead moves
  690. /// to (<see cref="SelectedColumn"/>,0) i.e. no horizontal scrolling.
  691. /// </summary>
  692. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  693. public void ChangeSelectionToStartOfTable (bool extend)
  694. {
  695. SetSelection (FullRowSelect ? SelectedColumn : 0, 0, extend);
  696. Update ();
  697. }
  698. /// <summary>
  699. /// Moves or extends the selection to the final cell in the table (nX,nY).
  700. /// If <see cref="FullRowSelect"/> is enabled then selection instead moves
  701. /// to (<see cref="SelectedColumn"/>,nY) i.e. no horizontal scrolling.
  702. /// </summary>
  703. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  704. public void ChangeSelectionToEndOfTable (bool extend)
  705. {
  706. var finalColumn = Table.Columns.Count - 1;
  707. SetSelection (FullRowSelect ? SelectedColumn : finalColumn, Table.Rows.Count - 1, extend);
  708. Update ();
  709. }
  710. /// <summary>
  711. /// Moves or extends the selection to the last cell in the current row
  712. /// </summary>
  713. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  714. public void ChangeSelectionToEndOfRow (bool extend)
  715. {
  716. SetSelection (Table.Columns.Count - 1, SelectedRow, extend);
  717. Update ();
  718. }
  719. /// <summary>
  720. /// Moves or extends the selection to the first cell in the current row
  721. /// </summary>
  722. /// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
  723. public void ChangeSelectionToStartOfRow (bool extend)
  724. {
  725. SetSelection (0, SelectedRow, extend);
  726. Update ();
  727. }
  728. /// <summary>
  729. /// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old selection regions)
  730. /// </summary>
  731. public void SelectAll ()
  732. {
  733. if (TableIsNullOrInvisible () || !MultiSelect || Table.Rows.Count == 0)
  734. return;
  735. ClearMultiSelectedRegions (true);
  736. // 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
  737. MultiSelectedRegions.Push (new TableSelection (new Point (SelectedColumn, SelectedRow), new Rect (0, 0, Table.Columns.Count, table.Rows.Count)));
  738. Update ();
  739. }
  740. /// <summary>
  741. /// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the selected cell
  742. /// </summary>
  743. /// <returns></returns>
  744. public IEnumerable<Point> GetAllSelectedCells ()
  745. {
  746. if (TableIsNullOrInvisible () || Table.Rows.Count == 0)
  747. {
  748. return Enumerable.Empty<Point>();
  749. }
  750. EnsureValidSelection ();
  751. var toReturn = new HashSet<Point>();
  752. // If there are one or more rectangular selections
  753. if (MultiSelect && MultiSelectedRegions.Any ()) {
  754. // 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
  755. var yMin = MultiSelectedRegions.Min (r => r.Rect.Top);
  756. var yMax = MultiSelectedRegions.Max (r => r.Rect.Bottom);
  757. var xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rect.Left);
  758. var xMax = FullRowSelect ? Table.Columns.Count : MultiSelectedRegions.Max (r => r.Rect.Right);
  759. for (int y = yMin; y < yMax; y++) {
  760. for (int x = xMin; x < xMax; x++) {
  761. if (IsSelected (x, y)) {
  762. toReturn.Add(new Point (x, y));
  763. }
  764. }
  765. }
  766. }
  767. // if there are no region selections then it is just the active cell
  768. // if we are selecting the full row
  769. if (FullRowSelect) {
  770. // all cells in active row are selected
  771. for (int x = 0; x < Table.Columns.Count; x++) {
  772. toReturn.Add(new Point (x, SelectedRow));
  773. }
  774. } else {
  775. // Not full row select and no multi selections
  776. toReturn.Add(new Point (SelectedColumn, SelectedRow));
  777. }
  778. return toReturn;
  779. }
  780. /// <summary>
  781. /// 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
  782. /// </summary>
  783. /// <param name="pt1X">Origin point for the selection in X</param>
  784. /// <param name="pt1Y">Origin point for the selection in Y</param>
  785. /// <param name="pt2X">End point for the selection in X</param>
  786. /// <param name="pt2Y">End point for the selection in Y</param>
  787. /// <param name="toggle">True if selection is result of <see cref="Command.ToggleChecked"/></param>
  788. /// <returns></returns>
  789. private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y, bool toggle = false)
  790. {
  791. var top = Math.Max (Math.Min (pt1Y, pt2Y), 0);
  792. var bot = Math.Max (Math.Max (pt1Y, pt2Y), 0);
  793. var left = Math.Max (Math.Min (pt1X, pt2X), 0);
  794. var right = Math.Max (Math.Max (pt1X, pt2X), 0);
  795. // Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
  796. return new TableSelection (new Point (pt1X, pt1Y), new Rect (left, top, right - left + 1, bot - top + 1)) {
  797. IsToggled = toggle
  798. };
  799. }
  800. private void ToggleCurrentCellSelection ()
  801. {
  802. if (!MultiSelect) {
  803. return;
  804. }
  805. var regions = GetMultiSelectedRegionsContaining(selectedColumn, selectedRow).ToArray();
  806. var toggles = regions.Where(s=>s.IsToggled).ToArray ();
  807. // Toggle it off
  808. if (toggles.Any ()) {
  809. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  810. MultiSelectedRegions.Clear ();
  811. foreach (var region in oldRegions) {
  812. if (!toggles.Contains (region))
  813. MultiSelectedRegions.Push (region);
  814. }
  815. } else {
  816. // user is toggling selection within a rectangular
  817. // select. So toggle the full region
  818. if(regions.Any())
  819. {
  820. foreach(var r in regions)
  821. {
  822. r.IsToggled = true;
  823. }
  824. }
  825. else{
  826. // Toggle on a single cell selection
  827. MultiSelectedRegions.Push (
  828. CreateTableSelection (selectedColumn, SelectedRow, selectedColumn, selectedRow, true)
  829. );
  830. }
  831. }
  832. }
  833. /// <summary>
  834. /// Returns a single point as a <see cref="TableSelection"/>
  835. /// </summary>
  836. /// <param name="x"></param>
  837. /// <param name="y"></param>
  838. /// <returns></returns>
  839. private TableSelection CreateTableSelection (int x, int y)
  840. {
  841. return CreateTableSelection (x, y, x, y);
  842. }
  843. /// <summary>
  844. /// <para>
  845. /// 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"/>).
  846. /// </para>
  847. /// <remarks>Returns <see langword="false"/> if <see cref="ColumnStyle.Visible"/> is <see langword="false"/>.</remarks>
  848. /// </summary>
  849. /// <param name="col"></param>
  850. /// <param name="row"></param>
  851. /// <returns></returns>
  852. public bool IsSelected (int col, int row)
  853. {
  854. if (!IsColumnVisible (col)) {
  855. return false;
  856. }
  857. if(GetMultiSelectedRegionsContaining(col,row).Any())
  858. {
  859. return true;
  860. }
  861. return row == SelectedRow &&
  862. (col == SelectedColumn || FullRowSelect);
  863. }
  864. private IEnumerable<TableSelection> GetMultiSelectedRegionsContaining(int col, int row)
  865. {
  866. if(!MultiSelect)
  867. {
  868. return Enumerable.Empty<TableSelection>();
  869. }
  870. if(FullRowSelect)
  871. {
  872. return MultiSelectedRegions.Where (r => r.Rect.Bottom > row && r.Rect.Top <= row);
  873. }
  874. else
  875. {
  876. return MultiSelectedRegions.Where (r => r.Rect.Contains (col, row));
  877. }
  878. }
  879. /// <summary>
  880. /// Returns true if the given <paramref name="columnIndex"/> indexes a visible
  881. /// column otherwise false. Returns false for indexes that are out of bounds.
  882. /// </summary>
  883. /// <param name="columnIndex"></param>
  884. /// <returns></returns>
  885. private bool IsColumnVisible (int columnIndex)
  886. {
  887. // if the column index provided is out of bounds
  888. if (columnIndex < 0 || columnIndex >= table.Columns.Count) {
  889. return false;
  890. }
  891. return this.Style.GetColumnStyleIfAny (Table.Columns [columnIndex])?.Visible ?? true;
  892. }
  893. /// <summary>
  894. /// 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
  895. /// </summary>
  896. public override void PositionCursor ()
  897. {
  898. if (TableIsNullOrInvisible ()) {
  899. base.PositionCursor ();
  900. return;
  901. }
  902. var screenPoint = CellToScreen (SelectedColumn, SelectedRow);
  903. if (screenPoint != null)
  904. Move (screenPoint.Value.X, screenPoint.Value.Y);
  905. }
  906. ///<inheritdoc/>
  907. public override bool MouseEvent (MouseEvent me)
  908. {
  909. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  910. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  911. me.Flags != MouseFlags.WheeledLeft && me.Flags != MouseFlags.WheeledRight)
  912. return false;
  913. if (!HasFocus && CanFocus) {
  914. SetFocus ();
  915. }
  916. if (TableIsNullOrInvisible ()) {
  917. return false;
  918. }
  919. // Scroll wheel flags
  920. switch (me.Flags) {
  921. case MouseFlags.WheeledDown:
  922. RowOffset++;
  923. EnsureValidScrollOffsets ();
  924. SetNeedsDisplay ();
  925. return true;
  926. case MouseFlags.WheeledUp:
  927. RowOffset--;
  928. EnsureValidScrollOffsets ();
  929. SetNeedsDisplay ();
  930. return true;
  931. case MouseFlags.WheeledRight:
  932. ColumnOffset++;
  933. EnsureValidScrollOffsets ();
  934. SetNeedsDisplay ();
  935. return true;
  936. case MouseFlags.WheeledLeft:
  937. ColumnOffset--;
  938. EnsureValidScrollOffsets ();
  939. SetNeedsDisplay ();
  940. return true;
  941. }
  942. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  943. if (scrollLeftPoint != null
  944. && scrollLeftPoint.Value.X == me.X
  945. && scrollLeftPoint.Value.Y == me.Y) {
  946. ColumnOffset--;
  947. EnsureValidScrollOffsets ();
  948. SetNeedsDisplay ();
  949. }
  950. if (scrollRightPoint != null
  951. && scrollRightPoint.Value.X == me.X
  952. && scrollRightPoint.Value.Y == me.Y) {
  953. ColumnOffset++;
  954. EnsureValidScrollOffsets ();
  955. SetNeedsDisplay ();
  956. }
  957. var hit = ScreenToCell (me.X, me.Y);
  958. if (hit != null) {
  959. if (MultiSelect && HasControlOrAlt (me)) {
  960. UnionSelection (hit.Value.X, hit.Value.Y);
  961. } else {
  962. SetSelection (hit.Value.X, hit.Value.Y, me.Flags.HasFlag (MouseFlags.ButtonShift));
  963. }
  964. Update ();
  965. }
  966. }
  967. // Double clicking a cell activates
  968. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  969. var hit = ScreenToCell (me.X, me.Y);
  970. if (hit != null) {
  971. OnCellActivated (new CellActivatedEventArgs (Table, hit.Value.X, hit.Value.Y));
  972. }
  973. }
  974. return false;
  975. }
  976. private bool HasControlOrAlt (MouseEvent me)
  977. {
  978. return me.Flags.HasFlag (MouseFlags.ButtonAlt) || me.Flags.HasFlag (MouseFlags.ButtonCtrl);
  979. }
  980. /// <summary>.
  981. /// Returns the column and row of <see cref="Table"/> that corresponds to a given point
  982. /// on the screen (relative to the control client area). Returns null if the point is
  983. /// in the header, no table is loaded or outside the control bounds.
  984. /// </summary>
  985. /// <param name="clientX">X offset from the top left of the control.</param>
  986. /// <param name="clientY">Y offset from the top left of the control.</param>
  987. /// <returns>Cell clicked or null.</returns>
  988. public Point? ScreenToCell (int clientX, int clientY)
  989. {
  990. return ScreenToCell (clientX, clientY, out _);
  991. }
  992. /// <inheritdoc cref="ScreenToCell(int, int)"/>
  993. /// <param name="clientX">X offset from the top left of the control.</param>
  994. /// <param name="clientY">Y offset from the top left of the control.</param>
  995. /// <param name="headerIfAny">If the click is in a header this is the column clicked.</param>
  996. public Point? ScreenToCell (int clientX, int clientY, out DataColumn headerIfAny)
  997. {
  998. headerIfAny = null;
  999. if (TableIsNullOrInvisible ())
  1000. return null;
  1001. var viewPort = CalculateViewport (Bounds);
  1002. var headerHeight = GetHeaderHeightIfAny ();
  1003. var col = viewPort.LastOrDefault (c => c.X <= clientX);
  1004. // Click is on the header section of rendered UI
  1005. if (clientY < headerHeight) {
  1006. headerIfAny = col?.Column;
  1007. return null;
  1008. }
  1009. var rowIdx = RowOffset - headerHeight + clientY;
  1010. // if click is off bottom of the rows don't give an
  1011. // invalid index back to user!
  1012. if (rowIdx >= Table.Rows.Count) {
  1013. return null;
  1014. }
  1015. if (col != null && rowIdx >= 0) {
  1016. return new Point (col.Column.Ordinal, rowIdx);
  1017. }
  1018. return null;
  1019. }
  1020. /// <summary>
  1021. /// 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
  1022. /// </summary>
  1023. /// <param name="tableColumn">The index of the <see cref="Table"/> column you are looking for, use <see cref="DataColumn.Ordinal"/></param>
  1024. /// <param name="tableRow">The index of the row in <see cref="Table"/> that you are looking for</param>
  1025. /// <returns></returns>
  1026. public Point? CellToScreen (int tableColumn, int tableRow)
  1027. {
  1028. if (TableIsNullOrInvisible ())
  1029. return null;
  1030. var viewPort = CalculateViewport (Bounds);
  1031. var headerHeight = GetHeaderHeightIfAny ();
  1032. var colHit = viewPort.FirstOrDefault (c => c.Column.Ordinal == tableColumn);
  1033. // current column is outside the scroll area
  1034. if (colHit == null)
  1035. return null;
  1036. // the cell is too far up above the current scroll area
  1037. if (RowOffset > tableRow)
  1038. return null;
  1039. // the cell is way down below the scroll area and off the screen
  1040. if (tableRow > RowOffset + (Bounds.Height - headerHeight))
  1041. return null;
  1042. return new Point (colHit.X, tableRow + headerHeight - RowOffset);
  1043. }
  1044. /// <summary>
  1045. /// Updates the view to reflect changes to <see cref="Table"/> and to (<see cref="ColumnOffset"/> / <see cref="RowOffset"/>) etc
  1046. /// </summary>
  1047. /// <remarks>This always calls <see cref="View.SetNeedsDisplay()"/></remarks>
  1048. public void Update ()
  1049. {
  1050. if (TableIsNullOrInvisible ()) {
  1051. SetNeedsDisplay ();
  1052. return;
  1053. }
  1054. EnsureValidScrollOffsets ();
  1055. EnsureValidSelection ();
  1056. EnsureSelectedCellIsVisible ();
  1057. SetNeedsDisplay ();
  1058. }
  1059. /// <summary>
  1060. /// 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.
  1061. /// </summary>
  1062. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  1063. public void EnsureValidScrollOffsets ()
  1064. {
  1065. if (TableIsNullOrInvisible ()) {
  1066. return;
  1067. }
  1068. ColumnOffset = Math.Max (Math.Min (ColumnOffset, Table.Columns.Count - 1), 0);
  1069. RowOffset = Math.Max (Math.Min (RowOffset, Table.Rows.Count - 1), 0);
  1070. }
  1071. /// <summary>
  1072. /// 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.
  1073. /// </summary>
  1074. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  1075. public void EnsureValidSelection ()
  1076. {
  1077. if (TableIsNullOrInvisible ()) {
  1078. // Table doesn't exist, we should probably clear those selections
  1079. ClearMultiSelectedRegions (false);
  1080. return;
  1081. }
  1082. SelectedColumn = Math.Max (Math.Min (SelectedColumn, Table.Columns.Count - 1), 0);
  1083. SelectedRow = Math.Max (Math.Min (SelectedRow, Table.Rows.Count - 1), 0);
  1084. // If SelectedColumn is invisible move it to a visible one
  1085. SelectedColumn = GetNearestVisibleColumn (SelectedColumn, lookRight: true, true);
  1086. var oldRegions = MultiSelectedRegions.ToArray ().Reverse ();
  1087. MultiSelectedRegions.Clear ();
  1088. // evaluate
  1089. foreach (var region in oldRegions) {
  1090. // ignore regions entirely below current table state
  1091. if (region.Rect.Top >= Table.Rows.Count)
  1092. continue;
  1093. // ignore regions entirely too far right of table columns
  1094. if (region.Rect.Left >= Table.Columns.Count)
  1095. continue;
  1096. // ensure region's origin exists
  1097. region.Origin = new Point (
  1098. Math.Max (Math.Min (region.Origin.X, Table.Columns.Count - 1), 0),
  1099. Math.Max (Math.Min (region.Origin.Y, Table.Rows.Count - 1), 0));
  1100. // ensure regions do not go over edge of table bounds
  1101. region.Rect = Rect.FromLTRB (region.Rect.Left,
  1102. region.Rect.Top,
  1103. Math.Max (Math.Min (region.Rect.Right, Table.Columns.Count), 0),
  1104. Math.Max (Math.Min (region.Rect.Bottom, Table.Rows.Count), 0)
  1105. );
  1106. MultiSelectedRegions.Push (region);
  1107. }
  1108. }
  1109. /// <summary>
  1110. /// Returns true if the <see cref="Table"/> is not set or all the
  1111. /// <see cref="DataColumn"/> in the <see cref="Table"/> have an explicit
  1112. /// <see cref="ColumnStyle"/> that marks them <see cref="ColumnStyle.visible"/>
  1113. /// <see langword="false"/>.
  1114. /// </summary>
  1115. /// <returns></returns>
  1116. private bool TableIsNullOrInvisible ()
  1117. {
  1118. return Table == null ||
  1119. Table.Columns.Count <= 0 ||
  1120. Table.Columns.Cast<DataColumn> ().All (
  1121. c => (Style.GetColumnStyleIfAny (c)?.Visible ?? true) == false);
  1122. }
  1123. /// <summary>
  1124. /// Returns <paramref name="columnIndex"/> unless the <see cref="ColumnStyle.Visible"/> is false for
  1125. /// the indexed <see cref="DataColumn"/>. If so then the index returned is nudged to the nearest visible
  1126. /// column.
  1127. /// </summary>
  1128. /// <remarks>Returns <paramref name="columnIndex"/> unchanged if it is invalid (e.g. out of bounds).</remarks>
  1129. /// <param name="columnIndex">The input column index.</param>
  1130. /// <param name="lookRight">When nudging invisible selections look right first.
  1131. /// <see langword="true"/> to look right, <see langword="false"/> to look left.</param>
  1132. /// <param name="allowBumpingInOppositeDirection">If we cannot find anything visible when
  1133. /// looking in direction of <paramref name="lookRight"/> then should we look in the opposite
  1134. /// direction instead? Use true if you want to push a selection to a valid index no matter what.
  1135. /// Use false if you are primarily interested in learning about directional column visibility.</param>
  1136. private int GetNearestVisibleColumn (int columnIndex, bool lookRight, bool allowBumpingInOppositeDirection)
  1137. {
  1138. if (TryGetNearestVisibleColumn (columnIndex, lookRight, allowBumpingInOppositeDirection, out var answer)) {
  1139. return answer;
  1140. }
  1141. return columnIndex;
  1142. }
  1143. private bool TryGetNearestVisibleColumn (int columnIndex, bool lookRight, bool allowBumpingInOppositeDirection, out int idx)
  1144. {
  1145. // if the column index provided is out of bounds
  1146. if (columnIndex < 0 || columnIndex >= table.Columns.Count) {
  1147. idx = columnIndex;
  1148. return false;
  1149. }
  1150. // get the column visibility by index (if no style visible is true)
  1151. bool [] columnVisibility = Table.Columns.Cast<DataColumn> ()
  1152. .Select (c => this.Style.GetColumnStyleIfAny (c)?.Visible ?? true)
  1153. .ToArray ();
  1154. // column is visible
  1155. if (columnVisibility [columnIndex]) {
  1156. idx = columnIndex;
  1157. return true;
  1158. }
  1159. int increment = lookRight ? 1 : -1;
  1160. // move in that direction
  1161. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment) {
  1162. // if we find a visible column
  1163. if (columnVisibility [i]) {
  1164. idx = i;
  1165. return true;
  1166. }
  1167. }
  1168. // Caller only wants to look in one direction and we did not find any
  1169. // visible columns in that direction
  1170. if (!allowBumpingInOppositeDirection) {
  1171. idx = columnIndex;
  1172. return false;
  1173. }
  1174. // Caller will let us look in the other direction so
  1175. // now look other way
  1176. increment = -increment;
  1177. for (int i = columnIndex; i >= 0 && i < columnVisibility.Length; i += increment) {
  1178. // if we find a visible column
  1179. if (columnVisibility [i]) {
  1180. idx = i;
  1181. return true;
  1182. }
  1183. }
  1184. // nothing seems to be visible so just return input index
  1185. idx = columnIndex;
  1186. return false;
  1187. }
  1188. /// <summary>
  1189. /// Updates scroll offsets to ensure that the selected cell is visible. Has no effect if <see cref="Table"/> has not been set.
  1190. /// </summary>
  1191. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDisplay()"/></remarks>
  1192. public void EnsureSelectedCellIsVisible ()
  1193. {
  1194. if (Table == null || Table.Columns.Count <= 0) {
  1195. return;
  1196. }
  1197. var columnsToRender = CalculateViewport (Bounds).ToArray ();
  1198. var headerHeight = GetHeaderHeightIfAny ();
  1199. //if we have scrolled too far to the left
  1200. if (SelectedColumn < columnsToRender.Min (r => r.Column.Ordinal)) {
  1201. ColumnOffset = SelectedColumn;
  1202. }
  1203. //if we have scrolled too far to the right
  1204. if (SelectedColumn > columnsToRender.Max (r => r.Column.Ordinal)) {
  1205. if (Style.SmoothHorizontalScrolling) {
  1206. // Scroll right 1 column at a time until the users selected column is visible
  1207. while (SelectedColumn > columnsToRender.Max (r => r.Column.Ordinal)) {
  1208. ColumnOffset++;
  1209. columnsToRender = CalculateViewport (Bounds).ToArray ();
  1210. // if we are already scrolled to the last column then break
  1211. // this will prevent any theoretical infinite loop
  1212. if (ColumnOffset >= Table.Columns.Count - 1)
  1213. break;
  1214. }
  1215. } else {
  1216. ColumnOffset = SelectedColumn;
  1217. }
  1218. }
  1219. //if we have scrolled too far down
  1220. if (SelectedRow >= RowOffset + (Bounds.Height - headerHeight)) {
  1221. RowOffset = SelectedRow - (Bounds.Height - headerHeight) + 1;
  1222. }
  1223. //if we have scrolled too far up
  1224. if (SelectedRow < RowOffset) {
  1225. RowOffset = SelectedRow;
  1226. }
  1227. }
  1228. /// <summary>
  1229. /// Invokes the <see cref="SelectedCellChanged"/> event
  1230. /// </summary>
  1231. protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args)
  1232. {
  1233. SelectedCellChanged?.Invoke (this,args);
  1234. }
  1235. /// <summary>
  1236. /// Invokes the <see cref="CellActivated"/> event
  1237. /// </summary>
  1238. /// <param name="args"></param>
  1239. protected virtual void OnCellActivated (CellActivatedEventArgs args)
  1240. {
  1241. CellActivated?.Invoke (this, args);
  1242. }
  1243. /// <summary>
  1244. /// Calculates which columns should be rendered given the <paramref name="bounds"/> in which to display and the <see cref="ColumnOffset"/>
  1245. /// </summary>
  1246. /// <param name="bounds"></param>
  1247. /// <param name="padding"></param>
  1248. /// <returns></returns>
  1249. private IEnumerable<ColumnToRender> CalculateViewport (Rect bounds, int padding = 1)
  1250. {
  1251. if (TableIsNullOrInvisible ()) {
  1252. return Enumerable.Empty<ColumnToRender> ();
  1253. }
  1254. var toReturn = new List<ColumnToRender> ();
  1255. int usedSpace = 0;
  1256. //if horizontal space is required at the start of the line (before the first header)
  1257. if (Style.ShowVerticalHeaderLines || Style.ShowVerticalCellLines)
  1258. usedSpace += 1;
  1259. int availableHorizontalSpace = bounds.Width;
  1260. int rowsToRender = bounds.Height;
  1261. // reserved for the headers row
  1262. if (ShouldRenderHeaders ())
  1263. rowsToRender -= GetHeaderHeight ();
  1264. bool first = true;
  1265. var lastColumn = Table.Columns.Cast<DataColumn> ().Last ();
  1266. foreach (var col in Table.Columns.Cast<DataColumn> ().Skip (ColumnOffset)) {
  1267. int startingIdxForCurrentHeader = usedSpace;
  1268. var colStyle = Style.GetColumnStyleIfAny (col);
  1269. int colWidth;
  1270. // if column is not being rendered
  1271. if (colStyle?.Visible == false) {
  1272. // do not add it to the returned columns
  1273. continue;
  1274. }
  1275. // is there enough space for this column (and it's data)?
  1276. colWidth = CalculateMaxCellWidth (col, rowsToRender, colStyle) + padding;
  1277. // there is not enough space for this columns
  1278. // visible content
  1279. if (usedSpace + colWidth > availableHorizontalSpace) {
  1280. bool showColumn = false;
  1281. // if this column accepts flexible width rendering and
  1282. // is therefore happy rendering into less space
  1283. if (colStyle != null && colStyle.MinAcceptableWidth > 0 &&
  1284. // is there enough space to meet the MinAcceptableWidth
  1285. (availableHorizontalSpace - usedSpace) >= colStyle.MinAcceptableWidth) {
  1286. // show column and use use whatever space is
  1287. // left for rendering it
  1288. showColumn = true;
  1289. colWidth = availableHorizontalSpace - usedSpace;
  1290. }
  1291. // If its the only column we are able to render then
  1292. // accept it anyway (that must be one massively wide column!)
  1293. if (first) {
  1294. showColumn = true;
  1295. }
  1296. // no special exceptions and we are out of space
  1297. // so stop accepting new columns for the render area
  1298. if (!showColumn)
  1299. break;
  1300. }
  1301. usedSpace += colWidth;
  1302. // required for if we end up here because first == true i.e. we have a single massive width (overspilling bounds) column to present
  1303. colWidth = Math.Min (availableHorizontalSpace, colWidth);
  1304. var isVeryLast = lastColumn == col;
  1305. // there is space
  1306. toReturn.Add(new ColumnToRender (col, startingIdxForCurrentHeader, colWidth, isVeryLast));
  1307. first = false;
  1308. }
  1309. if(Style.ExpandLastColumn)
  1310. {
  1311. var last = toReturn.Last ();
  1312. last.Width = Math.Max (last.Width, availableHorizontalSpace - last.X);
  1313. }
  1314. return toReturn;
  1315. }
  1316. private bool ShouldRenderHeaders ()
  1317. {
  1318. if (TableIsNullOrInvisible ())
  1319. return false;
  1320. return Style.AlwaysShowHeaders || rowOffset == 0;
  1321. }
  1322. /// <summary>
  1323. /// 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"/>
  1324. /// </summary>
  1325. /// <param name="col"></param>
  1326. /// <param name="rowsToRender"></param>
  1327. /// <param name="colStyle"></param>
  1328. /// <returns></returns>
  1329. private int CalculateMaxCellWidth (DataColumn col, int rowsToRender, ColumnStyle colStyle)
  1330. {
  1331. int spaceRequired = col.ColumnName.Sum (c => Rune.ColumnWidth (c));
  1332. // if table has no rows
  1333. if (RowOffset < 0)
  1334. return spaceRequired;
  1335. for (int i = RowOffset; i < RowOffset + rowsToRender && i < Table.Rows.Count; i++) {
  1336. //expand required space if cell is bigger than the last biggest cell or header
  1337. spaceRequired = Math.Max (spaceRequired, GetRepresentation (Table.Rows [i] [col], colStyle).Sum (c => Rune.ColumnWidth (c)));
  1338. }
  1339. // Don't require more space than the style allows
  1340. if (colStyle != null) {
  1341. // enforce maximum cell width based on style
  1342. if (spaceRequired > colStyle.MaxWidth) {
  1343. spaceRequired = colStyle.MaxWidth;
  1344. }
  1345. // enforce minimum cell width based on style
  1346. if (spaceRequired < colStyle.MinWidth) {
  1347. spaceRequired = colStyle.MinWidth;
  1348. }
  1349. }
  1350. // enforce maximum cell width based on global table style
  1351. if (spaceRequired > MaxCellWidth)
  1352. spaceRequired = MaxCellWidth;
  1353. return spaceRequired;
  1354. }
  1355. /// <summary>
  1356. /// Returns the value that should be rendered to best represent a strongly typed <paramref name="value"/> read from <see cref="Table"/>
  1357. /// </summary>
  1358. /// <param name="value"></param>
  1359. /// <param name="colStyle">Optional style defining how to represent cell values</param>
  1360. /// <returns></returns>
  1361. private string GetRepresentation (object value, ColumnStyle colStyle)
  1362. {
  1363. if (value == null || value == DBNull.Value) {
  1364. return NullSymbol;
  1365. }
  1366. return colStyle != null ? colStyle.GetRepresentation (value) : value.ToString ();
  1367. }
  1368. /// <summary>
  1369. /// Delegate for providing color to <see cref="TableView"/> cells based on the value being rendered
  1370. /// </summary>
  1371. /// <param name="args">Contains information about the cell for which color is needed</param>
  1372. /// <returns></returns>
  1373. public delegate ColorScheme CellColorGetterDelegate (CellColorGetterArgs args);
  1374. /// <summary>
  1375. /// Delegate for providing color for a whole row of a <see cref="TableView"/>
  1376. /// </summary>
  1377. /// <param name="args"></param>
  1378. /// <returns></returns>
  1379. public delegate ColorScheme RowColorGetterDelegate (RowColorGetterArgs args);
  1380. #region Nested Types
  1381. /// <summary>
  1382. /// Describes how to render a given column in a <see cref="TableView"/> including <see cref="Alignment"/>
  1383. /// and textual representation of cells (e.g. date formats)
  1384. ///
  1385. /// <a href="https://gui-cs.github.io/Terminal.Gui/articles/tableview.html">See TableView Deep Dive for more information</a>.
  1386. /// </summary>
  1387. public class ColumnStyle {
  1388. /// <summary>
  1389. /// Defines the default alignment for all values rendered in this column. For custom alignment based on cell contents use <see cref="AlignmentGetter"/>.
  1390. /// </summary>
  1391. public TextAlignment Alignment { get; set; }
  1392. /// <summary>
  1393. /// Defines a delegate for returning custom alignment per cell based on cell values. When specified this will override <see cref="Alignment"/>
  1394. /// </summary>
  1395. public Func<object, TextAlignment> AlignmentGetter;
  1396. /// <summary>
  1397. /// 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"/>
  1398. /// </summary>
  1399. public Func<object, string> RepresentationGetter;
  1400. /// <summary>
  1401. /// Defines a delegate for returning a custom color scheme per cell based on cell values.
  1402. /// Return null for the default
  1403. /// </summary>
  1404. public CellColorGetterDelegate ColorGetter;
  1405. private bool visible = true;
  1406. /// <summary>
  1407. /// Defines the format for values e.g. "yyyy-MM-dd" for dates
  1408. /// </summary>
  1409. public string Format { get; set; }
  1410. /// <summary>
  1411. /// 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"/>
  1412. /// </summary>
  1413. public int MaxWidth { get; set; } = TableView.DefaultMaxCellWidth;
  1414. /// <summary>
  1415. /// Set the minimum width of the column in characters. Setting this will ensure that
  1416. /// even when a column has short content/header it still fills a given width of the control.
  1417. ///
  1418. /// <para>This value will be ignored if more than the tables <see cref="TableView.MaxCellWidth"/>
  1419. /// or the <see cref="MaxWidth"/>
  1420. /// </para>
  1421. /// <remarks>
  1422. /// For setting a flexible column width (down to a lower limit) use <see cref="MinAcceptableWidth"/>
  1423. /// instead
  1424. /// </remarks>
  1425. /// </summary>
  1426. public int MinWidth { get; set; }
  1427. /// <summary>
  1428. /// Enables flexible sizing of this column based on available screen space to render into.
  1429. /// </summary>
  1430. public int MinAcceptableWidth { get; set; } = DefaultMinAcceptableWidth;
  1431. /// <summary>
  1432. /// Gets or Sets a value indicating whether the column should be visible to the user.
  1433. /// This affects both whether it is rendered and whether it can be selected. Defaults to
  1434. /// true.
  1435. /// </summary>
  1436. /// <remarks>If <see cref="MaxWidth"/> is 0 then <see cref="Visible"/> will always return false.</remarks>
  1437. public bool Visible { get => MaxWidth >= 0 && visible; set => visible = value; }
  1438. /// <summary>
  1439. /// Returns the alignment for the cell based on <paramref name="cellValue"/> and <see cref="AlignmentGetter"/>/<see cref="Alignment"/>
  1440. /// </summary>
  1441. /// <param name="cellValue"></param>
  1442. /// <returns></returns>
  1443. public TextAlignment GetAlignment (object cellValue)
  1444. {
  1445. if (AlignmentGetter != null)
  1446. return AlignmentGetter (cellValue);
  1447. return Alignment;
  1448. }
  1449. /// <summary>
  1450. /// 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"/>
  1451. /// </summary>
  1452. /// <param name="value"></param>
  1453. /// <returns></returns>
  1454. public string GetRepresentation (object value)
  1455. {
  1456. if (!string.IsNullOrWhiteSpace (Format)) {
  1457. if (value is IFormattable f)
  1458. return f.ToString (Format, null);
  1459. }
  1460. if (RepresentationGetter != null)
  1461. return RepresentationGetter (value);
  1462. return value?.ToString ();
  1463. }
  1464. }
  1465. /// <summary>
  1466. /// Defines rendering options that affect how the table is displayed.
  1467. ///
  1468. /// <a href="https://gui-cs.github.io/Terminal.Gui/articles/tableview.html">See TableView Deep Dive for more information</a>.
  1469. /// </summary>
  1470. public class TableStyle {
  1471. /// <summary>
  1472. /// Gets or sets a flag indicating whether to render headers of a <see cref="TableView"/>.
  1473. /// Defaults to <see langword="true"/>.
  1474. /// </summary>
  1475. /// <remarks><see cref="ShowHorizontalHeaderOverline"/>, <see cref="ShowHorizontalHeaderUnderline"/> etc
  1476. /// may still be used even if <see cref="ShowHeaders"/> is <see langword="false"/>.</remarks>
  1477. public bool ShowHeaders { get; set; } = true;
  1478. /// <summary>
  1479. /// When scrolling down always lock the column headers in place as the first row of the table
  1480. /// </summary>
  1481. public bool AlwaysShowHeaders { get; set; } = false;
  1482. /// <summary>
  1483. /// True to render a solid line above the headers
  1484. /// </summary>
  1485. public bool ShowHorizontalHeaderOverline { get; set; } = true;
  1486. /// <summary>
  1487. /// True to render a solid line under the headers
  1488. /// </summary>
  1489. public bool ShowHorizontalHeaderUnderline { get; set; } = true;
  1490. /// <summary>
  1491. /// True to render a solid line vertical line between cells
  1492. /// </summary>
  1493. public bool ShowVerticalCellLines { get; set; } = true;
  1494. /// <summary>
  1495. /// True to render a solid line vertical line between headers
  1496. /// </summary>
  1497. public bool ShowVerticalHeaderLines { get; set; } = true;
  1498. /// <summary>
  1499. /// True to render a arrows on the right/left of the table when
  1500. /// there are more column(s) that can be scrolled to. Requires
  1501. /// <see cref="ShowHorizontalHeaderUnderline"/> to be true.
  1502. /// Defaults to true
  1503. /// </summary>
  1504. public bool ShowHorizontalScrollIndicators { get; set; } = true;
  1505. /// <summary>
  1506. /// Gets or sets a flag indicating whether there should be a horizontal line after all the data
  1507. /// in the table. Defaults to <see langword="false"/>.
  1508. /// </summary>
  1509. public bool ShowHorizontalBottomline { get; set; } = false;
  1510. /// <summary>
  1511. /// True to invert the colors of the first symbol of the selected cell in the <see cref="TableView"/>.
  1512. /// This gives the appearance of a cursor for when the <see cref="ConsoleDriver"/> doesn't otherwise show
  1513. /// this
  1514. /// </summary>
  1515. public bool InvertSelectedCellFirstCharacter { get; set; } = false;
  1516. /// <summary>
  1517. /// Collection of columns for which you want special rendering (e.g. custom column lengths, text alignment etc)
  1518. /// </summary>
  1519. public Dictionary<DataColumn, ColumnStyle> ColumnStyles { get; set; } = new Dictionary<DataColumn, ColumnStyle> ();
  1520. /// <summary>
  1521. /// Delegate for coloring specific rows in a different color. For cell color <see cref="ColumnStyle.ColorGetter"/>
  1522. /// </summary>
  1523. /// <value></value>
  1524. public RowColorGetterDelegate RowColorGetter { get; set; }
  1525. /// <summary>
  1526. /// Determines rendering when the last column in the table is visible but it's
  1527. /// content or <see cref="ColumnStyle.MaxWidth"/> is less than the remaining
  1528. /// space in the control. True (the default) will expand the column to fill
  1529. /// the remaining bounds of the control. False will draw a column ending line
  1530. /// and leave a blank column that cannot be selected in the remaining space.
  1531. /// </summary>
  1532. /// <value></value>
  1533. public bool ExpandLastColumn { get; set; } = true;
  1534. /// <summary>
  1535. /// <para>
  1536. /// Determines how <see cref="TableView.ColumnOffset"/> is updated when scrolling
  1537. /// right off the end of the currently visible area.
  1538. /// </para>
  1539. /// <para>
  1540. /// If true then when scrolling right the scroll offset is increased the minimum required to show
  1541. /// the new column. This may be slow if you have an incredibly large number of columns in
  1542. /// your table and/or slow <see cref="ColumnStyle.RepresentationGetter"/> implementations
  1543. /// </para>
  1544. /// <para>
  1545. /// If false then scroll offset is set to the currently selected column (i.e. PageRight).
  1546. /// </para>
  1547. /// </summary>
  1548. public bool SmoothHorizontalScrolling { get; set; } = true;
  1549. /// <summary>
  1550. /// Returns the entry from <see cref="ColumnStyles"/> for the given <paramref name="col"/> or null if no custom styling is defined for it
  1551. /// </summary>
  1552. /// <param name="col"></param>
  1553. /// <returns></returns>
  1554. public ColumnStyle GetColumnStyleIfAny (DataColumn col)
  1555. {
  1556. return ColumnStyles.TryGetValue (col, out ColumnStyle result) ? result : null;
  1557. }
  1558. /// <summary>
  1559. /// Returns an existing <see cref="ColumnStyle"/> for the given <paramref name="col"/> or creates a new one with default options
  1560. /// </summary>
  1561. /// <param name="col"></param>
  1562. /// <returns></returns>
  1563. public ColumnStyle GetOrCreateColumnStyle (DataColumn col)
  1564. {
  1565. if (!ColumnStyles.ContainsKey (col))
  1566. ColumnStyles.Add (col, new ColumnStyle ());
  1567. return ColumnStyles [col];
  1568. }
  1569. }
  1570. /// <summary>
  1571. /// Describes a desire to render a column at a given horizontal position in the UI
  1572. /// </summary>
  1573. internal class ColumnToRender {
  1574. /// <summary>
  1575. /// The column to render
  1576. /// </summary>
  1577. public DataColumn Column { get; set; }
  1578. /// <summary>
  1579. /// The horizontal position to begin rendering the column at
  1580. /// </summary>
  1581. public int X { get; set; }
  1582. /// <summary>
  1583. /// The width that the column should occupy as calculated by <see cref="CalculateViewport(Rect, int)"/>. Note that this includes
  1584. /// space for padding i.e. the separator between columns.
  1585. /// </summary>
  1586. public int Width { get; internal set; }
  1587. /// <summary>
  1588. /// True if this column is the very last column in the <see cref="Table"/> (not just the last visible column)
  1589. /// </summary>
  1590. public bool IsVeryLast { get; }
  1591. public ColumnToRender (DataColumn col, int x, int width, bool isVeryLast)
  1592. {
  1593. Column = col;
  1594. X = x;
  1595. Width = width;
  1596. IsVeryLast = isVeryLast;
  1597. }
  1598. }
  1599. /// <summary>
  1600. /// Arguments for a <see cref="CellColorGetterDelegate"/>. Describes a cell for which a rendering
  1601. /// <see cref="ColorScheme"/> is being sought
  1602. /// </summary>
  1603. public class CellColorGetterArgs {
  1604. /// <summary>
  1605. /// The data table hosted by the <see cref="TableView"/> control.
  1606. /// </summary>
  1607. public DataTable Table { get; }
  1608. /// <summary>
  1609. /// The index of the row in <see cref="Table"/> for which color is needed
  1610. /// </summary>
  1611. public int RowIndex { get; }
  1612. /// <summary>
  1613. /// The index of column in <see cref="Table"/> for which color is needed
  1614. /// </summary>
  1615. public int ColIdex { get; }
  1616. /// <summary>
  1617. /// The hard typed value being rendered in the cell for which color is needed
  1618. /// </summary>
  1619. public object CellValue { get; }
  1620. /// <summary>
  1621. /// The textual representation of <see cref="CellValue"/> (what will actually be drawn to the screen)
  1622. /// </summary>
  1623. public string Representation { get; }
  1624. /// <summary>
  1625. /// the color scheme that is going to be used to render the cell if no cell specific color scheme is returned
  1626. /// </summary>
  1627. public ColorScheme RowScheme { get; }
  1628. internal CellColorGetterArgs (DataTable table, int rowIdx, int colIdx, object cellValue, string representation, ColorScheme rowScheme)
  1629. {
  1630. Table = table;
  1631. RowIndex = rowIdx;
  1632. ColIdex = colIdx;
  1633. CellValue = cellValue;
  1634. Representation = representation;
  1635. RowScheme = rowScheme;
  1636. }
  1637. }
  1638. /// <summary>
  1639. /// Arguments for <see cref="RowColorGetterDelegate"/>. Describes a row of data in a <see cref="DataTable"/>
  1640. /// for which <see cref="ColorScheme"/> is sought.
  1641. /// </summary>
  1642. public class RowColorGetterArgs {
  1643. /// <summary>
  1644. /// The data table hosted by the <see cref="TableView"/> control.
  1645. /// </summary>
  1646. public DataTable Table { get; }
  1647. /// <summary>
  1648. /// The index of the row in <see cref="Table"/> for which color is needed
  1649. /// </summary>
  1650. public int RowIndex { get; }
  1651. internal RowColorGetterArgs (DataTable table, int rowIdx)
  1652. {
  1653. Table = table;
  1654. RowIndex = rowIdx;
  1655. }
  1656. }
  1657. /// <summary>
  1658. /// Describes a selected region of the table
  1659. /// </summary>
  1660. public class TableSelection {
  1661. /// <summary>
  1662. /// Corner of the <see cref="Rect"/> where selection began
  1663. /// </summary>
  1664. /// <value></value>
  1665. public Point Origin { get; set; }
  1666. /// <summary>
  1667. /// Area selected
  1668. /// </summary>
  1669. /// <value></value>
  1670. public Rect Rect { get; set; }
  1671. /// <summary>
  1672. /// True if the selection was made through <see cref="Command.ToggleChecked"/>
  1673. /// and therefore should persist even through keyboard navigation.
  1674. /// </summary>
  1675. public bool IsToggled { get; set; }
  1676. /// <summary>
  1677. /// Creates a new selected area starting at the origin corner and covering the provided rectangular area
  1678. /// </summary>
  1679. /// <param name="origin"></param>
  1680. /// <param name="rect"></param>
  1681. public TableSelection (Point origin, Rect rect)
  1682. {
  1683. Origin = origin;
  1684. Rect = rect;
  1685. }
  1686. }
  1687. #endregion
  1688. }
  1689. }