Agregadas las opciones de consultar si guardar luego de hacer modificaciones y agregado el uso de la tecla Delete para borrar elementos

This commit is contained in:
Miguel 2025-02-13 16:52:33 +01:00
parent e63577e5c3
commit dc164e96ef
6 changed files with 143 additions and 10 deletions

View File

@ -20,6 +20,7 @@
<local:SubclassFilterConverter x:Key="SubclassFilterConverterosBuscarCoincidencias" <local:SubclassFilterConverter x:Key="SubclassFilterConverterosBuscarCoincidencias"
TargetType="{x:Type osExtraccion:osBuscarCoincidencias}" /> TargetType="{x:Type osExtraccion:osBuscarCoincidencias}" />
<local:SubclassFilterConverter x:Key="SubclassFilterConverterosVMMotor" TargetType="{x:Type os:osVMmotorSim}" /> <local:SubclassFilterConverter x:Key="SubclassFilterConverterosVMMotor" TargetType="{x:Type os:osVMmotorSim}" />
<local:UnsavedChangesConverter x:Key="UnsavedChangesConverter"/>
</Application.Resources> </Application.Resources>
</Application> </Application>

View File

@ -0,0 +1,27 @@
using System.Windows.Data;
using System.Windows;
namespace CtrEditor
{
public class UnsavedChangesConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string path)
{
var viewModel = Application.Current.MainWindow?.DataContext as MainViewModel;
if (viewModel?.HasUnsavedChanges == true)
{
return $"{path} *";
}
return path;
}
return string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

View File

@ -20,6 +20,7 @@ using CtrEditor.PopUps;
using System.Windows.Data; using System.Windows.Data;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Collections.Specialized;
namespace CtrEditor namespace CtrEditor
@ -104,11 +105,20 @@ namespace CtrEditor
[ObservableProperty] [ObservableProperty]
private bool isSimulationRunning; private bool isSimulationRunning;
[ObservableProperty]
private bool hasUnsavedChanges;
partial void OnIsSimulationRunningChanged(bool value) partial void OnIsSimulationRunningChanged(bool value)
{ {
CommandManager.InvalidateRequerySuggested(); // Notificar que el estado de los comandos ha cambiado CommandManager.InvalidateRequerySuggested(); // Notificar que el estado de los comandos ha cambiado
} }
partial void OnHasUnsavedChangesChanged(bool value)
{
// Notificar el cambio del título indirectamente a través de directorioTrabajo
OnPropertyChanged(nameof(directorioTrabajo));
}
public string directorioTrabajo public string directorioTrabajo
{ {
get => EstadoPersistente.Instance.directorio; get => EstadoPersistente.Instance.directorio;
@ -186,12 +196,29 @@ namespace CtrEditor
{ {
if (value != null) if (value != null)
{ {
if (HasUnsavedChanges)
{
var result = MessageBox.Show("There are unsaved changes. Do you want to save them?",
"Save Changes",
MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Cancel)
{
OnPropertyChanged(nameof(SelectedImage)); // Restore previous selection
return;
}
else if (result == MessageBoxResult.Yes)
{
SaveStateObjetosSimulables();
}
}
StopSimulation(); StopSimulation();
// SaveStateObjetosSimulables(); // Guarda el estado antes de cambiar la imagen ImageSelected?.Invoke(this, datosDeTrabajo.Imagenes[value]);
ImageSelected?.Invoke(this, datosDeTrabajo.Imagenes[value]); // Dispara el evento con la nueva ruta de imagen
LoadStateObjetosSimulables(); LoadStateObjetosSimulables();
EstadoPersistente.Instance.imagen = value; EstadoPersistente.Instance.imagen = value;
EstadoPersistente.Instance.GuardarEstado(); EstadoPersistente.Instance.GuardarEstado();
HasUnsavedChanges = false;
} }
} }
@ -281,6 +308,12 @@ namespace CtrEditor
stopwatch_Sim = new Stopwatch(); stopwatch_Sim = new Stopwatch();
stopwatch_Sim.Start(); stopwatch_Sim.Start();
ObjetosSimulables.CollectionChanged += (s, e) =>
{
if (e.Action != NotifyCollectionChangedAction.Move)
HasUnsavedChanges = true;
};
} }
private void OsListFilter_PropertyChanged(object? sender, PropertyChangedEventArgs e) private void OsListFilter_PropertyChanged(object? sender, PropertyChangedEventArgs e)
@ -329,8 +362,11 @@ namespace CtrEditor
if (NuevoOsBase != null) if (NuevoOsBase != null)
{ {
if (CrearUserControlDesdeObjetoSimulable(NuevoOsBase)) if (CrearUserControlDesdeObjetoSimulable(NuevoOsBase))
{
// Añadir el nuevo osBase a la colección de objetos simulables // Añadir el nuevo osBase a la colección de objetos simulables
ObjetosSimulables.Add(NuevoOsBase); ObjetosSimulables.Add(NuevoOsBase);
HasUnsavedChanges = true;
}
} }
return NuevoOsBase; return NuevoOsBase;
} }
@ -365,6 +401,7 @@ namespace CtrEditor
ObjetosSimulables.Remove(osObjeto); ObjetosSimulables.Remove(osObjeto);
if (osObjeto.VisualRepresentation != null) if (osObjeto.VisualRepresentation != null)
MainWindow.EliminarUserControlDelCanvas(osObjeto.VisualRepresentation); MainWindow.EliminarUserControlDelCanvas(osObjeto.VisualRepresentation);
HasUnsavedChanges = true;
} }
} }
@ -408,6 +445,7 @@ namespace CtrEditor
NuevoObjetoDuplicado.Top += OffsetY; NuevoObjetoDuplicado.Top += OffsetY;
ObjetosSimulables.Add(NuevoObjetoDuplicado); ObjetosSimulables.Add(NuevoObjetoDuplicado);
CrearUserControlDesdeObjetoSimulable(NuevoObjetoDuplicado); CrearUserControlDesdeObjetoSimulable(NuevoObjetoDuplicado);
HasUnsavedChanges = true;
} }
} }
catch catch
@ -422,13 +460,26 @@ namespace CtrEditor
} }
private void EliminarUserControl() public void EliminarObjetoSeleccionado()
{ {
if (SelectedItemOsList is osBase objEliminar) if (SelectedItemOsList is osBase objEliminar)
{
var result = MessageBox.Show($"¿Está seguro que desea eliminar el objeto '{objEliminar.Nombre}'?",
"Confirmar eliminación",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{ {
RemoverObjetoSimulable(objEliminar); RemoverObjetoSimulable(objEliminar);
} }
} }
}
private void EliminarUserControl()
{
EliminarObjetoSeleccionado();
}
private void EliminarTodosCommand() private void EliminarTodosCommand()
@ -659,6 +710,7 @@ namespace CtrEditor
// Guarda el libro de Excel. // Guarda el libro de Excel.
workbook.SaveAs(filePath); workbook.SaveAs(filePath);
HasUnsavedChanges = false;
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -875,6 +927,8 @@ namespace CtrEditor
// Restaurar las propiedades originales de los objetos // Restaurar las propiedades originales de los objetos
foreach (var obj in ObjetosSimulables) foreach (var obj in ObjetosSimulables)
obj.RestaurarDatosNoSerializables(); obj.RestaurarDatosNoSerializables();
HasUnsavedChanges = false;
} }
} }
@ -984,7 +1038,17 @@ namespace CtrEditor
private void Exit() private void Exit()
{ {
Save(); if (HasUnsavedChanges)
{
var result = MessageBox.Show("There are unsaved changes. Do you want to save them?",
"Save Changes",
MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Cancel)
return;
else if (result == MessageBoxResult.Yes)
SaveStateObjetosSimulables();
}
Application.Current.Shutdown(); Application.Current.Shutdown();
} }
} }

View File

@ -5,7 +5,7 @@
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:ObjetosSim="clr-namespace:CtrEditor.ObjetosSim" xmlns:ObjetosSim="clr-namespace:CtrEditor.ObjetosSim"
xmlns:ObjetosExtraccion="clr-namespace:CtrEditor.ObjetosSim.Extraccion_Datos" x:Class="CtrEditor.MainWindow" xmlns:ObjetosExtraccion="clr-namespace:CtrEditor.ObjetosSim.Extraccion_Datos" x:Class="CtrEditor.MainWindow"
Height="900" Width="1600" WindowState="Maximized" ResizeMode="CanResize" Title="{Binding directorioTrabajo}" Height="900" Width="1600" WindowState="Maximized" ResizeMode="CanResize" Title="{Binding directorioTrabajo, Converter={StaticResource UnsavedChangesConverter}}"
Icon="/app2.png"> Icon="/app2.png">
<Window.DataContext> <Window.DataContext>

View File

@ -49,7 +49,6 @@ namespace CtrEditor
private bool _isResizingUserControl = false; private bool _isResizingUserControl = false;
private bool _isDraggingUserControl = false; private bool _isDraggingUserControl = false;
private bool _isMovingUserControl = false; private bool _isMovingUserControl = false;
private double _initialAngleUserControl;
private TextBlock _angleDisplayTextBlock; private TextBlock _angleDisplayTextBlock;
public MainWindow() public MainWindow()
@ -66,7 +65,11 @@ namespace CtrEditor
ImagenEnTrabajoCanvas.MouseDown += Canvas_MouseDown_Panning; ImagenEnTrabajoCanvas.MouseDown += Canvas_MouseDown_Panning;
ImagenEnTrabajoCanvas.MouseMove += Canvas_MouseMove_Panning; ImagenEnTrabajoCanvas.MouseMove += Canvas_MouseMove_Panning;
ImagenEnTrabajoCanvas.MouseUp += Canvas_MouseUp_Panning; ImagenEnTrabajoCanvas.MouseUp += Canvas_MouseUp_Panning;
// Agregar el evento KeyDown a la ventana
this.KeyDown += MainWindow_KeyDown;
} }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ {
if (DataContext is MainViewModel viewModel) if (DataContext is MainViewModel viewModel)
@ -156,7 +159,6 @@ namespace CtrEditor
rotateTransform = new RotateTransform(); rotateTransform = new RotateTransform();
userControl.RenderTransform = rotateTransform; userControl.RenderTransform = rotateTransform;
} }
_initialAngleUserControl = rotateTransform.Angle;
// Establecer el punto inicial de referencia para el cálculo de rotación // Establecer el punto inicial de referencia para el cálculo de rotación
_startPointUserControl = new Point(rotateTransform.CenterX, rotateTransform.CenterY); _startPointUserControl = new Point(rotateTransform.CenterX, rotateTransform.CenterY);
@ -399,8 +401,20 @@ namespace CtrEditor
private Point lastMousePosition; private Point lastMousePosition;
private void MarkUnsavedChanges()
{
if (DataContext is MainViewModel viewModel)
{
if (_isMovingUserControl || _isRotatingUserControl || _isResizingUserControl || _isDraggingUserControl)
{
viewModel.HasUnsavedChanges = true;
}
}
}
private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
MarkUnsavedChanges();
if (_isResizingUserControl && resizeRectangles != null && resizeRectangles.Contains(sender)) if (_isResizingUserControl && resizeRectangles != null && resizeRectangles.Contains(sender))
{ {
_isResizingUserControl = false; _isResizingUserControl = false;
@ -417,6 +431,7 @@ namespace CtrEditor
AddResizeRectangles(_currentDraggingControl); AddResizeRectangles(_currentDraggingControl);
_isResizingUserControl = _isRotatingUserControl = _isDraggingUserControl = false; _isResizingUserControl = _isRotatingUserControl = _isDraggingUserControl = false;
_isMovingUserControl = false; _isMovingUserControl = false;
// Ocultar el TextBlock de ángulo // Ocultar el TextBlock de ángulo
if (_angleDisplayTextBlock != null) if (_angleDisplayTextBlock != null)
{ {
@ -808,6 +823,15 @@ namespace CtrEditor
} }
} }
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete && DataContext is MainViewModel viewModel)
{
viewModel.EliminarObjetoSeleccionado();
e.Handled = true;
}
}
} }
public class FloatValidationRule : ValidationRule public class FloatValidationRule : ValidationRule

View File

@ -1031,6 +1031,23 @@ namespace CtrEditor.ObjetosSim
} }
} }
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
// Don't mark changes for certain properties
if (e.PropertyName != nameof(Top) &&
e.PropertyName != nameof(Left) &&
e.PropertyName != nameof(Ancho) &&
e.PropertyName != nameof(Angulo) &&
Cloned == false &&
e.PropertyName != nameof(Show_On_This_Page) &&
_mainViewModel != null)
{
_mainViewModel.HasUnsavedChanges = true;
}
}
} }
public class UniqueId public class UniqueId