TableView.cs 72 KB

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