/* Copyright 2006-2023 The QElectroTech Team This file is part of QElectroTech. QElectroTech is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. QElectroTech is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QElectroTech. If not, see . */ #include "elementslocation.h" #include "../elementscollectioncache.h" #include "../factory/elementpicturefactory.h" #include "../qetapp.h" #include "../qetgraphicsitem/element.h" #include "../qetproject.h" #include "../qetxml.h" #include "xmlelementcollection.h" #include // make this class usable with QVariant int ElementsLocation::MetaTypeId = qRegisterMetaType("ElementsLocation"); /** @brief ElementsLocation::ElementsLocation Constructor */ ElementsLocation::ElementsLocation() {} /** @brief ElementsLocation::ElementsLocation \~ @param path : Item location path \~French Chemin de l'emplacement de l'element \~ @param project : Project of the location of the element \~French Projet de l'emplacement de l'element */ ElementsLocation::ElementsLocation(const QString &path, QETProject *project) : m_project(project) { setPath(path); } /** @brief ElementsLocation::~ElementsLocation Destructeur */ ElementsLocation::~ElementsLocation() { } /** @brief ElementsLocation::ElementsLocation The copy constructor \~French Constructeur de copie \~ @param other : Alternate item location to copy \~French Autre emplacement d'element a copier */ ElementsLocation::ElementsLocation(const ElementsLocation &other) : m_collection_path(other.m_collection_path), m_file_system_path(other.m_file_system_path), m_project(other.m_project) {} /** @brief ElementsLocation::ElementLocation Constructor, build an ElementLocation from a QMimeData, the mime data format must be "application/x-qet-element-uri" or "application/x-qet-category-uri". This location can be null even if format is valid. @param data */ ElementsLocation::ElementsLocation(const QMimeData *data) { if (data->hasFormat("application/x-qet-element-uri") || data->hasFormat("application/x-qet-category-uri")) setPath(data->text()); } /** @brief ElementsLocation::operator = Assignment operator \~French Operateur d'affectation \~ @param other : Other item location to assign \~French Autre emplacement d'element a affecter \~ @return *this ElementsLocation */ ElementsLocation &ElementsLocation::operator=(const ElementsLocation &other) { m_collection_path = other.m_collection_path; m_file_system_path = other.m_file_system_path; m_project = other.m_project; return(*this); } /** @brief ElementsLocation::operator == \~French Operateur de comparaison \~ @param other : other item location to compare \~French Autre emplacement d'element a comparer \~ @return true if other and this ElementsLocation are identical, false otherwise \~French true si other et cet ElementsLocation sont identiques, false sinon */ bool ElementsLocation::operator==(const ElementsLocation &other) const { return( m_collection_path == other.m_collection_path &&\ m_project == other.m_project ); } /** @brief ElementsLocation::operator != Operateur de comparaison @param other Autre emplacement d'element a comparer @return true si other et cet ElementsLocation sont differents, false sinon */ bool ElementsLocation::operator!=(const ElementsLocation &other) const { return( m_collection_path != other.m_collection_path ||\ m_project != other.m_project ); } /** @brief ElementsLocation::baseName @return The base name of the element or directory. Unlike ElementsLocation::fileName, this method don't return the extension name. For example if this location represent an element they return myElement. @see fileName() */ QString ElementsLocation::baseName() const { QRegularExpression regexp("^.*(?[^/]+)\\.elmt$"); if (!regexp.isValid()) { qWarning() <<"this is an error in the code" << regexp.errorString() << regexp.patternErrorOffset(); return QString(); } QRegularExpressionMatch match = regexp.match(m_collection_path); if (!match.hasMatch()) { qDebug()<<"no Match => return" <[0-9])\\+(?embed://*.*)$"); if (!re.isValid()) { qWarning() < return" <[a-z]+://.*)/.*$"); if (!re.isValid()) { qWarning() < return" <embeddedElementCollection() ->exist(collectionPath(false)); } else { if (fileSystemPath().isEmpty()) return false; if (isDirectory()) { QDir dir(fileSystemPath()); return dir.exists(); } else if (isElement()) return QFile::exists(fileSystemPath()); else return false; } } /** @brief ElementsLocation::isWritable @return True if this element can be writable (can use set xml) */ bool ElementsLocation::isWritable() const { if (m_project) return !m_project->isReadOnly(); else if (isFileSystem()) { if (fileSystemPath().startsWith(QETApp::commonElementsDirN())) return false; else return true; } return false; } /** @brief ElementsLocation::projectCollection @return If this location represente a item in an embedded project collection, return this collection else return nullptr. */ XmlElementCollection *ElementsLocation::projectCollection() const { if (m_project) return m_project->embeddedElementCollection(); else return nullptr; } /** @brief ElementsLocation::nameList @return the namelist of the represented element or directory. If namelist can't be set, return a empty namelist */ NamesList ElementsLocation::nameList() { NamesList nl; if (isElement()) { nl.fromXml(pugiXml()); } if (isDirectory()) { if (m_project) nl.fromXml(m_project->embeddedElementCollection() ->directory(collectionPath(false))); else { //Open the qet_directory file, // to get the traductions name of this dir QFile dir_conf(fileSystemPath() + "/qet_directory"); if (dir_conf.exists() && dir_conf.open( QIODevice::ReadOnly | QIODevice::Text)) { //Get the content of the file QDomDocument document; if (document.setContent(&dir_conf)) { QDomElement root = document .documentElement(); if (root.tagName() == "qet-directory") nl.fromXml(root); } } } } return nl; } /** @brief ElementsLocation::xml @return The definition of this element or directory. The definition can be null. */ QDomElement ElementsLocation::xml() const { if (!m_project) { QFile file (m_file_system_path); QDomDocument docu; if (docu.setContent(&file)) return docu.documentElement(); } else { QString str = m_collection_path; if (isElement()) { QDomElement element = m_project ->embeddedElementCollection() ->element(str.remove("embed://")); return element.firstChildElement("definition"); } else { QDomElement element = m_project ->embeddedElementCollection() ->directory(str.remove("embed://")); return element; } } return QDomElement(); } /** @brief ElementsLocation::pugiXml @return the xml document of this element or directory The definition can be null */ pugi::xml_document ElementsLocation::pugiXml() const { pugi::xml_document docu; //empty xml_document(); /* Except for linux OS (because linux keep in cache the file), * we keep in memory the xml * to avoid multiple access to file. * keep in memory the XML, * consumes a little more RAM, * for this reason we don't use it for linux to minimize the RAM footprint. */ #ifndef Q_OS_LINUX if (!m_string_stream.str().empty()) { docu.load_string(m_string_stream.str().c_str()); return docu; } #endif if (!m_project) { #ifndef Q_OS_LINUX if (docu.load_file(m_file_system_path.toStdString().c_str())) { docu.save(m_string_stream); } #else docu.load_file(m_file_system_path.toStdString().c_str()); #endif } else { //Get the xml dom from Qt xml and copie to pugi xml QDomDocument qdoc; QString str = m_collection_path; if (isElement()) { QDomElement element = m_project->embeddedElementCollection()->element(str.remove("embed://")); qdoc.appendChild(qdoc.importNode(element.firstChildElement("definition"),true)); } else { QDomElement element = m_project->embeddedElementCollection()->directory(str.remove("embed://")); qdoc.appendChild(qdoc.importNode(element, true)); } docu.load_string(qdoc.toString(4).toStdString().c_str()); } return docu; } /** @brief ElementsLocation::setXml Replace the current xml description by xml_document; The document element of xml_document must have tagname "definition" to be written This definition must be writable @param xml_document @return true if success */ bool ElementsLocation::setXml(const QDomDocument &xml_document) const { if (!isWritable()) return false; if (xml_document.documentElement().tagName() != "definition") { qDebug() << "ElementsLocation::setXml :" " tag name of document element isn't 'definition'"; return false; } if (isFileSystem()) { QString error; QETXML::writeXmlFile(xml_document, fileSystemPath(), &error); if (!error.isEmpty()) { qDebug() << "ElementsLocation::setXml error : " << error; return false; } else { return true; } } else if (isProject()) { //Element exist, we overwrite the existing element. if (exist()) { QDomElement dom_element = xml(); QDomNode parent_node = dom_element.parentNode(); parent_node.removeChild(dom_element); parent_node.appendChild(xml_document .documentElement() .cloneNode(true)); return true; } //Element doesn't exist, we create the element else { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove QString path_ = collectionPath(false); QRegExp rx ("^(.*)/(.*\\.elmt)$"); if (rx.exactMatch(path_)) { return project() ->embeddedElementCollection() ->addElementDefinition( rx.cap(1), rx.cap(2), xml_document .documentElement()); } else { qDebug() << "ElementsLocation::setXml :" " rx don't match"; } #else #if TODO_LIST #pragma message("@TODO remove code for QT 6 or later") # pragma message("@TODO ad Core5Compat to Cmake") #endif qDebug() << "Help code for QT 6 or later"; QString path_ = collectionPath(false); QRegularExpression rx("^(.*)/(.*\\.elmt)$"); if (rx.exactMatch(path_)) { return project() ->embeddedElementCollection() ->addElementDefinition( rx.cap(1), rx.cap(2), xml_document.documentElement()); } else { qDebug() << "ElementsLocation::setXml :" " rx don't match"; } #endif } } return false; } /** @brief ElementsLocation::uuid @return The uuid of the pointed element Uuid can be null */ QUuid ElementsLocation::uuid() const { if (!isElement()) { return QUuid(); } auto document = pugiXml(); auto uuid_node = document.document_element().child("uuid"); if (uuid_node.empty()) { return QUuid(); } return QUuid(uuid_node.attribute("uuid").as_string()); } /** @brief ElementLocation::icon @return The icon of the represented element. If icon can't be set, return a null QIcon */ QIcon ElementsLocation::icon() const { if (!m_project) { ElementsCollectionCache *cache = QETApp::collectionCache(); // Make a copy of this to keep this method const ElementsLocation loc(*this); if (cache->fetchElement(loc)) return QIcon(cache->pixmap()); } else { return QIcon(ElementPictureFactory::instance()->pixmap(*this)); } return QIcon(); } /** @brief ElementLocation::name @return The name of the represented element in the current local */ QString ElementsLocation::name() const { NamesList nl; nl.fromXml(pugiXml().document_element()); return nl.name(fileName()); } /** @brief ElementLocation::fileName @return Return the file name of the represented item, whatever the storage system (file system, xml collection) with is file extension. For example if this location represent an element, they return myElement.elmt. For a directory return myDirectory. @see baseName */ QString ElementsLocation::fileName() const { if (m_collection_path.isEmpty()) return QString(); QStringList qsl = m_collection_path.split("/"); if (qsl.isEmpty()) return QString(); else return qsl.last(); } /** @brief ElementsLocation::elementInformations @return the element information of the element represented by this location. If the location is a directory, the returned diagram context is empty */ DiagramContext ElementsLocation::elementInformations() const { DiagramContext context; if (isDirectory()) { return context; } context.fromXml(pugiXml().document_element().child( "elementInformations"), "elementInformation"); return context; } /** @brief operator << debug for processing ElementsLocation @param debug @param location @return debug msg */ QDebug operator<< (QDebug debug, const ElementsLocation &location) { QDebugStateSaver saver(debug); debug.noquote(); QString msg; msg += "ElementsLocation("; msg += (location.isProject()? location.projectCollectionPath() : location.collectionPath(true)); msg += location.exist()? ", true" : ", false"; msg +=")"; debug << msg; return debug; }