Probado - Reducido parametros de ROI

This commit is contained in:
Miguel 2024-04-15 13:38:56 +02:00
parent a86a84bd9f
commit 24313ada54
6 changed files with 150 additions and 159 deletions

View File

@ -38,5 +38,24 @@ namespace ROIEditor
{ {
return Path.Combine(strDirectorioTrabajo, "roieditor.db"); return Path.Combine(strDirectorioTrabajo, "roieditor.db");
} }
public string PNG_Folther_Path()
{
return strDirectorioTrabajo;
}
public string Json_Extension_Path()
{
string jsonPath = Path.ChangeExtension(NombreImagenEditando, ".json");
var imagePath = Path.Combine(strDirectorioTrabajo, jsonPath);
return imagePath;
}
public string PNG_Extension_Path()
{
string jsonPath = Path.ChangeExtension(NombreImagenEditando, ".png");
var imagePath = Path.Combine(PNG_Folther_Path(), jsonPath);
return imagePath;
}
} }
} }

98
ItemPersistente.cs Normal file
View File

@ -0,0 +1,98 @@
using System.Text.Json;
using Microsoft.Data.Sqlite;
namespace ROIEditor
{
public class ItemPersistente<T> where T : new()
{
private readonly string connectionString;
private readonly string tableName;
private T data; // Ahora 'data' es un objeto de tipo T
public string Clave;
public ItemPersistente(string dbPath, string tableName)
{
connectionString = $"Data Source={dbPath}";
this.tableName = tableName;
InitializeDatabase();
data = new T(); // Inicializa 'data' con el constructor por defecto de T
}
private void InitializeDatabase()
{
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $@"
CREATE TABLE IF NOT EXISTS {tableName} (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Clave TEXT UNIQUE,
SerializedData TEXT
)";
command.ExecuteNonQuery();
}
}
public void Save() { Save(Clave); }
public void Save(string clave)
{
if (clave == null) return;
Clave = clave;
string serializedData = JsonSerializer.Serialize(data);
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $@"
INSERT INTO {tableName} (Clave, SerializedData)
VALUES ($Clave, $SerializedData)
ON CONFLICT(Clave) DO UPDATE SET
SerializedData = excluded.SerializedData";
command.Parameters.AddWithValue("$Clave", clave);
command.Parameters.AddWithValue("$SerializedData", serializedData);
command.ExecuteNonQuery();
}
}
public bool Load() { return Load(Clave); }
public bool Load(string clave)
{
if (clave == null) return false;
Clave = clave;
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $"SELECT SerializedData FROM {tableName} WHERE Clave = $Clave";
command.Parameters.AddWithValue("$Clave", clave);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
string serializedData = reader.GetString(0);
data = JsonSerializer.Deserialize<T>(serializedData);
return true;
}
data = new();
return false;
}
}
}
public T Get()
{
return data;
}
public void Set(T newData)
{
data = newData;
}
}
}

View File

@ -1,12 +1,5 @@
using System; using System.Text.Json;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using System.ComponentModel;
namespace ROIEditor namespace ROIEditor
{ {
@ -130,97 +123,6 @@ namespace ROIEditor
} }
} }
public class ItemPersistente<T> where T : new()
{
private readonly string connectionString;
private readonly string tableName;
private T data; // Ahora 'data' es un objeto de tipo T
public string Clave;
public ItemPersistente(string dbPath, string tableName)
{
connectionString = $"Data Source={dbPath}";
this.tableName = tableName;
InitializeDatabase();
data = new T(); // Inicializa 'data' con el constructor por defecto de T
}
private void InitializeDatabase()
{
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $@"
CREATE TABLE IF NOT EXISTS {tableName} (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Clave TEXT UNIQUE,
SerializedData TEXT
)";
command.ExecuteNonQuery();
}
}
public void Save() { Save(Clave); }
public void Save(string clave)
{
if (clave == null) return;
Clave = clave;
string serializedData = JsonSerializer.Serialize(data);
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $@"
INSERT INTO {tableName} (Clave, SerializedData)
VALUES ($Clave, $SerializedData)
ON CONFLICT(Clave) DO UPDATE SET
SerializedData = excluded.SerializedData";
command.Parameters.AddWithValue("$Clave", clave);
command.Parameters.AddWithValue("$SerializedData", serializedData);
command.ExecuteNonQuery();
}
}
public bool Load() { return Load(Clave); }
public bool Load(string clave)
{
if (clave == null) return false;
Clave = clave;
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $"SELECT SerializedData FROM {tableName} WHERE Clave = $Clave";
command.Parameters.AddWithValue("$Clave", clave);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
string serializedData = reader.GetString(0);
data = JsonSerializer.Deserialize<T>(serializedData);
return true;
}
data = new();
return false;
}
}
}
public T Get()
{
return data;
}
public void Set(T newData)
{
data = newData;
}
}
} }

View File

@ -5,7 +5,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ROIEditor" xmlns:local="clr-namespace:ROIEditor"
mc:Ignorable="d" mc:Ignorable="d"
Title="Editor de ROI" Height="1000" Width="1600"> Title="Editor de ROI" Height="1000" Width="1600" HorizontalAlignment="Center" VerticalAlignment="Center">
<Window.Resources> <Window.Resources>
<Style x:Key="TextBoxPlaceholderStyle" TargetType="TextBox"> <Style x:Key="TextBoxPlaceholderStyle" TargetType="TextBox">
<Setter Property="Template"> <Setter Property="Template">
@ -43,12 +43,13 @@
<RowDefinition Height="1*"/> <RowDefinition Height="1*"/>
<!-- Esta fila ocupará 2/3 del espacio disponible --> <!-- Esta fila ocupará 2/3 del espacio disponible -->
</Grid.RowDefinitions> </Grid.RowDefinitions>
<ListBox x:Name="ListaFunciones" Grid.Row="0" Margin="0,0,0,5"> <ListBox x:Name="ListaImagenes" Grid.Row="0" Margin="0,5,0,0">
<!-- Aquí irán los elementos de la lista de funciones -->
</ListBox>
<ListBox x:Name="ListaImagenes" Grid.Row="1" Margin="0,5,0,0">
<!-- Aquí irán los elementos de la lista de imágenes --> <!-- Aquí irán los elementos de la lista de imágenes -->
</ListBox> </ListBox>
<ListBox x:Name="ListaFunciones" Grid.Row="1" Margin="0,0,0,5">
<!-- Aquí irán los elementos de la lista de funciones -->
</ListBox>
</Grid> </Grid>
@ -77,26 +78,18 @@
<Label Content="DX, DY:"/> <Label Content="DX, DY:"/>
<TextBox x:Name="ROI_dxdy" Margin="0,0,0,5"/> <TextBox x:Name="ROI_dxdy" Margin="0,0,0,5"/>
<!-- Nombre --> <!-- Nombre -->
<Label Content="Nombre:"/> <Label Content="Imagen:"/>
<TextBox x:Name="ROI_nombre" Margin="0,0,0,5"/> <ComboBox x:Name="ROI_imagen" Margin="0,0,0,5"/>
<CheckBox x:Name="AllImages" Content="Aplicar a Todas"/>
<!-- Código Numérico --> <!-- Código Numérico -->
<Label Content="Código Numérico:"/>
<TextBox x:Name="ROI_num" Margin="0,0,0,5"/>
<!-- Descripción --> <!-- Descripción -->
<Label Content="Descripción:"/> <Label Content="Descripción:"/>
<TextBox x:Name="ROI_descripcion" Margin="0,0,0,5"/> <TextBox x:Name="ROI_descripcion" Margin="0,0,0,5"/>
<!-- Campo de texto 1 -->
<Label Content="Campo de texto 1:"/>
<TextBox x:Name="ROI_text1" Margin="0,0,0,5"/>
<!-- Campo de texto 2 -->
<Label Content="Campo de texto 2:"/>
<TextBox x:Name="ROI_text2" Margin="0,0,0,5"/>
<!-- Campo de texto 3 -->
<Label Content="Campo de texto 3:"/>
<TextBox x:Name="ROI_text3" Margin="0,0,0,5"/>
<!-- Botones --> <!-- Botones -->
<Button x:Name="Guardar_ROI" Content="Guardar" Margin="0,0,0,5"/> <Button x:Name="Guardar_ROI" Content="Guardar" Margin="0,0,0,5"/>
<Button x:Name="Borrar_ROI" Content="Borrar ROI"/> <Button x:Name="Borrar_ROI" Content="Borrar ROI"/>
</StackPanel> </StackPanel>
</Grid> </Grid>

View File

@ -63,12 +63,7 @@ namespace ROIEditor
// Suscripción a los eventos LostFocus // Suscripción a los eventos LostFocus
ROI_xy.LostFocus += GuardarCambiosRoi; ROI_xy.LostFocus += GuardarCambiosRoi;
ROI_dxdy.LostFocus += GuardarCambiosRoi; ROI_dxdy.LostFocus += GuardarCambiosRoi;
ROI_nombre.LostFocus += GuardarCambiosRoi;
ROI_num.LostFocus += GuardarCambiosRoi;
ROI_descripcion.LostFocus += GuardarCambiosRoi; ROI_descripcion.LostFocus += GuardarCambiosRoi;
ROI_text1.LostFocus += GuardarCambiosRoi;
ROI_text2.LostFocus += GuardarCambiosRoi;
ROI_text3.LostFocus += GuardarCambiosRoi;
// Se carga el ultimo estado // Se carga el ultimo estado
Estado = EstadoTrabajo.CargarEstado(); Estado = EstadoTrabajo.CargarEstado();
@ -157,12 +152,16 @@ namespace ROIEditor
{ {
ROI_xy.Text = $"{selectedRoi.X}, {selectedRoi.Y}"; ROI_xy.Text = $"{selectedRoi.X}, {selectedRoi.Y}";
ROI_dxdy.Text = $"{selectedRoi.Width}, {selectedRoi.Height}"; ROI_dxdy.Text = $"{selectedRoi.Width}, {selectedRoi.Height}";
ROI_nombre.Text = selectedRoi.Nombre;
ROI_num.Text = selectedRoi.CodigoNumerico.ToString();
ROI_descripcion.Text = selectedRoi.Descripcion; ROI_descripcion.Text = selectedRoi.Descripcion;
ROI_text1.Text = selectedRoi.CampoTexto1;
ROI_text2.Text = selectedRoi.CampoTexto2; for (int i = 0; i < ROI_imagen.Items.Count; i++)
ROI_text3.Text = selectedRoi.CampoTexto3; {
if ((string)ROI_imagen.Items[i] == Estado.NombreImagenEditando)
{
ROI_imagen.SelectedIndex = i; // Selecciona el ítem que coincide con el último editado
break;
}
}
} }
private void ActualizarDatosROI(Roi selectedRoi) private void ActualizarDatosROI(Roi selectedRoi)
@ -177,12 +176,7 @@ namespace ROIEditor
selectedRoi.Y = int.Parse(xy[1].Trim()); selectedRoi.Y = int.Parse(xy[1].Trim());
selectedRoi.Width = int.Parse(dxdy[0].Trim()); selectedRoi.Width = int.Parse(dxdy[0].Trim());
selectedRoi.Height = int.Parse(dxdy[1].Trim()); selectedRoi.Height = int.Parse(dxdy[1].Trim());
selectedRoi.Nombre = ROI_nombre.Text;
selectedRoi.CodigoNumerico = int.TryParse(ROI_num.Text, out int codigo) ? codigo : 0;
selectedRoi.Descripcion = ROI_descripcion.Text; selectedRoi.Descripcion = ROI_descripcion.Text;
selectedRoi.CampoTexto1 = ROI_text1.Text;
selectedRoi.CampoTexto2 = ROI_text2.Text;
selectedRoi.CampoTexto3 = ROI_text3.Text;
// Aquí podrías llamar a un método que realice el guardado específico, si es necesario // Aquí podrías llamar a un método que realice el guardado específico, si es necesario
// Por ejemplo, actualizar la visualización del ROI o guardar en un archivo JSON // Por ejemplo, actualizar la visualización del ROI o guardar en un archivo JSON
@ -209,15 +203,20 @@ namespace ROIEditor
private void CargarImagenes() private void CargarImagenes()
{ {
// Asumiendo que las imágenes están en una carpeta "Imagenes" dentro del directorio de salida de tu aplicación // Asumiendo que las imágenes están en una carpeta "Imagenes" dentro del directorio de salida de tu aplicación
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Plantillas"); string folderPath = Estado.PNG_Folther_Path();
if (Directory.Exists(folderPath)) if (Directory.Exists(folderPath))
{ {
var archivosImagen = Directory.GetFiles(folderPath, "*.png"); // Asumiendo que buscas archivos .png var archivosImagen = Directory.GetFiles(folderPath, "*.png"); // Asumiendo que buscas archivos .png
ListaImagenes.Items.Clear();
ROI_imagen.Items.Clear();
foreach (var archivo in archivosImagen) foreach (var archivo in archivosImagen)
{ {
// Aquí simplemente añadimos el nombre del archivo a la lista, pero podrías querer añadir un objeto más complejo // Aquí simplemente añadimos el nombre del archivo a la lista, pero podrías querer añadir un objeto más complejo
ListaImagenes.Items.Add(Path.GetFileName(archivo)); ListaImagenes.Items.Add(Path.GetFileName(archivo));
ROI_imagen.Items.Add(Path.GetFileName(archivo));
} }
} }
else else
@ -423,18 +422,7 @@ namespace ROIEditor
Canvas.SetTop(imagenDeFondo, 0); Canvas.SetTop(imagenDeFondo, 0);
} }
public string PathPlantillasJson()
{
string jsonPath = Path.ChangeExtension(Estado.NombreImagenEditando, ".json");
var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "Plantillas", jsonPath);
return imagePath;
}
public string PathPlantillasPNG()
{
string jsonPath = Path.ChangeExtension(Estado.NombreImagenEditando, ".png");
var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "Plantillas", jsonPath);
return imagePath;
}
private void ListaImagenes_SelectionChanged(object sender, SelectionChangedEventArgs e) private void ListaImagenes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
@ -448,8 +436,7 @@ namespace ROIEditor
ListaDeROIs.Load(Estado.NombreImagenEditando); ListaDeROIs.Load(Estado.NombreImagenEditando);
ActualizarListaROIsEnUI(); ActualizarListaROIsEnUI();
var imagePath = PathPlantillasPNG(); CargarImagenEnTrabajo(Estado.PNG_Extension_Path());
CargarImagenEnTrabajo(imagePath);
CargarEstadoImagen(); CargarEstadoImagen();
} }

12
ROI.cs
View File

@ -21,13 +21,9 @@ namespace ROIEditor
public int Y { get; set; } public int Y { get; set; }
public int Width { get; set; } public int Width { get; set; }
public int Height { get; set; } public int Height { get; set; }
public string Nombre { get; set; }
public string NombreImagen { get; set; } public string NombreImagen { get; set; }
public int CodigoNumerico { get; set; }
public string Descripcion { get; set; } public string Descripcion { get; set; }
public string CampoTexto1 { get; set; }
public string CampoTexto2 { get; set; }
public string CampoTexto3 { get; set; }
// Constructor sin parámetros para facilitar la deserialización // Constructor sin parámetros para facilitar la deserialización
public Roi() { } public Roi() { }
@ -40,13 +36,9 @@ namespace ROIEditor
Y = y; Y = y;
Width = width; Width = width;
Height = height; Height = height;
Nombre = nombre;
NombreImagen = nombreImagen; NombreImagen = nombreImagen;
CodigoNumerico = codigoNumerico;
Descripcion = descripcion; Descripcion = descripcion;
CampoTexto1 = campoTexto1;
CampoTexto2 = campoTexto2;
CampoTexto3 = campoTexto3;
} }
public Roi(string nombreImagen, int x, int y, int width, int height) public Roi(string nombreImagen, int x, int y, int width, int height)
{ {