TableView.cs 71 KB

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