Optimización del launcher de la calculadora MAV eliminando verificaciones de dependencias y WebEngine al inicio. Se mejora la gestión del panel LaTeX, asegurando que solo se actualice si está visible. Se implementa inicialización perezosa para WebEngine y se ajusta la configuración de MathJax para SVG, mejorando el rendimiento y la experiencia del usuario.
This commit is contained in:
parent
c219b62857
commit
e51e6bf1ae
|
@ -70,8 +70,11 @@ class EvaluationManager:
|
||||||
self.main_window.engine.variables.clear()
|
self.main_window.engine.variables.clear()
|
||||||
self.logger.debug("Contexto del motor limpiado")
|
self.logger.debug("Contexto del motor limpiado")
|
||||||
|
|
||||||
# Limpiar panel LaTeX solo cuando hay contenido nuevo para evaluar
|
# Limpiar ecuaciones LaTeX en memoria
|
||||||
self._latex_equations.clear()
|
self._latex_equations.clear()
|
||||||
|
|
||||||
|
# Solo limpiar panel visual si está visible
|
||||||
|
if self.main_window.latex_panel_visible:
|
||||||
self.main_window.latex_panel.clear_equations()
|
self.main_window.latex_panel.clear_equations()
|
||||||
|
|
||||||
lines = input_content.splitlines()
|
lines = input_content.splitlines()
|
||||||
|
@ -213,6 +216,8 @@ class EvaluationManager:
|
||||||
'content': latex_content
|
'content': latex_content
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# Solo actualizar el panel si está visible/activo
|
||||||
|
if self.main_window.latex_panel_visible:
|
||||||
self.main_window.latex_panel.add_equation(equation_type, latex_content)
|
self.main_window.latex_panel.add_equation(equation_type, latex_content)
|
||||||
|
|
||||||
# Actualizar indicador visual
|
# Actualizar indicador visual
|
||||||
|
|
|
@ -23,12 +23,11 @@ class LatexPanel(QWidget):
|
||||||
self._mathjax_ready = False
|
self._mathjax_ready = False
|
||||||
self._pending_equations = []
|
self._pending_equations = []
|
||||||
self._parent_calculator = parent
|
self._parent_calculator = parent
|
||||||
|
self._webview_initialized = False
|
||||||
self._setup_ui()
|
self._setup_ui()
|
||||||
|
|
||||||
# Timer para verificar si MathJax está listo
|
# Timer para verificar si MathJax está listo (inicializado bajo demanda)
|
||||||
self._mathjax_check_timer = QTimer()
|
self._mathjax_check_timer = None
|
||||||
self._mathjax_check_timer.timeout.connect(self._check_mathjax_ready)
|
|
||||||
self._mathjax_check_timer.start(500) # Verificar cada 500ms
|
|
||||||
|
|
||||||
def _setup_ui(self):
|
def _setup_ui(self):
|
||||||
"""Configura la UI del panel"""
|
"""Configura la UI del panel"""
|
||||||
|
@ -67,9 +66,9 @@ class LatexPanel(QWidget):
|
||||||
self._webview_available = False
|
self._webview_available = False
|
||||||
|
|
||||||
def _setup_webview(self):
|
def _setup_webview(self):
|
||||||
"""Configura WebEngineView con MathJax"""
|
"""Configura WebEngineView con MathJax (inicialización perezosa)"""
|
||||||
html_content = self._generate_mathjax_html()
|
# No cargar HTML inmediatamente para optimizar tiempo de inicio
|
||||||
self.webview.setHtml(html_content)
|
pass
|
||||||
|
|
||||||
def _setup_text_browser(self):
|
def _setup_text_browser(self):
|
||||||
"""Configura el browser de texto como fallback"""
|
"""Configura el browser de texto como fallback"""
|
||||||
|
@ -108,14 +107,14 @@ class LatexPanel(QWidget):
|
||||||
""")
|
""")
|
||||||
|
|
||||||
def _generate_mathjax_html(self):
|
def _generate_mathjax_html(self):
|
||||||
"""Genera HTML base con MathJax"""
|
"""Genera HTML base con MathJax configurado para SVG"""
|
||||||
return """
|
return """
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
|
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
|
||||||
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
|
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
|
||||||
<script>
|
<script>
|
||||||
window.MathJax = {
|
window.MathJax = {
|
||||||
tex: {
|
tex: {
|
||||||
|
@ -123,16 +122,17 @@ class LatexPanel(QWidget):
|
||||||
displayMath: [['$$', '$$'], ['\\[', '\\]']],
|
displayMath: [['$$', '$$'], ['\\[', '\\]']],
|
||||||
processEscapes: true
|
processEscapes: true
|
||||||
},
|
},
|
||||||
chtml: {
|
svg: {
|
||||||
scale: 0.9,
|
scale: 0.9,
|
||||||
minScale: 0.5
|
minScale: 0.5,
|
||||||
|
fontCache: 'global'
|
||||||
},
|
},
|
||||||
startup: {
|
startup: {
|
||||||
ready: function () {
|
ready: function () {
|
||||||
MathJax.startup.defaultReady();
|
MathJax.startup.defaultReady();
|
||||||
// Notificar que MathJax está listo
|
// Notificar que MathJax está listo
|
||||||
window.mathJaxReady = true;
|
window.mathJaxReady = true;
|
||||||
console.log('MathJax completamente cargado');
|
console.log('MathJax SVG completamente cargado');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -181,24 +181,25 @@ class LatexPanel(QWidget):
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Reducir espaciado de MathJax */
|
/* Optimizaciones para SVG rendering */
|
||||||
.MathJax {
|
mjx-container[jax="SVG"] {
|
||||||
font-size: 0.9em !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
mjx-math {
|
|
||||||
margin: 1px 0 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
mjx-container {
|
|
||||||
margin: 2px 0 !important;
|
margin: 2px 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mjx-container[jax="SVG"] svg {
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mejorar contraste del SVG */
|
||||||
|
mjx-container[jax="SVG"] svg text {
|
||||||
|
fill: #d4d4d4 !important;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="equations-container">
|
<div id="equations-container">
|
||||||
<div class="info-message">
|
<div class="info-message">
|
||||||
Panel de Ecuaciones LaTeX
|
Panel de Ecuaciones LaTeX (SVG)
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -231,21 +232,21 @@ class LatexPanel(QWidget):
|
||||||
// Re-renderizar MathJax solo si está listo
|
// Re-renderizar MathJax solo si está listo
|
||||||
if (window.MathJax && window.mathJaxReady && type !== 'comment') {
|
if (window.MathJax && window.mathJaxReady && type !== 'comment') {
|
||||||
MathJax.typesetPromise([equation]).catch(function(err) {
|
MathJax.typesetPromise([equation]).catch(function(err) {
|
||||||
console.error('MathJax error:', err);
|
console.error('MathJax SVG error:', err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearEquations() {
|
function clearEquations() {
|
||||||
var container = document.getElementById('equations-container');
|
var container = document.getElementById('equations-container');
|
||||||
container.innerHTML = '<div class="info-message">Panel de Ecuaciones LaTeX</div>';
|
container.innerHTML = '<div class="info-message">Panel de Ecuaciones LaTeX (SVG)</div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Función para notificar que está listo para renderizar
|
// Función para notificar que está listo para renderizar
|
||||||
function triggerInitialRender() {
|
function triggerInitialRender() {
|
||||||
if (window.mathJaxReady) {
|
if (window.mathJaxReady) {
|
||||||
// Notificar a Python que MathJax está listo
|
// Notificar a Python que MathJax está listo
|
||||||
console.log('MathJax listo para renderizado inicial');
|
console.log('MathJax SVG listo para renderizado inicial');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
|
@ -254,6 +255,27 @@ class LatexPanel(QWidget):
|
||||||
</body>
|
</body>
|
||||||
</html>"""
|
</html>"""
|
||||||
|
|
||||||
|
def _ensure_webview_initialized(self):
|
||||||
|
"""Inicializa WebEngine bajo demanda para optimizar tiempo de carga"""
|
||||||
|
if self._webview_initialized:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
if hasattr(self, 'webview') and self._webview_available:
|
||||||
|
html_content = self._generate_mathjax_html()
|
||||||
|
self.webview.setHtml(html_content)
|
||||||
|
|
||||||
|
# Inicializar timer de verificación MathJax
|
||||||
|
if self._mathjax_check_timer is None:
|
||||||
|
self._mathjax_check_timer = QTimer()
|
||||||
|
self._mathjax_check_timer.timeout.connect(self._check_mathjax_ready)
|
||||||
|
self._mathjax_check_timer.start(500) # Verificar cada 500ms
|
||||||
|
|
||||||
|
self._webview_initialized = True
|
||||||
|
logging.debug("✅ WebEngine LaTeX inicializado bajo demanda")
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error inicializando WebEngine: {e}")
|
||||||
|
|
||||||
def _check_mathjax_ready(self):
|
def _check_mathjax_ready(self):
|
||||||
"""Verifica si MathJax está listo y renderiza ecuaciones pendientes"""
|
"""Verifica si MathJax está listo y renderiza ecuaciones pendientes"""
|
||||||
if not self._webview_available:
|
if not self._webview_available:
|
||||||
|
@ -293,6 +315,9 @@ class LatexPanel(QWidget):
|
||||||
self.equations.append({'type': eq_type, 'content': content})
|
self.equations.append({'type': eq_type, 'content': content})
|
||||||
|
|
||||||
if self._webview_available:
|
if self._webview_available:
|
||||||
|
# Inicializar WebEngine bajo demanda
|
||||||
|
self._ensure_webview_initialized()
|
||||||
|
|
||||||
if self._mathjax_ready:
|
if self._mathjax_ready:
|
||||||
# MathJax está listo, renderizar inmediatamente
|
# MathJax está listo, renderizar inmediatamente
|
||||||
self._add_equation_to_webview(eq_type, content)
|
self._add_equation_to_webview(eq_type, content)
|
||||||
|
@ -308,7 +333,7 @@ class LatexPanel(QWidget):
|
||||||
self.equations.clear()
|
self.equations.clear()
|
||||||
self._pending_equations.clear()
|
self._pending_equations.clear()
|
||||||
|
|
||||||
if self._webview_available:
|
if self._webview_available and self._webview_initialized:
|
||||||
# Usar JavaScript para limpiar dinámicamente si MathJax está listo
|
# Usar JavaScript para limpiar dinámicamente si MathJax está listo
|
||||||
if self._mathjax_ready:
|
if self._mathjax_ready:
|
||||||
self.webview.page().runJavaScript("clearEquations();")
|
self.webview.page().runJavaScript("clearEquations();")
|
||||||
|
@ -316,11 +341,16 @@ class LatexPanel(QWidget):
|
||||||
# Si MathJax no está listo, recargar HTML base limpio
|
# Si MathJax no está listo, recargar HTML base limpio
|
||||||
html_content = self._generate_mathjax_html()
|
html_content = self._generate_mathjax_html()
|
||||||
self.webview.setHtml(html_content)
|
self.webview.setHtml(html_content)
|
||||||
else:
|
elif hasattr(self, 'text_browser'):
|
||||||
|
# Para fallback o WebEngine no inicializado, solo si text_browser existe
|
||||||
self._setup_text_browser() # Reset al estado inicial
|
self._setup_text_browser() # Reset al estado inicial
|
||||||
|
|
||||||
def _update_text_browser(self):
|
def _update_text_browser(self):
|
||||||
"""Actualiza el contenido del text browser (fallback)"""
|
"""Actualiza el contenido del text browser (fallback)"""
|
||||||
|
# Verificar que text_browser existe antes de usarlo
|
||||||
|
if not hasattr(self, 'text_browser'):
|
||||||
|
return
|
||||||
|
|
||||||
html_parts = ["""
|
html_parts = ["""
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {
|
||||||
|
|
|
@ -56,7 +56,7 @@ class HybridCalculatorPySide6(QMainWindow):
|
||||||
self.debug = self.settings.get("debug_mode", False)
|
self.debug = self.settings.get("debug_mode", False)
|
||||||
|
|
||||||
# Estado del panel LaTeX
|
# Estado del panel LaTeX
|
||||||
self.latex_panel_visible = self.settings.get("latex_panel_visible", True)
|
self.latex_panel_visible = self.settings.get("latex_panel_visible", False)
|
||||||
self._latex_equations = []
|
self._latex_equations = []
|
||||||
|
|
||||||
# Configurar helpers
|
# Configurar helpers
|
||||||
|
@ -137,7 +137,9 @@ class HybridCalculatorPySide6(QMainWindow):
|
||||||
main_layout.addWidget(self.latex_panel)
|
main_layout.addWidget(self.latex_panel)
|
||||||
self.latex_button.setChecked(True)
|
self.latex_button.setChecked(True)
|
||||||
else:
|
else:
|
||||||
|
# Asegurar que el panel está oculto por defecto
|
||||||
self.latex_panel.hide()
|
self.latex_panel.hide()
|
||||||
|
self.latex_button.setChecked(False)
|
||||||
|
|
||||||
# Los formatos de salida se configuran automáticamente en EvaluationManager
|
# Los formatos de salida se configuran automáticamente en EvaluationManager
|
||||||
|
|
||||||
|
@ -259,20 +261,40 @@ class HybridCalculatorPySide6(QMainWindow):
|
||||||
|
|
||||||
def _toggle_latex_panel(self):
|
def _toggle_latex_panel(self):
|
||||||
"""Togglea la visibilidad del panel LaTeX"""
|
"""Togglea la visibilidad del panel LaTeX"""
|
||||||
|
main_layout = self.centralWidget().layout()
|
||||||
|
|
||||||
if self.latex_panel_visible:
|
if self.latex_panel_visible:
|
||||||
|
# Ocultar panel
|
||||||
|
main_layout.removeWidget(self.latex_panel)
|
||||||
self.latex_panel.hide()
|
self.latex_panel.hide()
|
||||||
self.latex_button.setChecked(False)
|
self.latex_button.setChecked(False)
|
||||||
self.latex_panel_visible = False
|
self.latex_panel_visible = False
|
||||||
else:
|
else:
|
||||||
main_layout = self.centralWidget().layout()
|
# Mostrar panel
|
||||||
main_layout.addWidget(self.latex_panel)
|
main_layout.addWidget(self.latex_panel)
|
||||||
self.latex_panel.show()
|
self.latex_panel.show()
|
||||||
self.latex_button.setChecked(True)
|
self.latex_button.setChecked(True)
|
||||||
self.latex_panel_visible = True
|
self.latex_panel_visible = True
|
||||||
|
|
||||||
|
# Actualizar panel con ecuaciones pendientes
|
||||||
|
self._sync_latex_equations_on_show()
|
||||||
|
|
||||||
# Guardar configuración
|
# Guardar configuración
|
||||||
self.settings_manager.set_setting("latex_panel_visible", self.latex_panel_visible)
|
self.settings_manager.set_setting("latex_panel_visible", self.latex_panel_visible)
|
||||||
|
|
||||||
|
def _sync_latex_equations_on_show(self):
|
||||||
|
"""Sincroniza las ecuaciones LaTeX cuando se muestra el panel"""
|
||||||
|
try:
|
||||||
|
# Limpiar panel
|
||||||
|
self.latex_panel.clear_equations()
|
||||||
|
|
||||||
|
# Añadir todas las ecuaciones pendientes
|
||||||
|
for eq in self.evaluation_manager.get_latex_equations():
|
||||||
|
self.latex_panel.add_equation(eq['type'], eq['content'])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(f"Error sincronizando ecuaciones LaTeX: {e}")
|
||||||
|
|
||||||
def _update_status(self, message: str, timeout: int = 0):
|
def _update_status(self, message: str, timeout: int = 0):
|
||||||
"""Actualiza la barra de estado"""
|
"""Actualiza la barra de estado"""
|
||||||
self.status_bar.showMessage(message, timeout)
|
self.status_bar.showMessage(message, timeout)
|
||||||
|
|
|
@ -31,7 +31,7 @@ class SettingsManager:
|
||||||
"window_geometry": None,
|
"window_geometry": None,
|
||||||
"splitter_sizes": None,
|
"splitter_sizes": None,
|
||||||
"debug_mode": False,
|
"debug_mode": False,
|
||||||
"latex_panel_visible": True
|
"latex_panel_visible": False
|
||||||
}
|
}
|
||||||
|
|
||||||
def _save_settings(self):
|
def _save_settings(self):
|
||||||
|
|
66
calc.py
66
calc.py
|
@ -1,82 +1,26 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""
|
||||||
Launcher para Calculadora MAV - Versión PySide6 con MathJax
|
Launcher para Calculadora MAV - Versión PySide6 con MathJax
|
||||||
|
Versión optimizada: sin verificaciones lentas al inicio
|
||||||
"""
|
"""
|
||||||
import sys
|
import sys
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
from pathlib import Path
|
|
||||||
import importlib.util
|
|
||||||
import logging
|
|
||||||
|
|
||||||
def check_dependencies():
|
|
||||||
"""Verifica que todas las dependencias estén instaladas"""
|
|
||||||
required_modules = [
|
|
||||||
'PySide6',
|
|
||||||
'sympy',
|
|
||||||
'numpy',
|
|
||||||
'matplotlib'
|
|
||||||
]
|
|
||||||
|
|
||||||
missing = []
|
|
||||||
for module in required_modules:
|
|
||||||
try:
|
|
||||||
__import__(module)
|
|
||||||
except ImportError:
|
|
||||||
missing.append(module)
|
|
||||||
|
|
||||||
if missing:
|
|
||||||
print("❌ Faltan las siguientes dependencias:")
|
|
||||||
for module in missing:
|
|
||||||
print(f" - {module}")
|
|
||||||
print("\n💡 Para instalar las dependencias, ejecuta:")
|
|
||||||
print(" pip install -r requirements.txt")
|
|
||||||
return False
|
|
||||||
|
|
||||||
print("✅ Todas las dependencias están instaladas")
|
|
||||||
return True
|
|
||||||
|
|
||||||
def check_pyside6_webengine():
|
|
||||||
"""Verifica si PySide6 WebEngine está disponible"""
|
|
||||||
try:
|
|
||||||
from PySide6.QtWebEngineWidgets import QWebEngineView
|
|
||||||
print("✅ PySide6 WebEngine disponible para MathJax")
|
|
||||||
return True
|
|
||||||
except ImportError:
|
|
||||||
print("⚠️ PySide6 WebEngine no disponible")
|
|
||||||
print(" Instalando QtWebEngine...")
|
|
||||||
try:
|
|
||||||
subprocess.run([sys.executable, '-m', 'pip', 'install', 'PySide6-WebEngine'],
|
|
||||||
check=True, capture_output=True)
|
|
||||||
print("✅ PySide6 WebEngine instalado correctamente")
|
|
||||||
return True
|
|
||||||
except subprocess.CalledProcessError:
|
|
||||||
print("❌ No se pudo instalar PySide6 WebEngine")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Función principal del launcher"""
|
"""Función principal optimizada del launcher"""
|
||||||
print("🚀 Iniciando Calculadora MAV - Diseño Minimalista 3 Paneles")
|
print("🚀 Iniciando Calculadora MAV - Diseño Minimalista 3 Paneles")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
# Verificar dependencias
|
print("🎯 Iniciando aplicación...")
|
||||||
if not check_dependencies():
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Verificar WebEngine
|
|
||||||
if not check_pyside6_webengine():
|
|
||||||
print("⚠️ Continuando sin WebEngine (funcionalidad limitada)")
|
|
||||||
|
|
||||||
print("\n🎯 Iniciando aplicación...")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Importar y ejecutar la aplicación
|
# Importar y ejecutar la aplicación directamente
|
||||||
from app.gui_main import main as run_app
|
from app.gui_main import main as run_app
|
||||||
run_app()
|
run_app()
|
||||||
|
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
print(f"❌ Error de importación: {e}")
|
print(f"❌ Error de importación: {e}")
|
||||||
print(" Verifica que todos los archivos del proyecto estén presentes")
|
print(" Verifica que todos los archivos del proyecto estén presentes")
|
||||||
|
print(" Si faltan dependencias, ejecuta: pip install -r requirements.txt")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
Loading…
Reference in New Issue