File indexing completed on 2025-02-09 06:01:30
0001 // SPDX-License-Identifier: GPL-2.0-or-later 0002 // SPDX-FileCopyrightText: 2023 Louis Schul <schul9louis@gmail.com> 0003 0004 #include "documentHandler.h" 0005 // #include <QDebug> 0006 #include <QFile> 0007 #include <QJsonDocument> 0008 #include <QTextStream> 0009 0010 DocumentHandler::DocumentHandler(QObject *parent) 0011 : QObject(parent) 0012 { 0013 } 0014 0015 QString DocumentHandler::readFile(const QString &path) 0016 { 0017 QFile file(path); 0018 0019 QString line = QStringLiteral("\n"); // The parser will still receive something even if the file is empty 0020 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { 0021 QTextStream stream(&file); 0022 while (!stream.atEnd()) { 0023 line.append(stream.readLine() + QStringLiteral("\n")); 0024 } 0025 if (line.length() > 3) 0026 line.remove(line.length() - 1, 1); // Remove the last \n 0027 0028 if (line.length() > 3) 0029 line.remove(0, 1); // Remove the first \n 0030 } 0031 file.close(); 0032 return line; 0033 } 0034 0035 void DocumentHandler::writeFile(const QString ¬e, const QString &path) 0036 { 0037 QFile file(path); 0038 if (file.open(QIODevice::WriteOnly)) { 0039 QTextStream stream(&file); 0040 stream << note << Qt::endl; 0041 } 0042 file.close(); 0043 } 0044 0045 QString DocumentHandler::getCssStyle(const QString &path) 0046 { 0047 QString style; 0048 if (QFile::exists(path)){ 0049 style = readFile(path); 0050 } else { 0051 style = readFile(QStringLiteral(":/KleverStyle.css")); 0052 } 0053 0054 return style; 0055 } 0056 0057 bool DocumentHandler::checkForHeader(const QString &path, const QString &header) 0058 { 0059 QFile file(path); 0060 if (header.isEmpty()) 0061 return false; 0062 0063 bool found = false; 0064 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { 0065 QTextStream stream(&file); 0066 while (!stream.atEnd()) { 0067 if (stream.readLine().trimmed() == header) { 0068 found = true; 0069 break; 0070 } 0071 } 0072 } 0073 file.close(); 0074 return found; 0075 } 0076 0077 bool DocumentHandler::saveJson(const QJsonObject &json, const QString &path) 0078 { 0079 QJsonDocument doc = QJsonDocument(json); 0080 0081 QFile file(path); 0082 if (file.open(QIODevice::WriteOnly)) { 0083 if (file.write(doc.toJson()) < 0) 0084 return false; 0085 file.close(); 0086 return true; 0087 } 0088 0089 return false; 0090 } 0091 0092 QJsonObject DocumentHandler::getJson(const QString &jsonPath) 0093 { 0094 QFile file(jsonPath); 0095 0096 QJsonObject json; 0097 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { 0098 json = QJsonDocument::fromJson(file.readAll()).object(); 0099 file.close(); 0100 } 0101 return json; 0102 }