CsvEditor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using Terminal.Gui;
  5. using Terminal.Gui.Trees;
  6. using System.Linq;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Text;
  10. using NStack;
  11. using System.Text.RegularExpressions;
  12. using CsvHelper;
  13. namespace UICatalog.Scenarios {
  14. [ScenarioMetadata (Name: "Csv Editor", Description: "Open and edit simple CSV files using the TableView class.")]
  15. [ScenarioCategory ("TableView")]
  16. [ScenarioCategory ("Controls")]
  17. [ScenarioCategory ("Dialogs")]
  18. [ScenarioCategory ("Text and Formatting")]
  19. [ScenarioCategory ("Dialogs")]
  20. [ScenarioCategory ("Top Level Windows")]
  21. [ScenarioCategory ("Files and IO")]
  22. public class CsvEditor : Scenario {
  23. TableView tableView;
  24. private string currentFile;
  25. private MenuItem miLeft;
  26. private MenuItem miRight;
  27. private MenuItem miCentered;
  28. private TextField selectedCellLabel;
  29. public override void Setup ()
  30. {
  31. Win.Title = this.GetName ();
  32. Win.Y = 1; // menu
  33. Win.Height = Dim.Fill (1); // status bar
  34. Application.Top.LayoutSubviews ();
  35. this.tableView = new TableView () {
  36. X = 0,
  37. Y = 0,
  38. Width = Dim.Fill (),
  39. Height = Dim.Fill (1),
  40. };
  41. var fileMenu = new MenuBarItem ("_File", new MenuItem [] {
  42. new MenuItem ("_Open CSV", "", () => Open()),
  43. new MenuItem ("_Save", "", () => Save()),
  44. new MenuItem ("_Quit", "Quits The App", () => Quit()),
  45. });
  46. //fileMenu.Help = "Help";
  47. var menu = new MenuBar (new MenuBarItem [] {
  48. fileMenu,
  49. new MenuBarItem ("_Edit", new MenuItem [] {
  50. new MenuItem ("_New Column", "", () => AddColumn()),
  51. new MenuItem ("_New Row", "", () => AddRow()),
  52. new MenuItem ("_Rename Column", "", () => RenameColumn()),
  53. new MenuItem ("_Delete Column", "", () => DeleteColum()),
  54. new MenuItem ("_Move Column", "", () => MoveColumn()),
  55. new MenuItem ("_Move Row", "", () => MoveRow()),
  56. new MenuItem ("_Sort Asc", "", () => Sort(true)),
  57. new MenuItem ("_Sort Desc", "", () => Sort(false)),
  58. }),
  59. new MenuBarItem ("_View", new MenuItem [] {
  60. miLeft = new MenuItem ("_Align Left", "", () => Align(TextAlignment.Left)),
  61. miRight = new MenuItem ("_Align Right", "", () => Align(TextAlignment.Right)),
  62. miCentered = new MenuItem ("_Align Centered", "", () => Align(TextAlignment.Centered)),
  63. // Format requires hard typed data table, when we read a CSV everything is untyped (string) so this only works for new columns in this demo
  64. miCentered = new MenuItem ("_Set Format Pattern", "", () => SetFormat()),
  65. })
  66. });
  67. Application.Top.Add (menu);
  68. var statusBar = new StatusBar (new StatusItem [] {
  69. new StatusItem(Key.CtrlMask | Key.O, "~^O~ Open", () => Open()),
  70. new StatusItem(Key.CtrlMask | Key.S, "~^S~ Save", () => Save()),
  71. new StatusItem(Application.QuitKey, $"{Application.QuitKey} to Quit", () => Quit()),
  72. });
  73. Application.Top.Add (statusBar);
  74. Win.Add (tableView);
  75. selectedCellLabel = new TextField () {
  76. X = 0,
  77. Y = Pos.Bottom (tableView),
  78. Text = "0,0",
  79. Width = Dim.Fill (),
  80. TextAlignment = TextAlignment.Right
  81. };
  82. selectedCellLabel.TextChanged += SelectedCellLabel_TextChanged;
  83. Win.Add (selectedCellLabel);
  84. tableView.SelectedCellChanged += OnSelectedCellChanged;
  85. tableView.CellActivated += EditCurrentCell;
  86. tableView.KeyPress += TableViewKeyPress;
  87. SetupScrollBar ();
  88. }
  89. private void SelectedCellLabel_TextChanged (ustring last)
  90. {
  91. // if user is in the text control and editing the selected cell
  92. if (!selectedCellLabel.HasFocus)
  93. return;
  94. // change selected cell to the one the user has typed into the box
  95. var match = Regex.Match (selectedCellLabel.Text.ToString (), "^(\\d+),(\\d+)$");
  96. if (match.Success) {
  97. tableView.SelectedColumn = int.Parse (match.Groups [1].Value);
  98. tableView.SelectedRow = int.Parse (match.Groups [2].Value);
  99. }
  100. }
  101. private void OnSelectedCellChanged (TableView.SelectedCellChangedEventArgs e)
  102. {
  103. // only update the text box if the user is not manually editing it
  104. if (!selectedCellLabel.HasFocus)
  105. selectedCellLabel.Text = $"{tableView.SelectedRow},{tableView.SelectedColumn}";
  106. if (tableView.Table == null || tableView.SelectedColumn == -1)
  107. return;
  108. var col = tableView.Table.Columns [tableView.SelectedColumn];
  109. var style = tableView.Style.GetColumnStyleIfAny (col);
  110. miLeft.Checked = style?.Alignment == TextAlignment.Left;
  111. miRight.Checked = style?.Alignment == TextAlignment.Right;
  112. miCentered.Checked = style?.Alignment == TextAlignment.Centered;
  113. }
  114. private void RenameColumn ()
  115. {
  116. if (NoTableLoaded ()) {
  117. return;
  118. }
  119. var currentCol = tableView.Table.Columns [tableView.SelectedColumn];
  120. if (GetText ("Rename Column", "Name:", currentCol.ColumnName, out string newName)) {
  121. currentCol.ColumnName = newName;
  122. tableView.Update ();
  123. }
  124. }
  125. private void DeleteColum ()
  126. {
  127. if (NoTableLoaded ()) {
  128. return;
  129. }
  130. if (tableView.SelectedColumn == -1) {
  131. MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
  132. return;
  133. }
  134. try {
  135. tableView.Table.Columns.RemoveAt (tableView.SelectedColumn);
  136. tableView.Update ();
  137. } catch (Exception ex) {
  138. MessageBox.ErrorQuery ("Could not remove column", ex.Message, "Ok");
  139. }
  140. }
  141. private void MoveColumn ()
  142. {
  143. if (NoTableLoaded ()) {
  144. return;
  145. }
  146. if (tableView.SelectedColumn == -1) {
  147. MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
  148. return;
  149. }
  150. try {
  151. var currentCol = tableView.Table.Columns [tableView.SelectedColumn];
  152. if (GetText ("Move Column", "New Index:", currentCol.Ordinal.ToString (), out string newOrdinal)) {
  153. var newIdx = Math.Min (Math.Max (0, int.Parse (newOrdinal)), tableView.Table.Columns.Count - 1);
  154. currentCol.SetOrdinal (newIdx);
  155. tableView.SetSelection (newIdx, tableView.SelectedRow, false);
  156. tableView.EnsureSelectedCellIsVisible ();
  157. tableView.SetNeedsDisplay ();
  158. }
  159. } catch (Exception ex) {
  160. MessageBox.ErrorQuery ("Error moving column", ex.Message, "Ok");
  161. }
  162. }
  163. private void Sort (bool asc)
  164. {
  165. if (NoTableLoaded ()) {
  166. return;
  167. }
  168. if (tableView.SelectedColumn == -1) {
  169. MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
  170. return;
  171. }
  172. var colName = tableView.Table.Columns [tableView.SelectedColumn].ColumnName;
  173. tableView.Table.DefaultView.Sort = colName + (asc ? " asc" : " desc");
  174. tableView.Table = tableView.Table.DefaultView.ToTable ();
  175. }
  176. private void MoveRow ()
  177. {
  178. if (NoTableLoaded ()) {
  179. return;
  180. }
  181. if (tableView.SelectedRow == -1) {
  182. MessageBox.ErrorQuery ("No Rows", "No row selected", "Ok");
  183. return;
  184. }
  185. try {
  186. int oldIdx = tableView.SelectedRow;
  187. var currentRow = tableView.Table.Rows [oldIdx];
  188. if (GetText ("Move Row", "New Row:", oldIdx.ToString (), out string newOrdinal)) {
  189. var newIdx = Math.Min (Math.Max (0, int.Parse (newOrdinal)), tableView.Table.Rows.Count - 1);
  190. if (newIdx == oldIdx)
  191. return;
  192. var arrayItems = currentRow.ItemArray;
  193. tableView.Table.Rows.Remove (currentRow);
  194. // Removing and Inserting the same DataRow seems to result in it loosing its values so we have to create a new instance
  195. var newRow = tableView.Table.NewRow ();
  196. newRow.ItemArray = arrayItems;
  197. tableView.Table.Rows.InsertAt (newRow, newIdx);
  198. tableView.SetSelection (tableView.SelectedColumn, newIdx, false);
  199. tableView.EnsureSelectedCellIsVisible ();
  200. tableView.SetNeedsDisplay ();
  201. }
  202. } catch (Exception ex) {
  203. MessageBox.ErrorQuery ("Error moving column", ex.Message, "Ok");
  204. }
  205. }
  206. private void Align (TextAlignment newAlignment)
  207. {
  208. if (NoTableLoaded ()) {
  209. return;
  210. }
  211. var col = tableView.Table.Columns [tableView.SelectedColumn];
  212. var style = tableView.Style.GetOrCreateColumnStyle (col);
  213. style.Alignment = newAlignment;
  214. miLeft.Checked = style.Alignment == TextAlignment.Left;
  215. miRight.Checked = style.Alignment == TextAlignment.Right;
  216. miCentered.Checked = style.Alignment == TextAlignment.Centered;
  217. tableView.Update ();
  218. }
  219. private void SetFormat ()
  220. {
  221. if (NoTableLoaded ()) {
  222. return;
  223. }
  224. var col = tableView.Table.Columns [tableView.SelectedColumn];
  225. if (col.DataType == typeof (string)) {
  226. MessageBox.ErrorQuery ("Cannot Format Column", "String columns cannot be Formatted, try adding a new column to the table with a date/numerical Type", "Ok");
  227. return;
  228. }
  229. var style = tableView.Style.GetOrCreateColumnStyle (col);
  230. if (GetText ("Format", "Pattern:", style.Format ?? "", out string newPattern)) {
  231. style.Format = newPattern;
  232. tableView.Update ();
  233. }
  234. }
  235. private bool NoTableLoaded ()
  236. {
  237. if (tableView.Table == null) {
  238. MessageBox.ErrorQuery ("No Table Loaded", "No table has currently be opened", "Ok");
  239. return true;
  240. }
  241. return false;
  242. }
  243. private void AddRow ()
  244. {
  245. if (NoTableLoaded ()) {
  246. return;
  247. }
  248. var newRow = tableView.Table.NewRow ();
  249. var newRowIdx = Math.Min (Math.Max (0, tableView.SelectedRow + 1), tableView.Table.Rows.Count);
  250. tableView.Table.Rows.InsertAt (newRow, newRowIdx);
  251. tableView.Update ();
  252. }
  253. private void AddColumn ()
  254. {
  255. if (NoTableLoaded ()) {
  256. return;
  257. }
  258. if (GetText ("Enter column name", "Name:", "", out string colName)) {
  259. var col = new DataColumn (colName);
  260. var newColIdx = Math.Min (Math.Max (0, tableView.SelectedColumn + 1), tableView.Table.Columns.Count);
  261. int result = MessageBox.Query ("Column Type", "Pick a data type for the column", new ustring [] { "Date", "Integer", "Double", "Text", "Cancel" });
  262. if (result <= -1 || result >= 4)
  263. return;
  264. switch (result) {
  265. case 0:
  266. col.DataType = typeof (DateTime);
  267. break;
  268. case 1:
  269. col.DataType = typeof (int);
  270. break;
  271. case 2:
  272. col.DataType = typeof (double);
  273. break;
  274. case 3:
  275. col.DataType = typeof (string);
  276. break;
  277. }
  278. tableView.Table.Columns.Add (col);
  279. col.SetOrdinal (newColIdx);
  280. tableView.Update ();
  281. }
  282. }
  283. private void Save ()
  284. {
  285. if (tableView.Table == null || string.IsNullOrWhiteSpace (currentFile)) {
  286. MessageBox.ErrorQuery ("No file loaded", "No file is currently loaded", "Ok");
  287. return;
  288. }
  289. using var writer = new CsvWriter (
  290. new StreamWriter (File.OpenWrite (currentFile)),
  291. CultureInfo.InvariantCulture);
  292. foreach (var col in tableView.Table.Columns.Cast<DataColumn> ().Select (c => c.ColumnName)) {
  293. writer.WriteField (col);
  294. }
  295. writer.NextRecord ();
  296. foreach (DataRow row in tableView.Table.Rows) {
  297. foreach (var item in row.ItemArray) {
  298. writer.WriteField (item);
  299. }
  300. writer.NextRecord ();
  301. }
  302. }
  303. private void Open ()
  304. {
  305. var ofd = new FileDialog ("Select File", "Open", "File", "Select a CSV file to open (does not support newlines, escaping etc)") {
  306. AllowedFileTypes = new string [] { ".csv" }
  307. };
  308. Application.Run (ofd);
  309. if (!ofd.Canceled && !string.IsNullOrWhiteSpace (ofd.FilePath?.ToString ())) {
  310. Open (ofd.FilePath.ToString ());
  311. }
  312. }
  313. private void Open (string filename)
  314. {
  315. int lineNumber = 0;
  316. currentFile = null;
  317. using var reader = new CsvReader (File.OpenText (filename), CultureInfo.InvariantCulture);
  318. try {
  319. var dt = new DataTable ();
  320. reader.Read ();
  321. if (reader.ReadHeader ()) {
  322. foreach (var h in reader.HeaderRecord) {
  323. dt.Columns.Add (h);
  324. }
  325. }
  326. while (reader.Read ()) {
  327. lineNumber++;
  328. var newRow = dt.Rows.Add ();
  329. for (int i = 0; i < dt.Columns.Count; i++) {
  330. newRow [i] = reader [i];
  331. }
  332. }
  333. tableView.Table = dt;
  334. // Only set the current filename if we successfully loaded the entire file
  335. currentFile = filename;
  336. Win.Title = $"{this.GetName ()} - {Path.GetFileName(currentFile)}";
  337. } catch (Exception ex) {
  338. MessageBox.ErrorQuery ("Open Failed", $"Error on line {lineNumber}{Environment.NewLine}{ex.Message}", "Ok");
  339. }
  340. }
  341. private void SetupScrollBar ()
  342. {
  343. var _scrollBar = new ScrollBarView (tableView, true);
  344. _scrollBar.ChangedPosition += () => {
  345. tableView.RowOffset = _scrollBar.Position;
  346. if (tableView.RowOffset != _scrollBar.Position) {
  347. _scrollBar.Position = tableView.RowOffset;
  348. }
  349. tableView.SetNeedsDisplay ();
  350. };
  351. /*
  352. _scrollBar.OtherScrollBarView.ChangedPosition += () => {
  353. _listView.LeftItem = _scrollBar.OtherScrollBarView.Position;
  354. if (_listView.LeftItem != _scrollBar.OtherScrollBarView.Position) {
  355. _scrollBar.OtherScrollBarView.Position = _listView.LeftItem;
  356. }
  357. _listView.SetNeedsDisplay ();
  358. };*/
  359. tableView.DrawContent += (e) => {
  360. _scrollBar.Size = tableView.Table?.Rows?.Count ?? 0;
  361. _scrollBar.Position = tableView.RowOffset;
  362. // _scrollBar.OtherScrollBarView.Size = _listView.Maxlength - 1;
  363. // _scrollBar.OtherScrollBarView.Position = _listView.LeftItem;
  364. _scrollBar.Refresh ();
  365. };
  366. }
  367. private void TableViewKeyPress (View.KeyEventEventArgs e)
  368. {
  369. if (e.KeyEvent.Key == Key.DeleteChar) {
  370. if (tableView.FullRowSelect) {
  371. // Delete button deletes all rows when in full row mode
  372. foreach (int toRemove in tableView.GetAllSelectedCells ().Select (p => p.Y).Distinct ().OrderByDescending (i => i))
  373. tableView.Table.Rows.RemoveAt (toRemove);
  374. } else {
  375. // otherwise set all selected cells to null
  376. foreach (var pt in tableView.GetAllSelectedCells ()) {
  377. tableView.Table.Rows [pt.Y] [pt.X] = DBNull.Value;
  378. }
  379. }
  380. tableView.Update ();
  381. e.Handled = true;
  382. }
  383. }
  384. private void ClearColumnStyles ()
  385. {
  386. tableView.Style.ColumnStyles.Clear ();
  387. tableView.Update ();
  388. }
  389. private void CloseExample ()
  390. {
  391. tableView.Table = null;
  392. }
  393. private void Quit ()
  394. {
  395. Application.RequestStop ();
  396. }
  397. private bool GetText (string title, string label, string initialText, out string enteredText)
  398. {
  399. bool okPressed = false;
  400. var ok = new Button ("Ok", is_default: true);
  401. ok.Clicked += () => { okPressed = true; Application.RequestStop (); };
  402. var cancel = new Button ("Cancel");
  403. cancel.Clicked += () => { Application.RequestStop (); };
  404. var d = new Dialog (title, 60, 20, ok, cancel);
  405. var lbl = new Label () {
  406. X = 0,
  407. Y = 1,
  408. Text = label
  409. };
  410. var tf = new TextField () {
  411. Text = initialText,
  412. X = 0,
  413. Y = 2,
  414. Width = Dim.Fill ()
  415. };
  416. d.Add (lbl, tf);
  417. tf.SetFocus ();
  418. Application.Run (d);
  419. enteredText = okPressed ? tf.Text.ToString () : null;
  420. return okPressed;
  421. }
  422. private void EditCurrentCell (TableView.CellActivatedEventArgs e)
  423. {
  424. if (e.Table == null)
  425. return;
  426. var oldValue = e.Table.Rows [e.Row] [e.Col].ToString ();
  427. if (GetText ("Enter new value", e.Table.Columns [e.Col].ColumnName, oldValue, out string newText)) {
  428. try {
  429. e.Table.Rows [e.Row] [e.Col] = string.IsNullOrWhiteSpace (newText) ? DBNull.Value : (object)newText;
  430. } catch (Exception ex) {
  431. MessageBox.ErrorQuery (60, 20, "Failed to set text", ex.Message, "Ok");
  432. }
  433. tableView.Update ();
  434. }
  435. }
  436. }
  437. }