from __future__ import annotations from copy import deepcopy from pathlib import Path from PySide6.QtCore import QObject, Signal from PySide6.QtGui import QUndoStack from bedit_core.models import ID, Component, ComponentID, GraphImplementation, Port, PortID, Parameter, ParameterID from bedit_core.models import Document as CoreDocument from bedit_gui.commands.change_icon_command import ChangeIconCommand from bedit_gui.commands.equation_text_command import ChangeEquationTextCommand from bedit_gui.commands.port_commands import AddPortCommand, ChangePortCommand, RemovePortCommand from bedit_gui.commands.param_commands import AddParamCommand, ChangeParamCommand, RemoveParamCommand from bedit_gui.commands.rename_component_command import RenameComponentCommand from bedit_gui.commands.rename_document_command import RenameDocumentCommand from bedit_gui.commands.simulation_database_command import ChangeSimulationDatabaseCommand from bedit_gui.commands.component_command import AddEmptyEquationComponent, AddEmptyGraphComponent, DeleteComponent, PasteComponents from bedit_gui.models import Icon, IconDatabase, SimulationDatabase from bedit_gui.services import document_files class Document(QObject): """The editable document currently owned by the GUI application.""" model_changed = Signal(object) path_changed = Signal(object) modified_changed = Signal(bool) icon_changed = Signal(object, object) equation_text_changed = Signal(object, str) simulation_database_changed = Signal(object) def __init__(self, parent: QObject | None = None) -> None: super().__init__(parent) self.undo_stack = QUndoStack(self) self.undo_stack.cleanChanged.connect(self._on_clean_changed) self._model = self._new_model() self._path: Path | None = None self.undo_stack.setClean() @property def model(self) -> CoreDocument: return self._model @property def path(self) -> Path | None: return self._path @property def modified(self) -> bool: return not self.undo_stack.isClean() def new(self) -> None: self._replace(self._new_model(), None) def open(self, path: str | Path) -> None: file_path = Path(path) model = document_files.load(file_path) self._replace(model, file_path) def save(self) -> None: if self._path is None: raise ValueError("the document does not have a file path") document_files.save(self._model, self._path) self.undo_stack.setClean() def save_as(self, path: str | Path) -> None: file_path = Path(path) document_files.save(self._model, file_path) if file_path != self._path: self._path = file_path self.path_changed.emit(file_path) self.undo_stack.setClean() def _replace(self, model: CoreDocument, path: Path | None) -> None: self.undo_stack.clear() self._model = model self._path = path self.model_changed.emit(model) self.path_changed.emit(path) self.undo_stack.setClean() def _on_clean_changed(self, clean: bool) -> None: self.modified_changed.emit(not clean) @staticmethod def _new_model() -> CoreDocument: return CoreDocument( format_version=1, id=ID(), name="Untitled", root={}, ) def rename(self, name: str) -> None: self.undo_stack.push(RenameDocumentCommand(self, name)) def rename_component(self, component: Component, name: str) -> None: self.undo_stack.push(RenameComponentCommand(self, component, name)) def component_id(self, component: Component) -> ComponentID: def find(components: dict[ComponentID, Component]) -> ComponentID | None: for component_id, candidate in components.items(): if candidate is component: return component_id if isinstance(candidate.implementation, GraphImplementation): found = find(candidate.implementation.graph.components) if found is not None: return found return None component_id = find(self.model.root) if component_id is None: raise ValueError("component is not part of this document") return component_id def stored_component_icon(self, component_id: ComponentID) -> Icon | None: database = self._icon_database(False) return deepcopy(database.icons.get(component_id)) if database is not None else None def component_icon(self, component_id: ComponentID) -> Icon: return self.stored_component_icon(component_id) or Icon() def change_icon(self, component_id: ComponentID, icon: Icon) -> None: self.undo_stack.push(ChangeIconCommand(self, component_id, icon)) def stored_simulation_database(self) -> SimulationDatabase | None: database = self._simulation_database(False) return deepcopy(database) if database is not None else None def simulation_database(self) -> SimulationDatabase: return self.stored_simulation_database() or SimulationDatabase() def change_simulation_database(self, database: SimulationDatabase) -> None: if database != self.stored_simulation_database(): self.undo_stack.push(ChangeSimulationDatabaseCommand(self, database)) def _set_simulation_database(self, database: SimulationDatabase | None) -> None: if database is None: if self.model.metadata is not None: self.model.metadata.pop("simulation_database", None) else: if self.model.metadata is None: self.model.metadata = {} self.model.metadata["simulation_database"] = deepcopy(database) self.simulation_database_changed.emit(self.stored_simulation_database()) def _simulation_database(self, create: bool) -> SimulationDatabase | None: metadata = self.model.metadata value = metadata.get("simulation_database") if metadata is not None else None if isinstance(value, dict): value = SimulationDatabase.from_data(value) metadata["simulation_database"] = value if isinstance(value, SimulationDatabase): return value if not create: return None if metadata is None: metadata = {} self.model.metadata = metadata database = SimulationDatabase() metadata["simulation_database"] = database return database def _set_component_icon(self, component_id: ComponentID, icon: Icon | None) -> None: if icon is None: database = self._icon_database(False) if database is not None: database.icons.pop(component_id, None) if not database.icons: self.model.metadata.pop("icon_database", None) else: self._icon_database(True).icons[component_id] = deepcopy(icon) self.icon_changed.emit(component_id, self.stored_component_icon(component_id)) def _icon_database(self, create: bool) -> IconDatabase | None: metadata = self.model.metadata value = metadata.get("icon_database") if metadata is not None else None if isinstance(value, dict): value = IconDatabase.from_data(value) metadata["icon_database"] = value if isinstance(value, IconDatabase): return value if not create: return None if metadata is None: metadata = {} self.model.metadata = metadata database = IconDatabase() metadata["icon_database"] = database return database def update_component_ports(self, component: Component, ports: dict[PortID, Port]) -> None: current = component.interface.ports removed = [ RemovePortCommand(self, component, port_id) for port_id in current.keys() - ports.keys() ] added = [ AddPortCommand(self, component, port_id, ports[port_id]) for port_id in ports.keys() - current.keys() ] changed = [ ChangePortCommand(self, component, port_id, ports[port_id]) for port_id in current.keys() & ports.keys() if current[port_id] != ports[port_id] ] commands = [*removed, *added, *changed] if not commands: return self.undo_stack.beginMacro("Edit interface") for command in commands: self.undo_stack.push(command) self.undo_stack.endMacro() def update_component_params(self, component: Component, params: dict[ParameterID, Parameter]) -> None: current = component.parameters removed = [ RemoveParamCommand(self, component, param_id) for param_id in current.keys() - params.keys() ] added = [ AddParamCommand(self, component, param_id, params[param_id]) for param_id in params.keys() - current.keys() ] changed = [ ChangeParamCommand(self, component, param_id, params[param_id]) for param_id in current.keys() & params.keys() if current[param_id] != params[param_id] ] commands = [*removed, *added, *changed] if not commands: return self.undo_stack.beginMacro("Edit parameter") for command in commands: self.undo_stack.push(command) self.undo_stack.endMacro() def update_component_equation_text(self, component: Component, section: str, text: list[str], edit_id: int) -> None: command = ChangeEquationTextCommand(self, component, section, text, edit_id) if command.old_text != command.new_text: self.undo_stack.push(command) def add_empty_graph_component(self, component: Component) -> None: if isinstance(component.implementation, GraphImplementation): command = AddEmptyGraphComponent(self, component) command.component.name = self._unique_component_name(component.implementation.graph.components, command.component.name) self.undo_stack.push(command) def add_empty_equation_component(self, component: Component) -> None: if isinstance(component.implementation, GraphImplementation): command = AddEmptyEquationComponent(self, component) command.component.name = self._unique_component_name(component.implementation.graph.components, command.component.name) self.undo_stack.push(command) def delete_component(self, component: Component) -> None: self.undo_stack.push(DeleteComponent(self, component)) def delete_components(self, components: list[Component]) -> None: if not components: return self.undo_stack.beginMacro("Delete components") for component in components: self.undo_stack.push(DeleteComponent(self, component)) self.undo_stack.endMacro() def paste_components(self, target: dict[ComponentID, Component], components: dict[ComponentID, Component], icons: dict[ComponentID, Icon]) -> None: if not components: return names = {component.name for component in target.values()} for component in components.values(): component.name = self._unique_name(names, component.name) names.add(component.name) self.undo_stack.push(PasteComponents(self, target, components, icons)) @staticmethod def _unique_component_name(components: dict[ComponentID, Component], name: str) -> str: return Document._unique_name({component.name for component in components.values()}, name) @staticmethod def _unique_name(names: set[str], name: str) -> str: if name not in names: return name index = 0 while f"{name}_{index}" in names: index += 1 return f"{name}_{index}"