Creado boton Duplicar

This commit is contained in:
Miguel 2024-05-20 14:05:34 +02:00
parent 0d18cae40a
commit 334b1a2fd8
6 changed files with 132 additions and 31 deletions

View File

@ -20,6 +20,7 @@
<None Remove="Icons\borrar.png" />
<None Remove="Icons\connect.png" />
<None Remove="Icons\disconnect.png" />
<None Remove="Icons\duplicate.png" />
<None Remove="Icons\fotocelula.png" />
<None Remove="Icons\save.png" />
<None Remove="Icons\start.png" />
@ -64,6 +65,7 @@
<Resource Include="Icons\borrar.png" />
<Resource Include="Icons\connect.png" />
<Resource Include="Icons\disconnect.png" />
<Resource Include="Icons\duplicate.png" />
<Resource Include="Icons\fotocelula.png" />
<Resource Include="Icons\save.png" />
<Resource Include="Icons\start.png" />

BIN
Icons/duplicate.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -58,6 +58,8 @@ namespace CtrEditor
public ICommand TBDisconnectPLCCommand { get; }
public ICommand TBEliminarUserControlCommand { get; }
public ICommand TBDuplicarUserControlCommand { get; }
public ICommand OpenWorkDirectoryCommand { get; }
@ -246,6 +248,7 @@ namespace CtrEditor
TBDisconnectPLCCommand = new RelayCommand(DisconnectPLC, () => IsConnected);
TBEliminarUserControlCommand = new RelayCommand(EliminarUserControl, () => habilitarEliminarUserControl);
TBDuplicarUserControlCommand = new RelayCommand(DuplicarUserControl, () => habilitarEliminarUserControl);
stopwatch_PLCRefresh = new Stopwatch();
stopwatch_SimRefresh = new Stopwatch();
@ -320,6 +323,45 @@ namespace CtrEditor
}
}
private void DuplicarUserControl()
{
if (SelectedItemOsList is osBase objDuplicar)
{
StopSimulation();
DisconnectPLC();
objDuplicar.SalvarDatosNoSerializables();
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.All
};
try
{
// Serializar
var serializedData = JsonConvert.SerializeObject(objDuplicar, settings);
// Duplicar
var NuevoObjetoDuplicado = JsonConvert.DeserializeObject<osBase>(serializedData, settings);
if (NuevoObjetoDuplicado != null)
{
NuevoObjetoDuplicado.Nombre += "_Duplicado";
ObjetosSimulables.Add(NuevoObjetoDuplicado);
CrearUserControlDesdeObjetoSimulable(NuevoObjetoDuplicado);
}
}
catch
{
// Log error or handle it accordingly
}
finally {
objDuplicar.RestaurarDatosNoSerializables();
}
}
}
private void EliminarUserControl()
{
if (SelectedItemOsList is osBase objEliminar)
@ -458,25 +500,21 @@ namespace CtrEditor
if (_selectedImage != null)
{
StopSimulation();
PLCViewModel.Disconnect();
DisconnectPLC();
// Crear copias temporales de las propiedades que serán anuladas
var tempVisualRepresentations = new Dictionary<osBase, UserControl>();
var tempSimulationManagers = new Dictionary<osBase, SimulationManagerFP>();
var tempMainViewModels = new Dictionary<osBase, MainViewModel>();
// Ruta del archivo a ser guardado
var path = datosDeTrabajo.ObtenerPathImagenConExtension(_selectedImage, ".json");
// Verificar si el archivo ya existe y crear un respaldo
if (File.Exists(path))
{
var backupPath = Path.ChangeExtension(path, ".bak");
File.Copy(path, backupPath, true); // Copia el archivo existente a un nuevo archivo .bak, sobrescribiendo si es necesario
}
foreach (var obj in ObjetosSimulables)
{
// Guardar referencias temporales
tempVisualRepresentations[obj] = obj.VisualRepresentation;
tempSimulationManagers[obj] = obj.simulationManager;
tempMainViewModels[obj] = obj._mainViewModel;
// Anular propiedades para la serialización
obj.VisualRepresentation = null;
obj.simulationManager = null;
obj._mainViewModel = null;
}
obj.SalvarDatosNoSerializables();
var settings = new JsonSerializerSettings
{
@ -495,26 +533,20 @@ namespace CtrEditor
// Serializar
var serializedData = JsonConvert.SerializeObject(dataToSerialize, settings);
File.WriteAllText(datosDeTrabajo.ObtenerPathImagenConExtension(_selectedImage, ".json"), serializedData);
File.WriteAllText(path, serializedData); // Escribir el nuevo archivo JSON
// Restaurar las propiedades originales de los objetos
foreach (var obj in ObjetosSimulables)
{
obj.VisualRepresentation = tempVisualRepresentations[obj];
obj.simulationManager = tempSimulationManagers[obj];
obj._mainViewModel = tempMainViewModels[obj];
obj.RestaurarDatosNoSerializables();
}
}
}
public void LoadStateObjetosSimulables()
{
try
{
StopSimulation();
PLCViewModel.Disconnect();
DisconnectPLC();
ObjetosSimulables.Clear();
simulationManager.Clear();
if (_selectedImage != null)

View File

@ -54,8 +54,8 @@
<!-- Margen superior para el menú -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" MinWidth="100"/>
<ColumnDefinition Width="4*" MinWidth="200"/>
<ColumnDefinition Width="1*" MinWidth="100"/>
<ColumnDefinition Width="8*" MinWidth="200"/>
<ColumnDefinition Width="2*" MinWidth="100"/>
</Grid.ColumnDefinitions>
<!-- Primera Columna -->
@ -177,6 +177,12 @@
<TextBlock Text="Eliminar"/>
</StackPanel>
</Button>
<Button Command="{Binding TBDuplicarUserControlCommand}" ToolTip="Duplicar Control">
<StackPanel>
<Image Source="Icons/duplicate.png" Width="16" Height="16"/>
<TextBlock Text="Duplicar"/>
</StackPanel>
</Button>
</ToolBar>
</ToolBarTray>

View File

@ -207,18 +207,40 @@ namespace CtrEditor.ObjetosSim
{
TiempoRestante = 3600 / (Botellas_hora * (Velocidad_actual_percentual / 100.0f));
var UltimaBotellla = GetLastElement<osBotella>(Botellas);
if (UltimaBotellla == null || (UltimaBotellla != null && !(UltimaBotellla.Left == Left && UltimaBotellla.Top == Top)))
var X = Left + OffsetLeftSalida;
var Y = Top + OffsetTopSalida;
var UltimaBotella = GetLastElement<osBotella>(Botellas);
if (UltimaBotella == null)
{
var Botella = _mainViewModel.CrearObjetoSimulable(typeof(osBotella), Left + OffsetLeftSalida, Top + OffsetTopSalida);
Botella.AutoCreated = true;
Botellas.Add((osBotella)Botella);
// No hay botellas, se puede crear una nueva directamente
var nuevaBotella = _mainViewModel.CrearObjetoSimulable(typeof(osBotella), X, Y);
((osBotella)nuevaBotella).Diametro = Diametro_botella;
nuevaBotella.AutoCreated = true;
Botellas.Add((osBotella)nuevaBotella);
}
else
{
// Calcular la distancia entre el centro de la última botella y la nueva posición
float distancia = (float)Math.Sqrt(Math.Pow(UltimaBotella.Left - X, 2) + Math.Pow(UltimaBotella.Top - Y, 2));
float distanciaMinima = Diametro_botella / 2; // Asumiendo que el diámetro de la nueva botella es similar
if (distancia > distanciaMinima)
{
var nuevaBotella = _mainViewModel.CrearObjetoSimulable(typeof(osBotella), X, Y);
((osBotella)nuevaBotella).Diametro = Diametro_botella;
nuevaBotella.AutoCreated = true;
Botellas.Add((osBotella)nuevaBotella);
}
}
}
}
else
{
TiempoRestante = 0;
}
}
public override void ucLoaded()
{
// El UserControl ya se ha cargado y podemos obtener las coordenadas para

View File

@ -19,6 +19,7 @@ using Microsoft.Xna.Framework;
using FarseerPhysics.Dynamics;
using Siemens.Simatic.Simulation.Runtime;
using System.Windows.Media.Imaging;
using System.Windows.Input;
namespace CtrEditor.ObjetosSim
{
@ -41,6 +42,28 @@ namespace CtrEditor.ObjetosSim
int ZIndex();
}
public class DataSaveToSerialize
{
private MainViewModel? _mainViewModel;
private UserControl? VisualRepresentation;
private SimulationManagerFP? simulationManager;
public DataSaveToSerialize(MainViewModel a, UserControl b, SimulationManagerFP c )
{
_mainViewModel = a;
VisualRepresentation = b;
simulationManager = c;
}
public void DataRestoreAfterSerialize(out MainViewModel a, out UserControl b, out SimulationManagerFP c)
{
a = _mainViewModel;
b = VisualRepresentation;
c = simulationManager;
}
}
public abstract class osBase : INotifyPropertyChanged
{
public virtual string Nombre { get; set; } = "osBase";
@ -52,6 +75,9 @@ namespace CtrEditor.ObjetosSim
public bool AutoCreated = false;
public bool RemoverDesdeSimulacion = false; // La simulacion indica que se debe remover
[JsonIgnore]
private DataSaveToSerialize DataSave;
[JsonIgnore]
protected UserControl? _visualRepresentation = null;
@ -74,6 +100,19 @@ namespace CtrEditor.ObjetosSim
[JsonIgnore]
public SimulationManagerFP simulationManager;
public void SalvarDatosNoSerializables()
{
DataSave = new DataSaveToSerialize(_mainViewModel,_visualRepresentation,simulationManager);
_mainViewModel = null;
_visualRepresentation = null;
simulationManager = null;
}
public void RestaurarDatosNoSerializables()
{
if (DataSave == null) return;
DataSave.DataRestoreAfterSerialize(out _mainViewModel,out _visualRepresentation,out simulationManager);
}
protected osBase ObtenerLink(string NameLink, Type tipoOsBase)
{
if (!string.IsNullOrEmpty(NameLink) && _mainViewModel != null)