Fixes #2195. CsvEditor: Column Type dialog not wide enough.

This commit is contained in:
BDisp
2022-11-07 21:10:12 +00:00
parent 39463146c5
commit d1d86edf3e
3 changed files with 185 additions and 191 deletions

View File

@@ -20,7 +20,7 @@ namespace Terminal.Gui {
/// or buttons added to the dialog calls <see cref="Application.RequestStop"/>.
/// </remarks>
public class Dialog : Window {
List<Button> buttons = new List<Button> ();
internal List<Button> buttons = new List<Button> ();
const int padding = 0;
/// <summary>

View File

@@ -300,7 +300,7 @@ namespace Terminal.Gui {
if (width == 0 & height == 0) {
// Dynamically size Width
d.Width = Math.Min (Math.Max (maxWidthLine, Math.Max (title.ConsoleWidth, Math.Max (textWidth + 2, d.GetButtonsWidth ()))), Application.Driver.Cols); // textWidth + (left + padding + padding + right)
d.Width = Math.Min (Math.Max (maxWidthLine, Math.Max (title.ConsoleWidth, Math.Max (textWidth + 2, d.GetButtonsWidth () + d.buttons.Count + 2))), Application.Driver.Cols); // textWidth + (left + padding + padding + right)
}
// Setup actions

View File

@@ -20,8 +20,7 @@ namespace UICatalog.Scenarios {
[ScenarioCategory ("Dialogs")]
[ScenarioCategory ("Top Level Windows")]
[ScenarioCategory ("Files and IO")]
public class CsvEditor : Scenario
{
public class CsvEditor : Scenario {
TableView tableView;
private string currentFile;
private MenuItem miLeft;
@@ -31,7 +30,7 @@ namespace UICatalog.Scenarios {
public override void Setup ()
{
Win.Title = this.GetName();
Win.Title = this.GetName ();
Win.Y = 1; // menu
Win.Height = Dim.Fill (1); // status bar
Application.Top.LayoutSubviews ();
@@ -81,22 +80,22 @@ namespace UICatalog.Scenarios {
Win.Add (tableView);
selectedCellLabel = new TextField(){
selectedCellLabel = new TextField () {
X = 0,
Y = Pos.Bottom(tableView),
Y = Pos.Bottom (tableView),
Text = "0,0",
Width = Dim.Fill(),
TextAlignment = TextAlignment.Right
Width = Dim.Fill (),
TextAlignment = TextAlignment.Right
};
selectedCellLabel.TextChanged += SelectedCellLabel_TextChanged;
Win.Add(selectedCellLabel);
Win.Add (selectedCellLabel);
tableView.SelectedCellChanged += OnSelectedCellChanged;
tableView.CellActivated += EditCurrentCell;
tableView.KeyPress += TableViewKeyPress;
SetupScrollBar();
SetupScrollBar ();
}
private void SelectedCellLabel_TextChanged (ustring last)
@@ -104,10 +103,10 @@ namespace UICatalog.Scenarios {
// if user is in the text control and editing the selected cell
if (!selectedCellLabel.HasFocus)
return;
// change selected cell to the one the user has typed into the box
var match = Regex.Match (selectedCellLabel.Text.ToString(), "^(\\d+),(\\d+)$");
if(match.Success) {
var match = Regex.Match (selectedCellLabel.Text.ToString (), "^(\\d+),(\\d+)$");
if (match.Success) {
tableView.SelectedColumn = int.Parse (match.Groups [1].Value);
tableView.SelectedRow = int.Parse (match.Groups [2].Value);
@@ -119,149 +118,147 @@ namespace UICatalog.Scenarios {
// only update the text box if the user is not manually editing it
if (!selectedCellLabel.HasFocus)
selectedCellLabel.Text = $"{tableView.SelectedRow},{tableView.SelectedColumn}";
if(tableView.Table == null || tableView.SelectedColumn == -1)
if (tableView.Table == null || tableView.SelectedColumn == -1)
return;
var col = tableView.Table.Columns[tableView.SelectedColumn];
var col = tableView.Table.Columns [tableView.SelectedColumn];
var style = tableView.Style.GetColumnStyleIfAny (col);
var style = tableView.Style.GetColumnStyleIfAny(col);
miLeft.Checked = style?.Alignment == TextAlignment.Left;
miRight.Checked = style?.Alignment == TextAlignment.Right;
miCentered.Checked = style?.Alignment == TextAlignment.Centered;
miCentered.Checked = style?.Alignment == TextAlignment.Centered;
}
private void RenameColumn ()
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
var currentCol = tableView.Table.Columns[tableView.SelectedColumn];
var currentCol = tableView.Table.Columns [tableView.SelectedColumn];
if(GetText("Rename Column","Name:",currentCol.ColumnName,out string newName)) {
if (GetText ("Rename Column", "Name:", currentCol.ColumnName, out string newName)) {
currentCol.ColumnName = newName;
tableView.Update();
tableView.Update ();
}
}
private void DeleteColum()
private void DeleteColum ()
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
if(tableView.SelectedColumn == -1) {
MessageBox.ErrorQuery("No Column","No column selected", "Ok");
if (tableView.SelectedColumn == -1) {
MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
return;
}
try {
tableView.Table.Columns.RemoveAt(tableView.SelectedColumn);
tableView.Update();
tableView.Table.Columns.RemoveAt (tableView.SelectedColumn);
tableView.Update ();
} catch (Exception ex) {
MessageBox.ErrorQuery("Could not remove column",ex.Message, "Ok");
MessageBox.ErrorQuery ("Could not remove column", ex.Message, "Ok");
}
}
private void MoveColumn ()
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
if(tableView.SelectedColumn == -1) {
MessageBox.ErrorQuery("No Column","No column selected", "Ok");
if (tableView.SelectedColumn == -1) {
MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
return;
}
try{
var currentCol = tableView.Table.Columns[tableView.SelectedColumn];
try {
if(GetText("Move Column","New Index:",currentCol.Ordinal.ToString(),out string newOrdinal)) {
var currentCol = tableView.Table.Columns [tableView.SelectedColumn];
var newIdx = Math.Min(Math.Max(0,int.Parse(newOrdinal)),tableView.Table.Columns.Count-1);
if (GetText ("Move Column", "New Index:", currentCol.Ordinal.ToString (), out string newOrdinal)) {
currentCol.SetOrdinal(newIdx);
var newIdx = Math.Min (Math.Max (0, int.Parse (newOrdinal)), tableView.Table.Columns.Count - 1);
tableView.SetSelection(newIdx,tableView.SelectedRow,false);
tableView.EnsureSelectedCellIsVisible();
tableView.SetNeedsDisplay();
currentCol.SetOrdinal (newIdx);
tableView.SetSelection (newIdx, tableView.SelectedRow, false);
tableView.EnsureSelectedCellIsVisible ();
tableView.SetNeedsDisplay ();
}
}catch(Exception ex)
{
MessageBox.ErrorQuery("Error moving column",ex.Message, "Ok");
} catch (Exception ex) {
MessageBox.ErrorQuery ("Error moving column", ex.Message, "Ok");
}
}
private void Sort (bool asc)
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
if(tableView.SelectedColumn == -1) {
MessageBox.ErrorQuery("No Column","No column selected", "Ok");
if (tableView.SelectedColumn == -1) {
MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
return;
}
var colName = tableView.Table.Columns[tableView.SelectedColumn].ColumnName;
var colName = tableView.Table.Columns [tableView.SelectedColumn].ColumnName;
tableView.Table.DefaultView.Sort = colName + (asc ? " asc" : " desc");
tableView.Table = tableView.Table.DefaultView.ToTable();
tableView.Table = tableView.Table.DefaultView.ToTable ();
}
private void MoveRow ()
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
if(tableView.SelectedRow == -1) {
MessageBox.ErrorQuery("No Rows","No row selected", "Ok");
if (tableView.SelectedRow == -1) {
MessageBox.ErrorQuery ("No Rows", "No row selected", "Ok");
return;
}
try{
try {
int oldIdx = tableView.SelectedRow;
var currentRow = tableView.Table.Rows[oldIdx];
var currentRow = tableView.Table.Rows [oldIdx];
if(GetText("Move Row","New Row:",oldIdx.ToString(),out string newOrdinal)) {
if (GetText ("Move Row", "New Row:", oldIdx.ToString (), out string newOrdinal)) {
var newIdx = Math.Min(Math.Max(0,int.Parse(newOrdinal)),tableView.Table.Rows.Count-1);
var newIdx = Math.Min (Math.Max (0, int.Parse (newOrdinal)), tableView.Table.Rows.Count - 1);
if(newIdx == oldIdx)
if (newIdx == oldIdx)
return;
var arrayItems = currentRow.ItemArray;
tableView.Table.Rows.Remove(currentRow);
tableView.Table.Rows.Remove (currentRow);
// Removing and Inserting the same DataRow seems to result in it loosing its values so we have to create a new instance
var newRow = tableView.Table.NewRow();
var newRow = tableView.Table.NewRow ();
newRow.ItemArray = arrayItems;
tableView.Table.Rows.InsertAt(newRow,newIdx);
tableView.SetSelection(tableView.SelectedColumn,newIdx,false);
tableView.EnsureSelectedCellIsVisible();
tableView.SetNeedsDisplay();
tableView.Table.Rows.InsertAt (newRow, newIdx);
tableView.SetSelection (tableView.SelectedColumn, newIdx, false);
tableView.EnsureSelectedCellIsVisible ();
tableView.SetNeedsDisplay ();
}
}catch(Exception ex)
{
MessageBox.ErrorQuery("Error moving column",ex.Message, "Ok");
} catch (Exception ex) {
MessageBox.ErrorQuery ("Error moving column", ex.Message, "Ok");
}
}
@@ -271,43 +268,43 @@ namespace UICatalog.Scenarios {
return;
}
var col = tableView.Table.Columns[tableView.SelectedColumn];
var col = tableView.Table.Columns [tableView.SelectedColumn];
var style = tableView.Style.GetOrCreateColumnStyle(col);
var style = tableView.Style.GetOrCreateColumnStyle (col);
style.Alignment = newAlignment;
miLeft.Checked = style.Alignment == TextAlignment.Left;
miRight.Checked = style.Alignment == TextAlignment.Right;
miCentered.Checked = style.Alignment == TextAlignment.Centered;
tableView.Update();
miCentered.Checked = style.Alignment == TextAlignment.Centered;
tableView.Update ();
}
private void SetFormat()
private void SetFormat ()
{
if (NoTableLoaded ()) {
return;
}
var col = tableView.Table.Columns[tableView.SelectedColumn];
var col = tableView.Table.Columns [tableView.SelectedColumn];
if(col.DataType == typeof(string)) {
MessageBox.ErrorQuery("Cannot Format Column","String columns cannot be Formatted, try adding a new column to the table with a date/numerical Type","Ok");
if (col.DataType == typeof (string)) {
MessageBox.ErrorQuery ("Cannot Format Column", "String columns cannot be Formatted, try adding a new column to the table with a date/numerical Type", "Ok");
return;
}
var style = tableView.Style.GetOrCreateColumnStyle(col);
var style = tableView.Style.GetOrCreateColumnStyle (col);
if(GetText("Format","Pattern:",style.Format ?? "",out string newPattern)) {
if (GetText ("Format", "Pattern:", style.Format ?? "", out string newPattern)) {
style.Format = newPattern;
tableView.Update();
tableView.Update ();
}
}
private bool NoTableLoaded ()
{
if(tableView.Table == null) {
MessageBox.ErrorQuery("No Table Loaded","No table has currently be opened","Ok");
if (tableView.Table == null) {
MessageBox.ErrorQuery ("No Table Loaded", "No table has currently be opened", "Ok");
return true;
}
@@ -316,112 +313,114 @@ namespace UICatalog.Scenarios {
private void AddRow ()
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
var newRow = tableView.Table.NewRow();
var newRow = tableView.Table.NewRow ();
var newRowIdx = Math.Min(Math.Max(0,tableView.SelectedRow+1),tableView.Table.Rows.Count);
var newRowIdx = Math.Min (Math.Max (0, tableView.SelectedRow + 1), tableView.Table.Rows.Count);
tableView.Table.Rows.InsertAt(newRow,newRowIdx);
tableView.Update();
tableView.Table.Rows.InsertAt (newRow, newRowIdx);
tableView.Update ();
}
private void AddColumn ()
{
if(NoTableLoaded()) {
if (NoTableLoaded ()) {
return;
}
if(GetText("Enter column name","Name:","",out string colName)) {
if (GetText ("Enter column name", "Name:", "", out string colName)) {
var col = new DataColumn(colName);
var col = new DataColumn (colName);
var newColIdx = Math.Min(Math.Max(0,tableView.SelectedColumn + 1),tableView.Table.Columns.Count);
int result = MessageBox.Query(40,15,"Column Type","Pick a data type for the column",new ustring[]{"Date","Integer","Double","Text","Cancel"});
var newColIdx = Math.Min (Math.Max (0, tableView.SelectedColumn + 1), tableView.Table.Columns.Count);
if(result <= -1 || result >= 4)
int result = MessageBox.Query ("Column Type", "Pick a data type for the column", new ustring [] { "Date", "Integer", "Double", "Text", "Cancel" });
if (result <= -1 || result >= 4)
return;
switch(result) {
case 0: col.DataType = typeof(DateTime);
break;
case 1: col.DataType = typeof(int);
break;
case 2: col.DataType = typeof(double);
break;
case 3: col.DataType = typeof(string);
break;
switch (result) {
case 0:
col.DataType = typeof (DateTime);
break;
case 1:
col.DataType = typeof (int);
break;
case 2:
col.DataType = typeof (double);
break;
case 3:
col.DataType = typeof (string);
break;
}
tableView.Table.Columns.Add(col);
col.SetOrdinal(newColIdx);
tableView.Update();
tableView.Table.Columns.Add (col);
col.SetOrdinal (newColIdx);
tableView.Update ();
}
}
private void Save()
private void Save ()
{
if(tableView.Table == null || string.IsNullOrWhiteSpace(currentFile)) {
MessageBox.ErrorQuery("No file loaded","No file is currently loaded","Ok");
if (tableView.Table == null || string.IsNullOrWhiteSpace (currentFile)) {
MessageBox.ErrorQuery ("No file loaded", "No file is currently loaded", "Ok");
return;
}
var sb = new StringBuilder();
var sb = new StringBuilder ();
sb.AppendLine(string.Join(",",tableView.Table.Columns.Cast<DataColumn>().Select(c=>c.ColumnName)));
sb.AppendLine (string.Join (",", tableView.Table.Columns.Cast<DataColumn> ().Select (c => c.ColumnName)));
foreach(DataRow row in tableView.Table.Rows) {
sb.AppendLine(string.Join(",",row.ItemArray));
foreach (DataRow row in tableView.Table.Rows) {
sb.AppendLine (string.Join (",", row.ItemArray));
}
File.WriteAllText(currentFile,sb.ToString());
File.WriteAllText (currentFile, sb.ToString ());
}
private void Open()
private void Open ()
{
var ofd = new FileDialog("Select File","Open","File","Select a CSV file to open (does not support newlines, escaping etc)");
ofd.AllowedFileTypes = new string[]{".csv" };
var ofd = new FileDialog ("Select File", "Open", "File", "Select a CSV file to open (does not support newlines, escaping etc)");
ofd.AllowedFileTypes = new string [] { ".csv" };
Application.Run(ofd);
if(!ofd.Canceled && !string.IsNullOrWhiteSpace(ofd.FilePath?.ToString()))
{
Open(ofd.FilePath.ToString());
Application.Run (ofd);
if (!ofd.Canceled && !string.IsNullOrWhiteSpace (ofd.FilePath?.ToString ())) {
Open (ofd.FilePath.ToString ());
}
}
private void Open(string filename)
private void Open (string filename)
{
int lineNumber = 0;
currentFile = null;
try {
var dt = new DataTable();
var lines = File.ReadAllLines(filename);
foreach(var h in lines[0].Split(',')){
dt.Columns.Add(h);
}
var dt = new DataTable ();
var lines = File.ReadAllLines (filename);
foreach(var line in lines.Skip(1)) {
lineNumber++;
dt.Rows.Add(line.Split(','));
foreach (var h in lines [0].Split (',')) {
dt.Columns.Add (h);
}
foreach (var line in lines.Skip (1)) {
lineNumber++;
dt.Rows.Add (line.Split (','));
}
tableView.Table = dt;
// Only set the current filename if we succesfully loaded the entire file
currentFile = filename;
}
catch(Exception ex) {
MessageBox.ErrorQuery("Open Failed",$"Error on line {lineNumber}{Environment.NewLine}{ex.Message}","Ok");
} catch (Exception ex) {
MessageBox.ErrorQuery ("Open Failed", $"Error on line {lineNumber}{Environment.NewLine}{ex.Message}", "Ok");
}
}
private void SetupScrollBar ()
@@ -445,45 +444,42 @@ namespace UICatalog.Scenarios {
};*/
tableView.DrawContent += (e) => {
_scrollBar.Size = tableView.Table?.Rows?.Count ??0;
_scrollBar.Size = tableView.Table?.Rows?.Count ?? 0;
_scrollBar.Position = tableView.RowOffset;
// _scrollBar.OtherScrollBarView.Size = _listView.Maxlength - 1;
// _scrollBar.OtherScrollBarView.Position = _listView.LeftItem;
// _scrollBar.OtherScrollBarView.Size = _listView.Maxlength - 1;
// _scrollBar.OtherScrollBarView.Position = _listView.LeftItem;
_scrollBar.Refresh ();
};
}
private void TableViewKeyPress (View.KeyEventEventArgs e)
{
if(e.KeyEvent.Key == Key.DeleteChar){
if (e.KeyEvent.Key == Key.DeleteChar) {
if(tableView.FullRowSelect)
{
if (tableView.FullRowSelect) {
// Delete button deletes all rows when in full row mode
foreach(int toRemove in tableView.GetAllSelectedCells().Select(p=>p.Y).Distinct().OrderByDescending(i=>i))
tableView.Table.Rows.RemoveAt(toRemove);
}
else{
foreach (int toRemove in tableView.GetAllSelectedCells ().Select (p => p.Y).Distinct ().OrderByDescending (i => i))
tableView.Table.Rows.RemoveAt (toRemove);
} else {
// otherwise set all selected cells to null
foreach(var pt in tableView.GetAllSelectedCells())
{
tableView.Table.Rows[pt.Y][pt.X] = DBNull.Value;
foreach (var pt in tableView.GetAllSelectedCells ()) {
tableView.Table.Rows [pt.Y] [pt.X] = DBNull.Value;
}
}
tableView.Update();
tableView.Update ();
e.Handled = true;
}
}
private void ClearColumnStyles ()
{
tableView.Style.ColumnStyles.Clear();
tableView.Update();
tableView.Style.ColumnStyles.Clear ();
tableView.Update ();
}
private void CloseExample ()
{
@@ -494,7 +490,7 @@ namespace UICatalog.Scenarios {
{
Application.RequestStop ();
}
private bool GetText(string title, string label, string initialText, out string enteredText)
private bool GetText (string title, string label, string initialText, out string enteredText)
{
bool okPressed = false;
@@ -504,44 +500,42 @@ namespace UICatalog.Scenarios {
cancel.Clicked += () => { Application.RequestStop (); };
var d = new Dialog (title, 60, 20, ok, cancel);
var lbl = new Label() {
var lbl = new Label () {
X = 0,
Y = 1,
Text = label
};
var tf = new TextField()
{
Text = initialText,
X = 0,
Y = 2,
Width = Dim.Fill()
};
d.Add (lbl,tf);
tf.SetFocus();
var tf = new TextField () {
Text = initialText,
X = 0,
Y = 2,
Width = Dim.Fill ()
};
d.Add (lbl, tf);
tf.SetFocus ();
Application.Run (d);
enteredText = okPressed? tf.Text.ToString() : null;
enteredText = okPressed ? tf.Text.ToString () : null;
return okPressed;
}
private void EditCurrentCell (TableView.CellActivatedEventArgs e)
{
if(e.Table == null)
if (e.Table == null)
return;
var oldValue = e.Table.Rows[e.Row][e.Col].ToString();
var oldValue = e.Table.Rows [e.Row] [e.Col].ToString ();
if(GetText("Enter new value",e.Table.Columns[e.Col].ColumnName,oldValue, out string newText)) {
if (GetText ("Enter new value", e.Table.Columns [e.Col].ColumnName, oldValue, out string newText)) {
try {
e.Table.Rows[e.Row][e.Col] = string.IsNullOrWhiteSpace(newText) ? DBNull.Value : (object)newText;
e.Table.Rows [e.Row] [e.Col] = string.IsNullOrWhiteSpace (newText) ? DBNull.Value : (object)newText;
} catch (Exception ex) {
MessageBox.ErrorQuery (60, 20, "Failed to set text", ex.Message, "Ok");
}
catch(Exception ex) {
MessageBox.ErrorQuery(60,20,"Failed to set text", ex.Message,"Ok");
}
tableView.Update();
tableView.Update ();
}
}
}