--- a/src/model.cpp Mon Sep 27 21:04:45 2021 +0300 +++ b/src/model.cpp Tue Sep 28 00:10:29 2021 +0300 @@ -18,6 +18,7 @@ #include <QBrush> #include <QFile> +#include <QFileInfo> #include <QFont> #include "model.h" #include "modeleditcontext.h" @@ -36,7 +37,7 @@ */ Model::Model(const QString& path, QObject *parent) : QAbstractListModel{parent}, - path{path} + storedPath{path} { connect(this, &Model::dataChanged, [&](){ this->needRecache = true; }); } @@ -187,6 +188,39 @@ } /** + * @brief Gets the path to the model + * @return path + */ +const QString& Model::path() const +{ + return this->storedPath; +} + +/** + * @brief Sets the path to the model + * @param path New path to use + */ +void Model::setPath(const QString &path) +{ + this->storedPath = path; + this->header.name = QFileInfo{path}.fileName(); + // Update the "Name: 1234.dat" comment + if (this->body.size() >= 2) + { + const ldraw::id_t id = this->body[1]->id; + if (this->isA<ldraw::MetaCommand>(id)) + { + const QString& textBody = this->body[1]->getProperty<ldraw::Property::Text>(); + if (textBody.startsWith("Name: ")) + { + auto editor = this->edit(); + editor.setObjectProperty<ldraw::Property::Text>(id, "Name: " + this->header.name); + } + } + } +} + +/** * @brief Gets the GL polygons of the object at the specified position in the model * @param index Index of object in the model * @param polygons_out Vector to add polygons into @@ -270,16 +304,60 @@ /** * @brief Write out the model as text */ -void Model::save() const +bool Model::save(QTextStream &errors) const { - QFile file{this->path}; + QFile file{this->storedPath}; if (file.open(QIODevice::WriteOnly)) { QTextStream out{&file}; for (const ModelObjectPointer& object : this->body) { - out << object.get()->textRepresentation() << "\r\n"; + out << object.get()->toLDrawCode() << "\r\n"; } file.close(); + if (out.status() != QTextStream::Ok) + { + errors << tr("Write error while writing to %1").arg(this->storedPath); + return false; + } + else + { + return true; + } + } + else + { + errors << tr("Could not open %1 for writing: %2") + .arg(this->storedPath) + .arg(file.errorString()); + return false; + } +} + +/** + * @brief Modifies the !LDRAW_ORG line so that it becomes unofficial + */ +void Model::makeUnofficial() +{ + if (this->body.size() >= 4) + { + const ldraw::id_t id = this->body[3]->id; + if (this->isA<ldraw::MetaCommand>(id)) + { + const QString& body = this->body[3]->getProperty<ldraw::Property::Text>(); + if (body.startsWith("!LDRAW_ORG ") and not body.startsWith("!LDRAW_ORG Unofficial_")) + { + QStringList tokens = body.split(" "); + tokens[1] = "Unofficial_" + tokens[1]; + // Remove the UPDATE tag + if (tokens.size() >= 4 && tokens[2] == "UPDATE") + { + tokens.removeAt(3); + tokens.removeAt(2); + } + EditContext editor = this->edit(); + editor.setObjectProperty<ldraw::Property::Text>(id, tokens.join(" ")); + } + } } } \ No newline at end of file