src/documentmanager.cpp

changeset 8
44679e468ba9
parent 5
593a658cba8e
child 12
fe67489523b5
--- a/src/documentmanager.cpp	Sat Oct 05 23:47:03 2019 +0300
+++ b/src/documentmanager.cpp	Sun Nov 03 12:17:41 2019 +0200
@@ -1,12 +1,96 @@
+#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}
 {
 }
 
-Model* DocumentManager::newModel()
+/**
+ * @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)
 {
-	openModels.emplace_back();
-	return openModels.back().get();
+	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