"""Unified application configuration for SimVX.
Merges editor and IDE settings into a single ``~/.config/simvx/config.json``
file with ``general``, ``editor``, and ``ide`` sections.
"""
import json
import logging
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
log = logging.getLogger(__name__)
CONFIG_DIR = Path.home() / ".config" / "simvx"
CONFIG_FILE = CONFIG_DIR / "config.json"
# Per-project config: overrides user config when present. Located at
# ``<project_root>/.simvx/config.json``. Follows the ``.editorconfig`` /
# ``.vscode/settings.json`` precedent: per-project settings supersede
# global ones on a per-key basis.
PROJECT_CONFIG_DIRNAME = ".simvx"
PROJECT_CONFIG_FILENAME = "config.json"
[docs]
def project_config_path(project_root: Path | str) -> Path:
"""Return the ``.simvx/config.json`` path for a project root.
Always returns a path even if no file exists yet; callers should test
``.exists()`` before reading.
"""
return Path(project_root) / PROJECT_CONFIG_DIRNAME / PROJECT_CONFIG_FILENAME
# ---------------------------------------------------------------------------
# Section dataclasses
# ---------------------------------------------------------------------------
[docs]
@dataclass
class GeneralConfig:
"""Settings shared by both editor and IDE."""
theme_preset: str = "dark"
font_size: float = 11.0
window_width: int = 1600
window_height: int = 900
recent_files: list[str] = field(default_factory=list)
recent_folders: list[str] = field(default_factory=list)
recent_projects: list[dict[str, str]] = field(default_factory=list)
custom_shortcuts: dict[str, str] = field(default_factory=dict)
[docs]
@dataclass
class EditorSection:
"""Editor-specific settings."""
dock_layout: dict[str, Any] = field(default_factory=dict)
show_grid: bool = True
grid_size: float = 1.0
grid_subdivisions: int = 4
snap_enabled: bool = False
snap_size: float = 0.5
auto_save_interval: int = 300
hot_reload_enabled: bool = True
[docs]
@dataclass
class IDESection:
"""IDE-specific settings."""
tab_size: int = 4
insert_spaces: bool = True
show_line_numbers: bool = True
show_minimap: bool = True
show_code_folding: bool = True
show_indent_guides: bool = True
auto_save: bool = False
format_on_save: bool = True
sidebar_width: int = 250
bottom_panel_height: int = 200
sidebar_visible: bool = True
bottom_panel_visible: bool = True
lsp_enabled: bool = True
lsp_command: str = "pylsp"
lsp_args: list[str] = field(default_factory=list)
lint_enabled: bool = True
lint_on_save: bool = True
lint_command: str = "ruff check --output-format=json"
format_command: str = "ruff format"
python_path: str = ""
venv_path: str = ""
auto_detect_venv: bool = True
debug_adapter: str = "debugpy"
keybindings: dict[str, str] = field(default_factory=dict)
# ---------------------------------------------------------------------------
# AppConfig
# ---------------------------------------------------------------------------
[docs]
@dataclass
class AppConfig:
"""Unified config with sections, persisted in ``~/.config/simvx/config.json``."""
general: GeneralConfig = field(default_factory=GeneralConfig)
editor: EditorSection = field(default_factory=EditorSection)
ide: IDESection = field(default_factory=IDESection)
# -- Persistence ---------------------------------------------------------
[docs]
def load(self) -> None:
"""Load from ``config.json``. Missing or malformed file leaves defaults."""
if not CONFIG_FILE.exists():
return
try:
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return
self._apply_dict(data)
[docs]
def load_with_project(self, project_root: Path | str | None) -> None:
"""Load user config, then overlay any ``.simvx/config.json`` for the project.
Project config is loaded ON TOP of the already-applied user config:
every key present in the project file replaces the user-config value
for that key. Sections / fields omitted from the project file keep
their user-config (or default) value. This mirrors the
``.editorconfig`` / ``.vscode/settings.json`` precedent: flat
per-key override, **no** deep dict merging (a project ``editor``
dict replaces the user one wholesale only for the fields it sets,
thanks to ``_update_dataclass`` skipping absent keys).
Passing ``None`` is equivalent to calling :meth:`load`.
"""
self.load()
if project_root is None:
return
p = project_config_path(project_root)
if not p.exists():
return
try:
data = json.loads(p.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
log.warning("Could not parse project config %s: %s", p, exc)
return
self._apply_dict(data)
[docs]
def save_project(self, project_root: Path | str, *, sections: list[str] | None = None) -> None:
"""Persist the **current** config to ``<project_root>/.simvx/config.json``.
When *sections* is given, only those top-level sections are written
(e.g. ``["editor"]`` writes just the editor block): useful for
committing project-level overrides without leaking machine-specific
``general`` fields like ``recent_files`` into the project repo.
"""
path = project_config_path(project_root)
path.parent.mkdir(parents=True, exist_ok=True)
full = {
"general": asdict(self.general),
"editor": asdict(self.editor),
"ide": asdict(self.ide),
}
if sections is not None:
full = {k: full[k] for k in sections if k in full}
path.write_text(json.dumps(full, indent=2) + "\n", encoding="utf-8")
[docs]
def save(self) -> None:
"""Write current config to ``config.json``."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
data = {
"general": asdict(self.general),
"editor": asdict(self.editor),
"ide": asdict(self.ide),
}
CONFIG_FILE.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
# -- Recent helpers ------------------------------------------------------
[docs]
def add_recent_file(self, path: str) -> None:
if path in self.general.recent_files:
self.general.recent_files.remove(path)
self.general.recent_files.insert(0, path)
self.general.recent_files = self.general.recent_files[:20]
[docs]
def add_recent_folder(self, path: str) -> None:
if path in self.general.recent_folders:
self.general.recent_folders.remove(path)
self.general.recent_folders.insert(0, path)
self.general.recent_folders = self.general.recent_folders[:10]
# -- Internal helpers ----------------------------------------------------
def _apply_dict(self, data: dict[str, Any]) -> None:
"""Apply a sectioned dict to this config."""
if "general" in data:
_update_dataclass(self.general, data["general"])
if "editor" in data:
_update_dataclass(self.editor, data["editor"])
if "ide" in data:
_update_dataclass(self.ide, data["ide"])
def _update_dataclass(obj: object, data: dict[str, Any]) -> None:
"""Set fields on *obj* from *data*, skipping unknown keys."""
for key, value in data.items():
if hasattr(obj, key):
setattr(obj, key, value)