src/documentmanager.cpp

Sun, 03 Nov 2019 13:07:04 +0200

author
Teemu Piippo <teemu@hecknology.net>
date
Sun, 03 Nov 2019 13:07:04 +0200
changeset 10
e249d97c7fe6
parent 8
44679e468ba9
child 12
fe67489523b5
permissions
-rw-r--r--

fixed translations being updated twice at the same time, that's bad

#include <QFile>
#include <QDir>
#include <QFileInfo>
#include "documentmanager.h"
#include "modeleditcontext.h"
#include "objecttypes/comment.h"
#include "parser.h"

/**
 * @brief Constructs a new document manager
 * @param parent Parent object
 */
DocumentManager::DocumentManager(QObject* parent) :
	QObject{parent}
{
}

/**
 * @brief Creates a new model.
 * @returns the name to the new model
 */
QString DocumentManager::newModel()
{
	const QString name = makeNewModelName();
	this->openModels.emplace(name, new Model);
	return name;
}

/**
 * @brief Looks for a model by name
 * @param name Name of the model
 * @returns model or null
 * '
 */
Model* DocumentManager::findModelByName(const QString& name)
{
	const auto iterator = this->openModels.find(name);
	if (iterator == std::end(this->openModels))
	{
		return nullptr;
	}
	else
	{
		return iterator->second.get();
	}
}

QString pathToName(const QFileInfo& path)
{
	static const char* paths[] = {
		"s",
		"48"
		"8"
	};
	const QString baseName = path.fileName();
	const QString dirName = QFileInfo{path.dir().path()}.fileName();
	QString result;
	if (utility::contains(paths, dirName))
	{
		result = dirName + "\\" + baseName;
	}
	else
	{
		result = baseName;
	}
	return result;
}

QString DocumentManager::openModel(const QString& path, QTextStream& errorStream)
{
	QFile file{path};
	const QString name = pathToName(path);
	file.open(QFile::ReadOnly | QFile::Text);
	std::unique_ptr<Model> newModel = std::make_unique<Model>();
	QTextStream textStream{&file};
	Model::EditContext editor = newModel->edit();
	Parser parser{file};
	parser.parseBody(editor);
	QString result;
	if (file.error() == QFile::NoError)
	{
		openModels[name] = std::move(newModel);
		result = name;
	}
	else
	{
		errorStream << file.errorString();
	}
	return result;
}

QString DocumentManager::makeNewModelName()
{
	untitledNameCounter += 1;
	return "untitled-" + QString::number(untitledNameCounter);
}

mercurial