Calc/app/gui_settings.py

124 lines
4.5 KiB
Python

"""
Sistema de Configuración y Persistencia para la Calculadora MAV CAS Híbrida
"""
import os
import json
import logging
from typing import Dict, Any
from PySide6.QtCore import QTimer
class SettingsManager:
"""Gestor de configuración y persistencia"""
SETTINGS_FILE = "./.data/settings.json"
HISTORY_FILE = "./.data/history.txt"
def __init__(self, main_window):
self.main_window = main_window
self.logger = logging.getLogger(__name__)
self.settings = self._load_settings()
def _load_settings(self) -> Dict[str, Any]:
"""Carga configuración de la aplicación"""
if os.path.exists(self.SETTINGS_FILE):
try:
with open(self.SETTINGS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
pass
return {
"window_geometry": None,
"splitter_sizes": None,
"debug_mode": False,
"latex_panel_visible": True
}
def _save_settings(self):
"""Guarda configuraciones"""
try:
# Crear directorio si no existe
os.makedirs(os.path.dirname(self.SETTINGS_FILE), exist_ok=True)
# Guardar geometría
geometry = self.main_window.geometry()
self.settings["window_geometry"] = {
"x": geometry.x(),
"y": geometry.y(),
"width": geometry.width(),
"height": geometry.height()
}
# Guardar tamaños del splitter
if hasattr(self.main_window, 'main_splitter'):
self.settings["splitter_sizes"] = self.main_window.main_splitter.sizes()
self.settings["latex_panel_visible"] = self.main_window.latex_panel_visible
self.settings["debug_mode"] = getattr(self.main_window, 'debug', False)
with open(self.SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(self.settings, f, indent=4, ensure_ascii=False)
except Exception as e:
self.logger.error(f"Error guardando configuración: {e}")
def _load_history(self):
"""Carga historial de entrada"""
try:
if os.path.exists(self.HISTORY_FILE):
with open(self.HISTORY_FILE, "r", encoding="utf-8") as f:
content = f.read()
if content.strip():
self.main_window.input_text.setPlainText(content)
# Evaluación inicial
QTimer.singleShot(100, self.main_window._evaluate_and_update)
except Exception as e:
self.logger.error(f"Error cargando historial: {e}")
def _save_history(self):
"""Guarda historial de entrada"""
try:
# Crear directorio si no existe
os.makedirs(os.path.dirname(self.HISTORY_FILE), exist_ok=True)
content = self.main_window.input_text.toPlainText()
if content:
with open(self.HISTORY_FILE, "w", encoding="utf-8") as f:
f.write(content)
elif os.path.exists(self.HISTORY_FILE):
os.remove(self.HISTORY_FILE)
except Exception as e:
self.logger.error(f"Error guardando historial: {e}")
def _restore_geometry(self):
"""Restaura geometría guardada"""
try:
geom = self.settings.get("window_geometry")
if geom and isinstance(geom, dict):
self.main_window.setGeometry(geom["x"], geom["y"], geom["width"], geom["height"])
# Restaurar splitter
sizes = self.settings.get("splitter_sizes")
if sizes and hasattr(self.main_window, 'main_splitter'):
self.main_window.main_splitter.setSizes(sizes)
except Exception as e:
self.logger.warning(f"No se pudo restaurar geometría: {e}")
def initialize(self):
"""Inicializa la configuración cargando datos"""
self._load_history()
self._restore_geometry()
def save_all(self):
"""Guarda toda la configuración"""
self._save_settings()
self._save_history()
def get_setting(self, key: str, default=None):
"""Obtiene un valor de configuración"""
return self.settings.get(key, default)
def set_setting(self, key: str, value):
"""Establece un valor de configuración"""
self.settings[key] = value