import json import logging from os import path, makedirs from typing import Any from PySide6.QtCore import QAbstractListModel, QByteArray, QModelIndex, QObject, QPersistentModelIndex, QStandardPaths, QUrl, Qt, Signal, Slot, Property from PySide6.QtQml import QmlElement from kodereviewer.project import Project QML_IMPORT_NAME = "org.deprecated.kodereviewer" QML_IMPORT_MAJOR_VERSION = 1 logger = logging.getLogger(__name__) @QmlElement class ProjectModel(QAbstractListModel): """Projects list!""" projects: list[Project] NameRole = Qt.ItemDataRole.UserRole + 1 OwnerRole = NameRole + 1 UrlRole = OwnerRole + 1 def __init__(self): super().__init__() self.projects = [] project_config = self._project_file() try: with open(project_config) as fp: data = json.load(fp) if isinstance(data, list): self._load_projects(data) except OSError: logger.exception(f'Cannot open {project_config}') def _project_file(self) -> str: app_data = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) project_config = path.join(app_data, 'projects.json') return project_config def data(self, index: QModelIndex | QPersistentModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> object: project = self.projects[index.row()] if role == Qt.ItemDataRole.DisplayRole: return project.name if role == self.NameRole: return project.name if role == self.OwnerRole: return project.owner if role == self.UrlRole: return project.url return None def rowCount(self, parent: QModelIndex | QPersistentModelIndex = QModelIndex()) -> int: return len(self.projects) def roleNames(self) -> dict[int, QByteArray]: return { self.NameRole: QByteArray(b"name"), self.OwnerRole: QByteArray(b"owner"), self.UrlRole: QByteArray(b"url") } @Slot(int, result=Project) def get(self, index: int) -> Project: return self.projects[index] def _load_projects(self, data: list[dict[str, Any]]) -> None: for project in data: self.projects.append(Project( project['name'], project['owner'], project['url'] )) def _save_projects(self): project_config = self._project_file() data = [{'name': project.name, 'owner': project.owner, 'url': project.url} for project in self.projects] if not path.exists(project_config): dir = path.dirname(project_config) makedirs(dir) with open(project_config, 'w') as fp: json.dump(data, fp) @Slot(str, str, str) def add(self, name: str, owner: str, url: str) -> None: self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self.projects.append(Project(name, owner, url)) self._save_projects() self.endInsertRows()