Sélectionner une révision Git
VivyDocument.cc 13,06 Kio
#include "VivyDocument.hh"
#include "../Utils.hh"
#include <QFileInfo>
#include <QDir>
#include <QString>
#include <QStringList>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QTextStream>
using namespace Vivy;
// Runtime document version, don't set it in the header!!!
QString VivyDocument::runtimeVersion = QStringLiteral("alpha");
VivyDocument::VivyDocument(const QString &documentPath, Options opt)
: AbstractDocument(AbstractDocument::Type::Vivy, documentPath)
, documentOptions(opt)
{
// Ignore some things in case of memory document creation because no real
// document with an extension is available.
if (opt & MemoryDocumentCreation) {
documentName = documentPath;
documentLocation = QDir::home();
}
// Load a real document
else {
QFileInfo fileInfo(name);
QFile file(name);
documentName = fileInfo.baseName();
documentLocation = fileInfo.absoluteDir();
if ((fileInfo.completeSuffix() != fileSuffix))
throw std::runtime_error("Invalid file suffix");
if (!file.exists() || !fileInfo.isFile() ||
!file.open(QIODevice::ReadOnly | QIODevice::Text))
throw std::runtime_error("Document doesn't exists");
QTextStream fileContent(&file);
QJsonParseError jsonError;
QJsonDocument json = QJsonDocument::fromJson(fileContent.readAll().toUtf8(), &jsonError);
if (json.isNull())
throw std::runtime_error("Json error " + jsonError.errorString().toStdString());
loadSaveJsonDocumentFile(json);
}
}
void
VivyDocument::save()
{
if (documentOptions & MemoryDocumentCreation)
throw std::logic_error("You can't save a memory document");
const bool needExt = !documentName.endsWith(fileSuffix);
const QString filepath = documentLocation.absolutePath() + QDir::separator() + documentName +
(needExt ? "." + fileSuffix : "");
QFile file(filepath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
throw std::runtime_error("Failed to open file in WO+Text mode: " + filepath.toStdString());
QTextStream writter(&file);
QJsonDocument json = getSaveJsonDocumentFile();
writter << json.toJson(QJsonDocument::Compact);
file.close();