Se agregó la función CanPasteFromClipboard para validar el contenido del portapapeles antes de pegar objetos, mejorando la gestión de errores y asegurando que solo se seleccionen objetos con representación visual válida. Se implementó un retraso en la selección para permitir el renderizado completo de los objetos pegados.

This commit is contained in:
Miguel 2025-06-13 23:28:50 +02:00
parent 16f5131803
commit e935efb0cb
1 changed files with 121 additions and 6 deletions

View File

@ -16,6 +16,7 @@ using System.Text.RegularExpressions;
using System.Collections.Generic; using System.Collections.Generic;
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace CtrEditor namespace CtrEditor
{ {
@ -660,7 +661,7 @@ namespace CtrEditor
} }
// Agregar opciones de pegado // Agregar opciones de pegado
if (Clipboard.ContainsText()) if (CanPasteFromClipboard())
{ {
var pasteMenuItem = new MenuItem { Header = "Pegar (Ctrl+V)" }; var pasteMenuItem = new MenuItem { Header = "Pegar (Ctrl+V)" };
pasteMenuItem.Click += (s, e) => PasteObjectsFromJson(); pasteMenuItem.Click += (s, e) => PasteObjectsFromJson();
@ -957,13 +958,77 @@ namespace CtrEditor
} }
} }
// Seleccionar los objetos pegados // Forzar actualización del layout para asegurar que los objetos estén renderizados
foreach (var obj in newlyPastedObjects) ImagenEnTrabajoCanvas.UpdateLayout();
{
_objectManager.SelectObject(obj); // Usar Task.Delay para dar más tiempo al renderizado completo
} Task.Delay(100).ContinueWith(_ =>
{
Application.Current.Dispatcher.Invoke(() =>
{
try
{
// Forzar una segunda actualización del layout
ImagenEnTrabajoCanvas.UpdateLayout();
// Validar que los objetos tengan representación visual antes de seleccionar
var validObjects = newlyPastedObjects.Where(obj =>
obj.VisualRepresentation != null &&
ImagenEnTrabajoCanvas.Children.Contains(obj.VisualRepresentation)).ToList();
Console.WriteLine($"Intentando seleccionar {validObjects.Count} de {newlyPastedObjects.Count} objetos pegados");
if (validObjects.Count > 0)
{
// Limpiar selección actual primero
_objectManager.ClearSelection();
// Seleccionar los objetos válidos uno por uno con verificación
foreach (var obj in validObjects)
{
try
{
if (obj.VisualRepresentation != null)
{
Console.WriteLine($"Seleccionando objeto: {obj.Nombre} (ID: {obj.Id.Value})");
_objectManager.SelectObject(obj);
}
}
catch (Exception objEx)
{
Console.WriteLine($"Error al seleccionar objeto {obj.Nombre}: {objEx.Message}");
}
}
// Actualizar visuales de selección con manejo de errores
try
{
_objectManager.UpdateSelectionVisuals();
Console.WriteLine($"Seleccionados exitosamente {_objectManager.SelectedObjects.Count} objetos");
}
catch (Exception visEx)
{
Console.WriteLine($"Error al actualizar visuales de selección: {visEx.Message}");
Console.WriteLine($"Stack trace: {visEx.StackTrace}");
}
}
else
{
Console.WriteLine("No se pudieron seleccionar los objetos pegados - representación visual no válida");
foreach (var obj in newlyPastedObjects)
{
Console.WriteLine($"Objeto {obj.Nombre}: VisualRep={obj.VisualRepresentation != null}, EnCanvas={obj.VisualRepresentation != null && ImagenEnTrabajoCanvas.Children.Contains(obj.VisualRepresentation)}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error general al seleccionar objetos pegados: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
}
});
});
_objectManager.UpdateSelectionVisuals();
viewModel.HasUnsavedChanges = true; viewModel.HasUnsavedChanges = true;
Console.WriteLine($"Pegados {newlyPastedObjects.Count} objeto(s) desde el portapapeles"); Console.WriteLine($"Pegados {newlyPastedObjects.Count} objeto(s) desde el portapapeles");
@ -974,6 +1039,56 @@ namespace CtrEditor
MessageBox.Show($"Error al pegar objetos: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show($"Error al pegar objetos: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
} }
} }
private bool CanPasteFromClipboard()
{
if (!Clipboard.ContainsText())
return false;
try
{
string jsonString = Clipboard.GetText();
// Validación básica del JSON
if (string.IsNullOrWhiteSpace(jsonString) ||
(!jsonString.TrimStart().StartsWith("[") && !jsonString.TrimStart().StartsWith("{")))
{
return false;
}
// Intentar una deserialización rápida para validar
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
ObjectCreationHandling = ObjectCreationHandling.Replace,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
// Intentar deserializar como lista de objetos
try
{
var pastedObjects = JsonConvert.DeserializeObject<List<osBase>>(jsonString, settings);
return pastedObjects != null && pastedObjects.Any();
}
catch
{
// Si falla como lista, intentar como objeto individual
try
{
var singleObject = JsonConvert.DeserializeObject<osBase>(jsonString, settings);
return singleObject != null;
}
catch
{
return false;
}
}
}
catch
{
return false;
}
}
} }
public class FloatValidationRule : ValidationRule public class FloatValidationRule : ValidationRule