113 lines
2.3 KiB
C++
113 lines
2.3 KiB
C++
#include "Document.h"
|
|
#include "Feature.h"
|
|
#include "SketchFeature.h"
|
|
|
|
#include <QFile>
|
|
#include <QFileInfo>
|
|
#include <QJsonDocument>
|
|
#include <QJsonArray>
|
|
#include <QJsonObject>
|
|
|
|
Document::Document(QObject *parent) : QObject(parent)
|
|
{
|
|
}
|
|
|
|
Document::~Document()
|
|
{
|
|
clear();
|
|
}
|
|
|
|
void Document::addFeature(Feature* feature)
|
|
{
|
|
m_features.append(feature);
|
|
emit featureAdded(feature);
|
|
}
|
|
|
|
void Document::clear()
|
|
{
|
|
qDeleteAll(m_features);
|
|
m_features.clear();
|
|
m_fileName.clear();
|
|
emit cleared();
|
|
}
|
|
|
|
const QList<Feature*>& Document::features() const
|
|
{
|
|
return m_features;
|
|
}
|
|
|
|
void Document::setFileName(const QString& fileName)
|
|
{
|
|
m_fileName = fileName;
|
|
}
|
|
|
|
QString Document::fileName() const
|
|
{
|
|
if (m_fileName.isEmpty()) {
|
|
return "Untitled";
|
|
}
|
|
return QFileInfo(m_fileName).fileName();
|
|
}
|
|
|
|
bool Document::save(const QString& path) const
|
|
{
|
|
QJsonArray featuresArray;
|
|
for (const Feature* feature : m_features) {
|
|
QJsonObject featureObject;
|
|
feature->write(featureObject);
|
|
featuresArray.append(featureObject);
|
|
}
|
|
|
|
QJsonObject rootObject;
|
|
rootObject["features"] = featuresArray;
|
|
|
|
QJsonDocument doc(rootObject);
|
|
QFile file(path);
|
|
if (!file.open(QIODevice::WriteOnly)) {
|
|
return false;
|
|
}
|
|
|
|
file.write(doc.toJson());
|
|
return true;
|
|
}
|
|
|
|
bool Document::load(const QString& path)
|
|
{
|
|
QFile file(path);
|
|
if (!file.open(QIODevice::ReadOnly)) {
|
|
return false;
|
|
}
|
|
|
|
QByteArray data = file.readAll();
|
|
QJsonDocument doc = QJsonDocument::fromJson(data);
|
|
|
|
if (doc.isNull() || !doc.isObject()) {
|
|
return false;
|
|
}
|
|
|
|
clear();
|
|
|
|
QJsonObject rootObject = doc.object();
|
|
if (rootObject.contains("features") && rootObject["features"].isArray()) {
|
|
QJsonArray featuresArray = rootObject["features"].toArray();
|
|
for (const QJsonValue& value : featuresArray) {
|
|
QJsonObject obj = value.toObject();
|
|
if (obj.contains("type") && obj["type"].isString()) {
|
|
QString type = obj["type"].toString();
|
|
Feature* feature = nullptr;
|
|
|
|
if (type == "Sketch") {
|
|
feature = new SketchFeature("");
|
|
}
|
|
|
|
if (feature) {
|
|
feature->read(obj);
|
|
addFeature(feature);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|