Separando los ObjetosSimulables para todas las paginas de los individuales

This commit is contained in:
Miguel 2024-06-05 22:27:53 +02:00
parent 84e7ac1c28
commit 84725cc8d6
4 changed files with 186 additions and 103 deletions

View File

@ -28,6 +28,16 @@ namespace CtrEditor
return null;
}
public string? ObtenerPathAllPages(string extension)
{
string folderPath = EstadoPersistente.Instance.directorio; // Usar directamente desde el Singleton
if (Directory.Exists(folderPath))
return Path.ChangeExtension(folderPath + "\\allpages", extension);
else return null;
}
public void CargarImagenes()
{
Imagenes.Clear();

View File

@ -16,6 +16,7 @@ using System.Reflection;
using CommunityToolkit.Mvvm.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid;
using System.Text.RegularExpressions;
using System.Windows.Data;
namespace CtrEditor
@ -147,9 +148,13 @@ namespace CtrEditor
[ObservableProperty]
private TipoSimulable selectedItem;
public ICollectionView ObjetosSimulablesFiltered { get; }
public ICollectionView ObjetosSimulablesAllPages { get; }
[ObservableProperty]
public ObservableCollection<osBase> objetosSimulables;
//
// Constructor
//
@ -160,6 +165,7 @@ namespace CtrEditor
datosDeTrabajo = new DatosDeTrabajo();
ObjetosSimulables = new ObservableCollection<osBase>();
ListaOsBase = new ObservableCollection<TipoSimulable>();
// Inicializa el PLCViewModel
@ -463,8 +469,49 @@ namespace CtrEditor
StopSimulation();
DisconnectPLC();
ObservableCollection<osBase> _objetosSimulables = new ObservableCollection<osBase>();
ObservableCollection<osBase> _objetosSimulablesAllPages = new ObservableCollection<osBase>();
foreach (var obj in ObjetosSimulables)
{
// Guardar referencias temporales
obj.SalvarDatosNoSerializables();
if (!obj.Enable_on_all_pages)
_objetosSimulables.Add(obj);
else
_objetosSimulablesAllPages.Add(obj);
}
// Salvar los objetos de la pagina actual
// Crear un objeto que incluya tanto los ObjetosSimulables como el UnitConverter y PLC_ConnectionData
var dataToSerialize = new SimulationData
{
ObjetosSimulables = _objetosSimulables,
UnitConverter = PixelToMeter.Instance.calc,
PLC_ConnectionData = PLCViewModel
};
// Ruta del archivo a ser guardado
var path = DatosDeTrabajo.ObtenerPathImagenConExtension(SelectedImage, ".json");
if (path != null)
SerializarYSalvar(dataToSerialize, path);
// Salvar los objetos de todas las paginas
// Ruta del archivo a ser guardado
path = DatosDeTrabajo.ObtenerPathAllPages(".json");
if (path!=null)
SerializarYSalvar(_objetosSimulablesAllPages, path);
// Restaurar las propiedades originales de los objetos
foreach (var obj in ObjetosSimulables)
obj.RestaurarDatosNoSerializables();
}
}
private void SerializarYSalvar(object listaObjetos, string path)
{
// Verificar si el archivo ya existe y crear un respaldo
if (File.Exists(path))
@ -473,9 +520,6 @@ namespace CtrEditor
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
obj.SalvarDatosNoSerializables();
var settings = new JsonSerializerSettings
{
@ -484,22 +528,9 @@ namespace CtrEditor
TypeNameHandling = TypeNameHandling.Auto
};
// Crear un objeto que incluya tanto los ObjetosSimulables como el UnitConverter y PLC_ConnectionData
var dataToSerialize = new SimulationData
{
ObjetosSimulables = ObjetosSimulables,
UnitConverter = PixelToMeter.Instance.calc,
PLC_ConnectionData = PLCViewModel
};
// Serializar
var serializedData = JsonConvert.SerializeObject(dataToSerialize, settings);
var serializedData = JsonConvert.SerializeObject(listaObjetos, settings);
File.WriteAllText(path, serializedData); // Escribir el nuevo archivo JSON
// Restaurar las propiedades originales de los objetos
foreach (var obj in ObjetosSimulables)
obj.RestaurarDatosNoSerializables();
}
}
public void LoadStateObjetosSimulables()
@ -512,10 +543,6 @@ namespace CtrEditor
simulationManager.Clear();
if (SelectedImage != null)
{
string jsonPath = datosDeTrabajo.ObtenerPathImagenConExtension(SelectedImage, ".json");
if (File.Exists(jsonPath))
{
string jsonString = File.ReadAllText(jsonPath);
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
@ -524,6 +551,12 @@ namespace CtrEditor
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
string jsonPath = datosDeTrabajo.ObtenerPathImagenConExtension(SelectedImage, ".json");
if (File.Exists(jsonPath))
{
string jsonString = File.ReadAllText(jsonPath);
var simulationData = JsonConvert.DeserializeObject<SimulationData>(jsonString, settings);
if (simulationData != null)
{
@ -540,13 +573,26 @@ namespace CtrEditor
// Re-register to the events
PLCViewModel.RefreshEvent += OnRefreshEvent;
}
}
jsonPath = DatosDeTrabajo.ObtenerPathAllPages(".json");
if (File.Exists(jsonPath))
{
string jsonString = File.ReadAllText(jsonPath);
ObservableCollection<osBase> _objetosSimulablesAllPages = new ObservableCollection<osBase>();
_objetosSimulablesAllPages = JsonConvert.DeserializeObject<ObservableCollection<osBase>>(jsonString, settings);
if (_objetosSimulablesAllPages != null)
foreach(var obj in _objetosSimulablesAllPages)
ObjetosSimulables.Add(obj);
}
// Recorrer la colección de objetos simulables
foreach (var objetoSimulable in ObjetosSimulables)
CrearUserControlDesdeObjetoSimulable(objetoSimulable);
}
}
}
}
catch { /* Consider logging the error or handling it appropriately */ }
}

View File

@ -1,43 +1,38 @@
<Window
xmlns:ctreditor="clr-namespace:CtrEditor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Siemens="clr-namespace:CtrEditor.Siemens"
xmlns:local="clr-namespace:CtrEditor"
<Window xmlns:ctreditor="clr-namespace:CtrEditor" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Siemens="clr-namespace:CtrEditor.Siemens" xmlns:local="clr-namespace:CtrEditor"
xmlns:uc="clr-namespace:CtrEditor.ObjetosSim.UserControls"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:ObjetosSim="clr-namespace:CtrEditor.ObjetosSim" x:Class="CtrEditor.MainWindow"
Height="900" Width="1600" WindowState="Maximized"
ResizeMode="CanResize" Title="{Binding directorioTrabajo}" Icon="/app2.png">
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:ObjetosSim="clr-namespace:CtrEditor.ObjetosSim" x:Class="CtrEditor.MainWindow" Height="900" Width="1600"
WindowState="Maximized" ResizeMode="CanResize" Title="{Binding directorioTrabajo}" Icon="/app2.png">
<Window.DataContext>
<ctreditor:MainViewModel/>
<ctreditor:MainViewModel />
</Window.DataContext>
<Window.Resources>
<!-- Style for Start/Stop Button -->
<Style x:Key="StartStopButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsSimulationRunning}" Value="True">
<Setter Property="Background" Value="LightGreen"/>
<Setter Property="Background" Value="LightGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- Style for Connect/Disconnect Button -->
<Style x:Key="ConnectDisconnectButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsConnected}" Value="True">
<Setter Property="Background" Value="LightGreen"/>
<Setter Property="Background" Value="LightGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
@ -55,27 +50,30 @@
<Grid Margin="0,20,0,0">
<!-- Margen superior para el menú -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" MinWidth="100"/>
<ColumnDefinition Width="8*" MinWidth="200"/>
<ColumnDefinition Width="2*" MinWidth="100"/>
<ColumnDefinition Width="1*" MinWidth="100" />
<ColumnDefinition Width="8*" MinWidth="200" />
<ColumnDefinition Width="2*" MinWidth="100" />
</Grid.ColumnDefinitions>
<!-- Primera Columna -->
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*" />
<RowDefinition Height="2*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox x:Name="ListaImagenes" Grid.Row="0" Margin="5" ItemsSource="{Binding ListaImagenes}" SelectedItem="{Binding SelectedImage}" />
<ListBox x:Name="ListaFunciones" Grid.Row="1" Margin="5" ItemsSource="{Binding ListaOsBase}" DisplayMemberPath="Nombre" SelectedItem="{Binding SelectedItem}">
<ListBox x:Name="ListaImagenes" Grid.Row="0" Margin="5" ItemsSource="{Binding ListaImagenes}"
SelectedItem="{Binding SelectedImage}" />
<ListBox x:Name="ListaFunciones" Grid.Row="1" Margin="5" ItemsSource="{Binding ListaOsBase}"
DisplayMemberPath="Nombre" SelectedItem="{Binding SelectedItem}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding ItemDoubleClickCommand}" CommandParameter="{Binding SelectedItem}"/>
<i:InvokeCommandAction Command="{Binding ItemDoubleClickCommand}"
CommandParameter="{Binding SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
<Siemens:PLCControl x:Name="PLCSim" Grid.Row="2" Margin="5" DataContext="{Binding PLCViewModel}"/>
<Siemens:PLCControl x:Name="PLCSim" Grid.Row="2" Margin="5" DataContext="{Binding PLCViewModel}" />
</Grid>
<!-- GridSplitter -->
<GridSplitter Grid.Column="0" Grid.Row="0" HorizontalAlignment="Right" Width="5" Background="LightGray" />
@ -89,44 +87,47 @@
<ToolBarTray Grid.Row="0">
<ToolBar>
<Button Command="{Binding TBStartSimulationCommand}" ToolTip="Iniciar Simulación" Style="{StaticResource StartStopButtonStyle}">
<Button Command="{Binding TBStartSimulationCommand}" ToolTip="Iniciar Simulación"
Style="{StaticResource StartStopButtonStyle}">
<StackPanel>
<Image Source="Icons/start.png" Width="16" Height="16"/>
<TextBlock Text="Iniciar"/>
<Image Source="Icons/start.png" Width="16" Height="16" />
<TextBlock Text="Iniciar" />
</StackPanel>
</Button>
<Button Command="{Binding TBStopSimulationCommand}" ToolTip="Detener Simulación">
<StackPanel>
<Image Source="Icons/stop.png" Width="16" Height="16"/>
<TextBlock Text="Detener"/>
<Image Source="Icons/stop.png" Width="16" Height="16" />
<TextBlock Text="Detener" />
</StackPanel>
</Button>
<Button Command="{Binding TBSaveCommand}" ToolTip="Guardar">
<StackPanel>
<Image Source="Icons/save.png" Width="16" Height="16"/>
<TextBlock Text="Guardar"/>
<Image Source="Icons/save.png" Width="16" Height="16" />
<TextBlock Text="Guardar" />
</StackPanel>
</Button>
<Button Command="{Binding TBConnectPLCCommand}" ToolTip="Conectar PLC" Style="{StaticResource ConnectDisconnectButtonStyle}">
<Button Command="{Binding TBConnectPLCCommand}" ToolTip="Conectar PLC"
Style="{StaticResource ConnectDisconnectButtonStyle}">
<StackPanel>
<Image Source="Icons/connect.png" Width="16" Height="16"/>
<TextBlock Text="Conectar"/>
<Image Source="Icons/connect.png" Width="16" Height="16" />
<TextBlock Text="Conectar" />
</StackPanel>
</Button>
<Button Command="{Binding TBDisconnectPLCCommand}" ToolTip="Desconectar PLC">
<StackPanel>
<Image Source="Icons/disconnect.png" Width="16" Height="16"/>
<TextBlock Text="Desconectar"/>
<Image Source="Icons/disconnect.png" Width="16" Height="16" />
<TextBlock Text="Desconectar" />
</StackPanel>
</Button>
</ToolBar>
</ToolBarTray>
<ScrollViewer Grid.Row="1" x:Name="ImagenEnTrabajoScrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" PanningMode="Both">
<ScrollViewer Grid.Row="1" x:Name="ImagenEnTrabajoScrollViewer" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" PanningMode="Both">
<Canvas x:Name="ImagenEnTrabajoCanvas" Margin="400">
<!-- El Margin puede ser ajustado según el espacio adicional que quieras proporcionar -->
<Canvas.LayoutTransform>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<ScaleTransform ScaleX="1" ScaleY="1" />
</Canvas.LayoutTransform>
</Canvas>
</ScrollViewer>
@ -138,37 +139,49 @@
<!-- Tercera Columna -->
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<!-- Altura ajustable para el ListBox -->
<RowDefinition Height="*" MinHeight="100" />
<!-- ListBox1 -->
<RowDefinition Height="Auto" />
<!-- Espacio para el GridSplitter -->
<RowDefinition Height="*" />
<!-- Altura ajustable para el PanelEdicion -->
<!-- GridSplitter -->
<RowDefinition Height="*" MinHeight="200" />
<!-- StackPanel -->
<RowDefinition Height="Auto" />
<!-- ToolBarTray -->
</Grid.RowDefinitions>
<!-- ListBox -->
<ListBox x:Name="ListaOs"
Grid.Row="0"
Margin="5"
ItemsSource="{Binding ObjetosSimulables}"
DisplayMemberPath="Nombre"
<ListBox x:Name="ListaOs" Grid.Row="0" Margin="5" ItemsSource="{Binding ObjetosSimulables}"
SelectedItem="{Binding SelectedItemOsList, Mode=TwoWay}"
SelectionChanged="ListaOs_SelectionChanged"/>
SelectionChanged="ListaOs_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Nombre}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Enable_on_all_pages}" Value="True">
<Setter Property="Foreground" Value="Blue" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=Enable_on_all_pages}" Value="False">
<Setter Property="Foreground" Value="Black" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- GridSplitter -->
<GridSplitter Grid.Row="1"
Height="5"
HorizontalAlignment="Stretch"
Background="Gray"
ResizeDirection="Rows"
VerticalAlignment="Center"/>
<GridSplitter Grid.Row="1" Height="5" HorizontalAlignment="Stretch" Background="Gray"
ResizeDirection="Rows" VerticalAlignment="Center" />
<!-- PanelEdicion -->
<xctk:PropertyGrid Grid.Row="2" Margin="5" x:Name="PanelEdicion" AutoGenerateProperties="False" SelectedObject="{Binding}">
<xctk:PropertyGrid Grid.Row="2" Margin="5" x:Name="PanelEdicion" AutoGenerateProperties="False"
SelectedObject="{Binding}">
<xctk:PropertyGrid.EditorDefinitions>
<!-- String -->
<xctk:EditorTemplateDefinition>
<xctk:EditorTemplateDefinition.TargetProperties>
@ -176,7 +189,8 @@
</xctk:EditorTemplateDefinition.TargetProperties>
<xctk:EditorTemplateDefinition.EditingTemplate>
<DataTemplate>
<TextBox Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Text="{Binding Value}" />
<TextBox Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
Text="{Binding Value}" />
</DataTemplate>
</xctk:EditorTemplateDefinition.EditingTemplate>
</xctk:EditorTemplateDefinition>
@ -185,7 +199,9 @@
<xctk:EditorTemplateDefinition TargetProperties="VelocidadActual">
<xctk:EditorTemplateDefinition.EditingTemplate>
<DataTemplate>
<xctk:SingleUpDown Increment="0.01" Background="Beige" Text="{Binding Value, Converter={StaticResource floatFormatter}}" FontWeight="Bold"/>
<xctk:SingleUpDown Increment="0.01" Background="Beige"
Text="{Binding Value, Converter={StaticResource floatFormatter}}"
FontWeight="Bold" />
</DataTemplate>
</xctk:EditorTemplateDefinition.EditingTemplate>
</xctk:EditorTemplateDefinition>
@ -197,7 +213,8 @@
</xctk:EditorTemplateDefinition.TargetProperties>
<xctk:EditorTemplateDefinition.EditingTemplate>
<DataTemplate>
<xctk:SingleUpDown Increment="0.01" Text="{Binding Value, Converter={StaticResource floatFormatter}}" />
<xctk:SingleUpDown Increment="0.01"
Text="{Binding Value, Converter={StaticResource floatFormatter}}" />
</DataTemplate>
</xctk:EditorTemplateDefinition.EditingTemplate>
</xctk:EditorTemplateDefinition>
@ -209,7 +226,7 @@
</xctk:EditorTemplateDefinition.TargetProperties>
<xctk:EditorTemplateDefinition.EditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Value, Converter={StaticResource doubleFormatter}}"/>
<TextBox Text="{Binding Value, Converter={StaticResource doubleFormatter}}" />
</DataTemplate>
</xctk:EditorTemplateDefinition.EditingTemplate>
</xctk:EditorTemplateDefinition>
@ -217,19 +234,18 @@
</xctk:PropertyGrid.EditorDefinitions>
</xctk:PropertyGrid>
<ToolBarTray Grid.Row="3">
<ToolBar>
<Button Command="{Binding TBEliminarUserControlCommand}" ToolTip="Eliminar Control">
<StackPanel>
<Image Source="Icons/borrar.png" Width="16" Height="16"/>
<TextBlock Text="Eliminar"/>
<Image Source="Icons/borrar.png" Width="16" Height="16" />
<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"/>
<Image Source="Icons/duplicate.png" Width="16" Height="16" />
<TextBlock Text="Duplicar" />
</StackPanel>
</Button>
</ToolBar>

View File

@ -86,6 +86,11 @@ namespace CtrEditor.ObjetosSim
[ObservableProperty]
private string group_Panel;
[ObservableProperty]
private bool enable_on_all_pages;
partial void OnTopChanged(float value)
{
CanvasSetTopinMeter(value);
@ -108,7 +113,13 @@ namespace CtrEditor.ObjetosSim
OnTimerAfterMovement();
});
}
/// <summary>
/// Este timer se usa para llamar a OnTimerAfterMovement luego de que han pasado 500ms sin que se
/// llame a ResetTimer.
/// Esto es util para no actualizar las simulaciones o controles mientras se esta moviendo aun el control.
/// Se debe hacer overrride de OnTimerAfterMovement y dentro de esta funcion llamar a la actualizacion que se
/// requiere hacer una vez terminado el movimiento del control por parte del usuario.
/// </summary>
public void ResetTimer()
{
if (timer == null)