From e3eb2fb9e5c07fe3f864d1181a2f10df8ce0a132 Mon Sep 17 00:00:00 2001 From: Miguel Date: Wed, 18 Jun 2025 02:44:36 +0200 Subject: [PATCH] =?UTF-8?q?Mejoras=20en=20el=20Launcher=20C#=20y=20gesti?= =?UTF-8?q?=C3=B3n=20de=20proyectos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Se añadió la funcionalidad de limpieza del estado previo en el gestor de lanzadores C#. - Se implementó un método para reiniciar completamente el launcher, asegurando una inicialización adecuada. - Se mejoró la gestión de argumentos para ejecutables, permitiendo la selección y ejecución con argumentos predefinidos. - Se optimizó la lógica de inicialización y se añadieron mensajes de depuración para facilitar el seguimiento de errores. - Se realizaron ajustes en la interfaz para mejorar la experiencia del usuario al gestionar proyectos y ejecutables. --- data/log.txt | 16 ++ static/js/csharp_launcher.js | 323 ++++++++++++++++++++++++++++++++--- static/js/launcher.js | 10 +- templates/index.html | 3 +- 4 files changed, 327 insertions(+), 25 deletions(-) diff --git a/data/log.txt b/data/log.txt index fce08ca..846395e 100644 --- a/data/log.txt +++ b/data/log.txt @@ -32,3 +32,19 @@ [01:54:56] ✅ Proceso completado exitosamente (PID: 44892) [01:54:56] ⏱️ Tiempo de ejecución: 3.87 segundos [01:54:56] ================================================== +[02:43:57] 🚀 Ejecutando: GTPCorrgir +[02:43:57] 📁 Directorio: D:/Proyectos/VisualStudio/GTPCorrgir\bin\Release\net8.0-windows +[02:43:57] ⚡ Comando: D:/Proyectos/VisualStudio/GTPCorrgir\bin\Release\net8.0-windows\GTPCorrgir.exe --Menu +[02:43:57] ================================================== +[02:43:57] ✅ Proceso iniciado con PID: 42668 +[02:43:59] ✅ Proceso completado exitosamente (PID: 42668) +[02:43:59] ⏱️ Tiempo de ejecución: 2.71 segundos +[02:43:59] ================================================== +[02:44:06] 🚀 Ejecutando: GTPCorrgir +[02:44:06] 📁 Directorio: D:/Proyectos/VisualStudio/GTPCorrgir\bin\Release\net8.0-windows +[02:44:06] ⚡ Comando: D:/Proyectos/VisualStudio/GTPCorrgir\bin\Release\net8.0-windows\GTPCorrgir.exe --Menu +[02:44:06] ================================================== +[02:44:06] ✅ Proceso iniciado con PID: 34300 +[02:44:08] ❌ Proceso terminó con código: 1 (PID: 34300) +[02:44:08] ⏱️ Tiempo de ejecución: 2.09 segundos +[02:44:08] ================================================== diff --git a/static/js/csharp_launcher.js b/static/js/csharp_launcher.js index b45e54c..f123834 100644 --- a/static/js/csharp_launcher.js +++ b/static/js/csharp_launcher.js @@ -12,10 +12,16 @@ class CSharpLauncherManager { 'Desarrollo', 'APIs', 'Otros' ]; this.currentCategory = 'all'; + this.initialized = false; + this.processInterval = null; } async init() { console.log('Initializing C# Launcher Manager...'); + + // Limpiar estado previo si existe + this.clearState(); + await this.loadProjects(); await this.loadFavorites(); this.setupEventListeners(); @@ -23,7 +29,35 @@ class CSharpLauncherManager { await this.refreshProcesses(); // Actualizar procesos cada 10 segundos - setInterval(() => this.refreshProcesses(), 10000); + if (!this.processInterval) { + this.processInterval = setInterval(() => this.refreshProcesses(), 10000); + } + + this.initialized = true; + console.log('C# Launcher Manager initialized successfully'); + } + + clearState() { + console.log('Clearing C# launcher state...'); + this.currentProject = null; + this.projects = []; + this.executables = []; + this.favorites = new Set(); + this.runningProcesses = []; + + // Limpiar intervalos previos + if (this.processInterval) { + clearInterval(this.processInterval); + this.processInterval = null; + } + } + + // Método de utilidad para resetear completamente el launcher + async reset() { + console.log('Resetting C# Launcher...'); + localStorage.removeItem('csharp_last_selected_project'); + this.clearState(); + await this.init(); } async loadProjects() { @@ -71,7 +105,10 @@ class CSharpLauncherManager { renderProjectSelector() { const select = document.getElementById('csharp-project-select'); - if (!select) return; + if (!select) { + console.warn('C# project select element not found'); + return; + } select.innerHTML = ''; @@ -83,24 +120,78 @@ class CSharpLauncherManager { option.setAttribute('data-category', project.category || 'Otros'); select.appendChild(option); }); + + // Restaurar última selección con delay para asegurar que el DOM esté listo + setTimeout(() => this.restoreLastSelectedProject(), 100); + } + + restoreLastSelectedProject() { + try { + const lastSelectedProject = localStorage.getItem('csharp_last_selected_project'); + console.log('Restoring last selected project:', lastSelectedProject); + + if (!lastSelectedProject) { + console.log('No last selected project found'); + return; + } + + const project = this.projects.find(p => p.id === lastSelectedProject); + if (!project) { + console.log('Last selected project not found in current projects list, clearing localStorage'); + localStorage.removeItem('csharp_last_selected_project'); + return; + } + + const select = document.getElementById('csharp-project-select'); + if (!select) { + console.warn('Project select element not found during restore'); + return; + } + + console.log('Restoring project:', project.name); + select.value = lastSelectedProject; + + // Disparar evento change para cargar el proyecto + const changeEvent = new Event('change', { bubbles: true }); + select.dispatchEvent(changeEvent); + } catch (error) { + console.error('Error restoring last selected project:', error); + // Limpiar localStorage corrupto + localStorage.removeItem('csharp_last_selected_project'); + } } async onProjectChange(e) { const projectId = e.target.value; + console.log('Project change event:', projectId); if (!projectId) { + console.log('No project selected, clearing state'); this.currentProject = null; this.hideCSharpProjectButtons(); this.clearExecutables(); + // Limpiar persistencia + localStorage.removeItem('csharp_last_selected_project'); return; } try { this.currentProject = this.projects.find(p => p.id === projectId); + if (!this.currentProject) { + console.error('Project not found:', projectId); + return; + } + + console.log('Loading project:', this.currentProject.name); this.showCSharpProjectButtons(); await this.loadProjectExecutables(projectId); + + // Guardar selección para persistencia + localStorage.setItem('csharp_last_selected_project', projectId); + console.log('Project loaded successfully'); } catch (error) { console.error('Error changing project:', error); + this.showNotification('Error cargando el proyecto', 'error'); } } @@ -162,6 +253,11 @@ class CSharpLauncherManager { } grid.innerHTML = filteredExecutables.map(exe => this.createExecutableCard(exe)).join(''); + + // Cargar argumentos para cada ejecutable después de renderizar + filteredExecutables.forEach(exe => { + this.loadExecutableArgumentsForCard(this.currentProject.id, exe.filename); + }); } createExecutableCard(exe) { @@ -171,6 +267,8 @@ class CSharpLauncherManager { 'Release' : 'Debug'; + // Los argumentos se cargan después de renderizar + return `
@@ -183,15 +281,25 @@ class CSharpLauncherManager { ${buildTypeBadge} ${exe.filename}
+ + +
+ +
+
@@ -379,6 +487,50 @@ class CSharpLauncherManager { } } + async loadExecutableArgumentsForCard(projectId, exeName) { + try { + const response = await fetch(`/api/csharp-executable-arguments/${projectId}/${exeName}`); + if (response.ok) { + const data = await response.json(); + const argsList = data.arguments || []; + this.populateArgumentsCombo(exeName, argsList); + } + } catch (error) { + console.error('Error loading arguments for card:', error); + } + } + + populateArgumentsCombo(exeName, argsList) { + const comboId = `args-combo-${exeName.replace('.exe', '').replace(/[^a-zA-Z0-9]/g, '_')}`; + const combo = document.getElementById(comboId); + if (!combo) return; + + // Limpiar opciones existentes excepto "Sin argumentos" + combo.innerHTML = ''; + + // Agregar argumentos predefinidos + argsList.forEach((arg, index) => { + const option = document.createElement('option'); + option.value = arg.arguments; + option.textContent = arg.description; + option.title = arg.arguments; // Tooltip con los argumentos + combo.appendChild(option); + }); + } + + async executeWithSelectedArgs(projectId, exeName) { + const comboId = `args-combo-${exeName.replace('.exe', '').replace(/[^a-zA-Z0-9]/g, '_')}`; + const combo = document.getElementById(comboId); + const selectedArgs = combo ? combo.value : ''; + + if (selectedArgs) { + const argsArray = selectedArgs.split(' ').filter(arg => arg.length > 0); + await this.executeExecutable(projectId, exeName, argsArray); + } else { + await this.executeExecutable(projectId, exeName); + } + } + clearExecutables() { const grid = document.getElementById('csharp-executables-grid'); if (grid) { @@ -993,15 +1145,15 @@ async function saveCSharpExecutableMetadata(projectId, exeName) { const result = await response.json(); if (result.status === 'success') { - showNotification(result.message, 'success'); + csharpLauncherManager.showNotification(result.message, 'success'); closeCSharpMetadataEditor(); await loadCSharpExecutableManager(); await csharpLauncherManager.loadProjectExecutables(projectId); } else { - showNotification(result.message, 'error'); + csharpLauncherManager.showNotification(result.message, 'error'); } } catch (error) { - showNotification('Error guardando metadatos', 'error'); + csharpLauncherManager.showNotification('Error guardando metadatos', 'error'); console.error('Error saving metadata:', error); } } @@ -1022,7 +1174,7 @@ async function editCSharpExecutableArguments(projectId, exeName) { } } -function showCSharpArgumentsEditor(projectId, exeName, arguments) { +function showCSharpArgumentsEditor(projectId, exeName, argsList) { const modalHtml = `
@@ -1057,14 +1209,14 @@ function showCSharpArgumentsEditor(projectId, exeName, arguments) { `; document.body.insertAdjacentHTML('beforeend', modalHtml); - renderCSharpArguments(arguments); + renderCSharpArguments(argsList); } -function renderCSharpArguments(arguments) { +function renderCSharpArguments(argsList) { const container = document.getElementById('csharp-arguments-list'); if (!container) return; - container.innerHTML = arguments.map((arg, index) => ` + container.innerHTML = argsList.map((arg, index) => `
@@ -1087,7 +1239,7 @@ function renderCSharpArguments(arguments) {
`).join(''); - if (arguments.length === 0) { + if (argsList.length === 0) { container.innerHTML = `
⚙️
@@ -1115,40 +1267,48 @@ function removeCSharpArgument(index) { function collectCSharpArguments() { const argumentItems = document.querySelectorAll('.argument-item'); - const arguments = []; + const argsList = []; argumentItems.forEach(item => { const description = item.querySelector('.arg-description').value.trim(); const argumentValue = item.querySelector('.arg-value').value.trim(); if (description && argumentValue) { - arguments.push({ description, arguments: argumentValue }); + argsList.push({ description, arguments: argumentValue }); } }); - return arguments; + return argsList; } async function saveCSharpExecutableArguments(projectId, exeName) { - const arguments = collectCSharpArguments(); + const argsList = collectCSharpArguments(); try { const response = await fetch(`/api/csharp-executable-arguments/${projectId}/${exeName}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ arguments }) + body: JSON.stringify({ arguments: argsList }) }); const result = await response.json(); if (result.status === 'success') { - showNotification(result.message, 'success'); + csharpLauncherManager.showNotification(result.message, 'success'); closeCSharpArgumentsEditor(); + // Recargar la lista de ejecutables si está abierto el gestor + if (document.getElementById('csharp-executable-manager').style.display !== 'none') { + await loadCSharpExecutableManager(); + } + // Recargar argumentos en las cards actuales + if (csharpLauncherManager.currentProject) { + csharpLauncherManager.loadExecutableArgumentsForCard(projectId, exeName); + } } else { - showNotification(result.message, 'error'); + csharpLauncherManager.showNotification(result.message, 'error'); } } catch (error) { - showNotification('Error guardando argumentos', 'error'); + csharpLauncherManager.showNotification('Error guardando argumentos', 'error'); console.error('Error saving arguments:', error); } } @@ -1254,5 +1414,124 @@ function showCSharpExecutableArgs(projectId, exeName, displayName) { } } -// Inicialización global -window.csharpLauncherManager = new CSharpLauncherManager(); \ No newline at end of file +// Asegurar inicialización cuando el DOM esté listo +(function () { + console.log('C# Launcher script loaded, preparing initialization...'); + + function initializeCSharpLauncher() { + try { + console.log('Initializing CSharpLauncherManager...'); + if (!window.csharpLauncherManager) { + window.csharpLauncherManager = new CSharpLauncherManager(); + console.log('CSharpLauncherManager created successfully'); + } + } catch (error) { + console.error('Error creating CSharpLauncherManager:', error); + } + } + + // Inicializar inmediatamente si el DOM ya está listo + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initializeCSharpLauncher); + } else { + initializeCSharpLauncher(); + } +})(); + +// Función global para debug +window.debugCSharpLauncher = function () { + console.log('=== C# Launcher Debug Info ==='); + console.log('Initialized:', window.csharpLauncherManager.initialized); + console.log('Projects:', window.csharpLauncherManager.projects); + console.log('Current Project:', window.csharpLauncherManager.currentProject); + console.log('Executables:', window.csharpLauncherManager.executables); + console.log('Favorites:', Array.from(window.csharpLauncherManager.favorites)); + console.log('localStorage:', localStorage.getItem('csharp_last_selected_project')); + + // Verificar elementos DOM + const select = document.getElementById('csharp-project-select'); + console.log('Project Select Element:', select); + if (select) { + console.log('Select Options:', select.options.length); + console.log('Select Value:', select.value); + } + console.log('=============================='); +}; + +// Función global para resetear +window.resetCSharpLauncher = function () { + console.log('Resetting C# Launcher...'); + return window.csharpLauncherManager.reset(); +}; + +// === FUNCIONES DE RESPALDO PARA EVITAR ERRORES DE REFERENCIA === + +// Asegurar que las funciones globales estén definidas antes de que se necesiten +document.addEventListener('DOMContentLoaded', function () { + console.log('DOM loaded, ensuring C# launcher functions are available...'); + + // Solo redefinir si no existe para evitar conflictos + if (typeof window.openCSharpProjectEditor === 'undefined') { + window.openCSharpProjectEditor = function () { + if (!window.csharpLauncherManager) { + console.error('csharpLauncherManager not initialized'); + alert('Error: El launcher C# no está inicializado. Refresca la página.'); + return; + } + window.csharpLauncherManager.openProjectEditor(); + }; + } + + if (typeof window.loadCSharpExecutables === 'undefined') { + window.loadCSharpExecutables = function () { + if (!window.csharpLauncherManager) { + console.error('csharpLauncherManager not initialized'); + return; + } + const select = document.getElementById('csharp-project-select'); + if (select && window.csharpLauncherManager) { + window.csharpLauncherManager.onProjectChange({ target: select }); + } + }; + } + + if (typeof window.filterCSharpByCategory === 'undefined') { + window.filterCSharpByCategory = function (category) { + if (!window.csharpLauncherManager) { + console.error('csharpLauncherManager not initialized'); + return; + } + window.csharpLauncherManager.filterByCategory(category); + }; + } + + if (typeof window.refreshCSharpProcesses === 'undefined') { + window.refreshCSharpProcesses = function () { + if (!window.csharpLauncherManager) { + console.error('csharpLauncherManager not initialized'); + return; + } + window.csharpLauncherManager.refreshProcesses(); + }; + } + + if (typeof window.openCSharpExecutableManager === 'undefined') { + window.openCSharpExecutableManager = function () { + if (!window.csharpLauncherManager) { + console.error('csharpLauncherManager not initialized'); + alert('Error: El launcher C# no está inicializado. Refresca la página.'); + return; + } + + if (!window.csharpLauncherManager.currentProject) { + alert('Por favor selecciona un proyecto primero'); + return; + } + + // Usar la función ya implementada + loadCSharpExecutableManager(); + }; + } + + console.log('C# launcher backup functions initialized'); +}); \ No newline at end of file diff --git a/static/js/launcher.js b/static/js/launcher.js index 1c37e22..7852cb2 100644 --- a/static/js/launcher.js +++ b/static/js/launcher.js @@ -1371,8 +1371,14 @@ function switchTab(tabName) { } // Inicializar C# launcher si es la primera vez - if (tabName === 'csharp' && !window.csharpLauncherManager.currentProject) { - window.csharpLauncherManager.init(); + if (tabName === 'csharp') { + if (!window.csharpLauncherManager) { + console.error('csharpLauncherManager not found! Make sure csharp_launcher.js is loaded.'); + return; + } + if (!window.csharpLauncherManager.initialized) { + window.csharpLauncherManager.init(); + } } } diff --git a/templates/index.html b/templates/index.html index b26df1b..8f5212c 100644 --- a/templates/index.html +++ b/templates/index.html @@ -385,7 +385,8 @@

Launcher C# - Proyectos Compilados