Files
BEdit/src/bedit_gui/documents/document.py

198 lines
7.3 KiB
Python

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.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.models import Icon, IconDatabase
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)
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 _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()