Compare commits
40 Commits
main
...
99ed398c2f
| Author | SHA1 | Date | |
|---|---|---|---|
| 99ed398c2f | |||
| 3e6273cb7d | |||
| 2702b9c835 | |||
| 2ccbe3839a | |||
| 3266c99fc3 | |||
| b8fe4e6502 | |||
| acb8be5602 | |||
| 3610aa3841 | |||
| 0c3d711513 | |||
| b2f01a7990 | |||
| 1fc1b1715d | |||
| 0e1a0d4959 | |||
| 2c3d49db30 | |||
| c09aad88dc | |||
| e54204e394 | |||
| 772ab6b2ff | |||
| c75d35179b | |||
| 0166a00d9d | |||
| 432e81d4be | |||
| e21c899aac | |||
| 169d8f9f1e | |||
| d45b1098f9 | |||
| 4c906099eb | |||
| 144460b5aa | |||
| 5b5713c89f | |||
| a07e03d80d | |||
| 40e1dd3002 | |||
| 16c524f7a2 | |||
| 0dba9639e6 | |||
| 6a3725bde7 | |||
| 301d143b37 | |||
| 13b53683a5 | |||
| 7ba0304232 | |||
| d943f2d89a | |||
| bddb6df3ee | |||
| 7ec346b5a5 | |||
| b631f4200e | |||
| 0bbac662f4 | |||
| b3718c211f | |||
| fd32b85554 |
@ -1,6 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
project(GenericCore LANGUAGES CXX)
|
||||
set(TARGET_APP "GenericCore")
|
||||
project(${TARGET_APP} VERSION 0.1.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
@ -8,23 +9,40 @@ set(CMAKE_AUTORCC ON)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core LinguistTools)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools)
|
||||
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core LinguistTools)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools Gui)
|
||||
|
||||
set(TS_FILES GenericCore_en_US.ts)
|
||||
configure_file(CoreConfig.h.in CoreConfig.h)
|
||||
|
||||
add_library(GenericCore STATIC
|
||||
set(TS_FILES ${TARGET_APP}_en_US.ts)
|
||||
|
||||
add_library(${TARGET_APP} STATIC
|
||||
genericcore.cpp
|
||||
genericcore.h
|
||||
${TS_FILES}
|
||||
constants.h
|
||||
data/settingshandler.h data/settingshandler.cpp
|
||||
model/tablemodel.h model/tablemodel.cpp
|
||||
model/modelitem.h model/modelitem.cpp
|
||||
formats/jsonparser.h formats/jsonparser.cpp
|
||||
model/commands/insertrowscommand.h model/commands/insertrowscommand.cpp
|
||||
model/commands/removerowscommand.h model/commands/removerowscommand.cpp
|
||||
model/commands/edititemcommand.h model/commands/edititemcommand.cpp
|
||||
data/filehandler.h data/filehandler.cpp
|
||||
model/metadata.h
|
||||
formats/csvparser.h formats/csvparser.cpp
|
||||
# 3rd party libraries
|
||||
../3rdParty/rapidcsv/src/rapidcsv.h
|
||||
)
|
||||
|
||||
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Core)
|
||||
include_directories(${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
target_compile_definitions(GenericCore PRIVATE GENERICCORE_LIBRARY)
|
||||
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui)
|
||||
|
||||
target_compile_definitions(${TARGET_APP} PRIVATE ${TARGET_APP}_LIBRARY)
|
||||
|
||||
if(COMMAND qt_create_translation)
|
||||
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
else()
|
||||
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
endif()
|
||||
|
||||
2
CoreConfig.h.in
Normal file
2
CoreConfig.h.in
Normal file
@ -0,0 +1,2 @@
|
||||
#define CORE_NAME "${PROJECT_NAME}"
|
||||
#define CORE_VERSION "${PROJECT_VERSION}"
|
||||
15
constants.h
Normal file
15
constants.h
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef CONSTANTS_H
|
||||
#define CONSTANTS_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
/// Platform dependent
|
||||
#ifdef Q_OS_LINUX
|
||||
static const QString UPDATER_EXE = "maintenancetool";
|
||||
#elif defined(Q_OS_MAC)
|
||||
static const QString UPDATER_EXE = "maintenancetool.app/Contents/MacOS/maintenancetool";
|
||||
#elif defined(Q_OS_WIN)
|
||||
static const QString UPDATER_EXE = "maintenancetool.exe";
|
||||
#endif
|
||||
|
||||
#endif // CONSTANTS_H
|
||||
89
data/filehandler.cpp
Normal file
89
data/filehandler.cpp
Normal file
@ -0,0 +1,89 @@
|
||||
#include "filehandler.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QDir>
|
||||
#include <QJsonDocument>
|
||||
#include <QStandardPaths>
|
||||
|
||||
#include "../formats/csvparser.h"
|
||||
|
||||
bool FileHandler::saveToFile(const QJsonDocument& doc, const QString& fileName) {
|
||||
qDebug() << "saving file...";
|
||||
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
|
||||
qDebug() << path;
|
||||
|
||||
QDir dir;
|
||||
if (!dir.exists(path)) {
|
||||
dir.mkpath(path);
|
||||
}
|
||||
// qDebug() << path + fileName;
|
||||
const QString filePath = path + '/' + fileName;
|
||||
QFile file(filePath);
|
||||
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
|
||||
qWarning() << "can't open file";
|
||||
return false;
|
||||
}
|
||||
QTextStream out(&file);
|
||||
out.setEncoding(QStringConverter::Utf8);
|
||||
out << doc.toJson(QJsonDocument::Indented);
|
||||
return true;
|
||||
}
|
||||
|
||||
QByteArray FileHandler::loadJSONDataFromFile(const QString fileName) {
|
||||
QFile file;
|
||||
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
|
||||
file.setFileName(path + "/" + fileName);
|
||||
|
||||
QPair<QString, QByteArray> fileContent = getFileContent(path + "/" + fileName);
|
||||
|
||||
return fileContent.second;
|
||||
}
|
||||
|
||||
QList<ModelItemValues> FileHandler::getItemValuesFromCSVFile(const QString& filePath) {
|
||||
QList<ModelItemValues> result;
|
||||
QFile file;
|
||||
file.setFileName(filePath);
|
||||
if (file.exists()) {
|
||||
result = CsvParser::getItemsFromCSVFile(filePath);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool FileHandler::exportToCSVFile(const QList<QStringList>& rows, const QString& filePath) {
|
||||
return CsvParser::exportToCSVFile(rows, filePath);
|
||||
}
|
||||
|
||||
FileHandler::FileHandler() {}
|
||||
|
||||
/** Tries to open the file specified by the file path & returns the content
|
||||
* @brief FileHandler::getFileContent
|
||||
* @param filePath
|
||||
* @return Returns an error string (empty if successful) and the file content
|
||||
*/
|
||||
QPair<QString, QByteArray> FileHandler::getFileContent(const QString& filePath) {
|
||||
QString errorString = "";
|
||||
|
||||
QByteArray fileContent;
|
||||
QFile file;
|
||||
file.setFileName(filePath);
|
||||
if (file.exists()) {
|
||||
qDebug() << "File found, reading content...";
|
||||
const bool successfulOpened = file.open(QIODevice::ReadOnly | QIODevice::Text);
|
||||
if (successfulOpened) {
|
||||
// TODO learn and decide on the differences between "readAll" and using
|
||||
// streams
|
||||
fileContent = file.readAll();
|
||||
file.close();
|
||||
} else {
|
||||
errorString = "File could not be opened!";
|
||||
qWarning() << errorString;
|
||||
}
|
||||
} else {
|
||||
errorString = "File not found. Returning empty result...";
|
||||
qInfo() << errorString;
|
||||
}
|
||||
|
||||
const QPair<QString, QByteArray> result(errorString, fileContent);
|
||||
return result;
|
||||
}
|
||||
28
data/filehandler.h
Normal file
28
data/filehandler.h
Normal file
@ -0,0 +1,28 @@
|
||||
#ifndef FILEHANDLER_H
|
||||
#define FILEHANDLER_H
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
class QJsonDocument;
|
||||
class QString;
|
||||
class QByteArray;
|
||||
|
||||
class FileHandler {
|
||||
public:
|
||||
/// JSON
|
||||
static bool saveToFile(const QJsonDocument& doc, const QString& fileName);
|
||||
static QByteArray loadJSONDataFromFile(const QString fileName);
|
||||
|
||||
/// CSV
|
||||
static QList<ModelItemValues> getItemValuesFromCSVFile(const QString& filePath);
|
||||
static bool exportToCSVFile(const QList<QStringList>& rows, const QString& filePath);
|
||||
|
||||
private:
|
||||
explicit FileHandler();
|
||||
|
||||
static QPair<QString, QByteArray> getFileContent(const QString& filePath);
|
||||
};
|
||||
|
||||
#endif // FILEHANDLER_H
|
||||
43
data/settingshandler.cpp
Normal file
43
data/settingshandler.cpp
Normal file
@ -0,0 +1,43 @@
|
||||
#include "settingshandler.h"
|
||||
|
||||
#include <QSettings>
|
||||
|
||||
QVariantMap SettingsHandler::getSettings(QString group) {
|
||||
QSettings settings;
|
||||
QVariantMap result;
|
||||
|
||||
if (!group.isEmpty()) {
|
||||
settings.beginGroup(group);
|
||||
}
|
||||
|
||||
foreach (QString key, settings.allKeys()) {
|
||||
result.insert(key, settings.value(key));
|
||||
}
|
||||
|
||||
if (!group.isEmpty()) {
|
||||
settings.endGroup();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void SettingsHandler::saveSettings(QVariantMap settingMap, QString group) {
|
||||
qInfo() << "saving settings...";
|
||||
|
||||
QSettings settings;
|
||||
if (!group.isEmpty()) {
|
||||
settings.beginGroup(group);
|
||||
}
|
||||
|
||||
foreach (QString key, settingMap.keys()) {
|
||||
// qDebug() << "saving:" << key << "-" << settingMap.value(key);
|
||||
settings.setValue(key, settingMap.value(key));
|
||||
}
|
||||
if (!group.isEmpty()) {
|
||||
settings.endGroup();
|
||||
}
|
||||
|
||||
settings.sync();
|
||||
}
|
||||
|
||||
SettingsHandler::SettingsHandler() {}
|
||||
15
data/settingshandler.h
Normal file
15
data/settingshandler.h
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef SETTINGSHANDLER_H
|
||||
#define SETTINGSHANDLER_H
|
||||
|
||||
#include <QVariantMap>
|
||||
|
||||
class SettingsHandler {
|
||||
public:
|
||||
static QVariantMap getSettings(QString group = "");
|
||||
static void saveSettings(QVariantMap settingMap, QString group = "");
|
||||
|
||||
private:
|
||||
SettingsHandler();
|
||||
};
|
||||
|
||||
#endif // SETTINGSHANDLER_H
|
||||
158
formats/csvparser.cpp
Normal file
158
formats/csvparser.cpp
Normal file
@ -0,0 +1,158 @@
|
||||
#include "csvparser.h"
|
||||
|
||||
#include <QHash>
|
||||
#include <QLocale>
|
||||
#include <QVariant>
|
||||
|
||||
#include "../../3rdParty/rapidcsv/src/rapidcsv.h"
|
||||
#include "../model/metadata.h"
|
||||
|
||||
using namespace rapidcsv;
|
||||
|
||||
QList<ModelItemValues> CsvParser::getItemsFromCSVFile(const QString& fileName) {
|
||||
Document doc(fileName.toStdString());
|
||||
|
||||
const bool isCompatible = isCsvCompatible(doc);
|
||||
if (isCompatible) {
|
||||
const QList<ModelItemValues> result = createListItemsFromCsvEntries(doc);
|
||||
return result;
|
||||
} else {
|
||||
return QList<ModelItemValues>();
|
||||
}
|
||||
}
|
||||
|
||||
bool CsvParser::exportToCSVFile(const QList<QStringList>& rows, const QString& filePath) {
|
||||
Document doc(std::string(), LabelParams(0, -1));
|
||||
const QList<QString> headerNames = GET_HEADER_NAMES();
|
||||
for (int column = 0; column < headerNames.size(); ++column) {
|
||||
doc.SetColumnName(column, headerNames.at(column).toStdString());
|
||||
}
|
||||
for (int row = 0; row < rows.size(); ++row) {
|
||||
QStringList rowValues = rows.at(row);
|
||||
std::vector<std::string> rowValueStrings;
|
||||
for (int column = 0; column < rowValues.size(); ++column) {
|
||||
rowValueStrings.push_back(rowValues.at(column).toStdString());
|
||||
}
|
||||
doc.InsertRow(row, rowValueStrings);
|
||||
}
|
||||
doc.Save(filePath.toStdString());
|
||||
return true;
|
||||
}
|
||||
|
||||
CsvParser::CsvParser() {}
|
||||
|
||||
/** A CSV file is compatible if the following is true:
|
||||
* - there is a CSV column for every column in the table model
|
||||
* (except there are optional columns defined in the model)
|
||||
* @brief CsvParser::isCsvCompatible
|
||||
* @param doc
|
||||
* @return
|
||||
*/
|
||||
bool CsvParser::isCsvCompatible(const rapidcsv::Document& doc) {
|
||||
qInfo() << "Checking CSV document for compatiblity...";
|
||||
const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
for (const QString& headerName : GET_HEADER_NAMES()) {
|
||||
bool isHeaderNameFound = false;
|
||||
if (std::find(columnNames.begin(), columnNames.end(), headerName) != columnNames.end()) {
|
||||
qDebug() << QString("Header found in column names: %1").arg(headerName);
|
||||
} else {
|
||||
const QString errorString =
|
||||
QString("Couldn't find header name '%1' in CSV file. Aborting...").arg(headerName);
|
||||
qWarning() << errorString;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
QList<ModelItemValues> CsvParser::createListItemsFromCsvEntries(const rapidcsv::Document& doc) {
|
||||
QList<ModelItemValues> result;
|
||||
const int rowCount = doc.GetRowCount();
|
||||
const QList<QString> headerNames = GET_HEADER_NAMES();
|
||||
|
||||
/// get the values for all columns
|
||||
QHash<QString, std::vector<std::string>> columnValueMap = extractColumnValues(headerNames, doc);
|
||||
|
||||
/// get item values for each row
|
||||
for (int row = 0; row < rowCount; ++row) {
|
||||
const ModelItemValues itemValues = getItemValuesForRow(headerNames, columnValueMap, row);
|
||||
result.append(itemValues);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QHash<QString, std::vector<std::string>> CsvParser::extractColumnValues(
|
||||
const QList<QString> headerNames,
|
||||
const rapidcsv::Document& doc) {
|
||||
QHash<QString, std::vector<std::string>> columnValueMap;
|
||||
for (const QString& columnName : headerNames) {
|
||||
// NEXT add support for optional columns
|
||||
// if (optionalCsvHeaderNames.contains(columnName)) {
|
||||
// const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
// int columnIdx = doc.GetColumnIdx(columnName.toStdString());
|
||||
// if (columnIdx == -1) {
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
const std::vector<std::string> columnValues =
|
||||
doc.GetColumn<std::string>(columnName.toStdString());
|
||||
columnValueMap.insert(columnName, columnValues);
|
||||
}
|
||||
|
||||
return columnValueMap;
|
||||
}
|
||||
|
||||
ModelItemValues CsvParser::getItemValuesForRow(
|
||||
const QList<QString>& headerNames,
|
||||
const QHash<QString, std::vector<std::string>>& columnValueMap,
|
||||
const int row) {
|
||||
ModelItemValues result;
|
||||
for (const QString& columnName : headerNames) {
|
||||
if (!columnValueMap.contains(columnName)) {
|
||||
continue;
|
||||
}
|
||||
int role = ROLE_NAMES.key(columnName.toLatin1());
|
||||
std::string valueString = columnValueMap.value(columnName).at(row);
|
||||
|
||||
QVariant value = parseItemValue(role, valueString);
|
||||
if (value.isValid()) {
|
||||
result[role] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QVariant CsvParser::parseItemValue(const int role, const std::string& valueString) {
|
||||
QVariant result;
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
/// string values
|
||||
result = QString::fromStdString(valueString);
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
/// int values
|
||||
|
||||
/// GetColumn<int> crashed (probably because of the empty values)
|
||||
/// so the strings will be processed later
|
||||
const QString intAsString = QString::fromStdString(valueString);
|
||||
result = intAsString.toInt();
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
/// double values
|
||||
const QString doubleAsString = QString::fromStdString(valueString);
|
||||
double doubleValue;
|
||||
if (doubleAsString.contains(',')) {
|
||||
QLocale german(QLocale::German);
|
||||
doubleValue = german.toDouble(doubleAsString);
|
||||
} else {
|
||||
doubleValue = doubleAsString.toDouble();
|
||||
}
|
||||
result = doubleValue;
|
||||
|
||||
// } else if (typeColumns.contains(columnName)) {
|
||||
// // NEXT validate string is allowed
|
||||
// values[role] = QString::fromStdString(columnValueMap.value(columnName).at(row));
|
||||
} else {
|
||||
/// no type recognized for column
|
||||
QString errorString = QString("Couldn't find value type for role '%1'").arg(role);
|
||||
qCritical() << errorString;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
32
formats/csvparser.h
Normal file
32
formats/csvparser.h
Normal file
@ -0,0 +1,32 @@
|
||||
#ifndef CSVPARSER_H
|
||||
#define CSVPARSER_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
namespace rapidcsv {
|
||||
class Document;
|
||||
}
|
||||
|
||||
class CsvParser {
|
||||
public:
|
||||
static QList<ModelItemValues> getItemsFromCSVFile(const QString& fileName);
|
||||
static bool exportToCSVFile(const QList<QStringList>& rows, const QString& filePath);
|
||||
|
||||
private:
|
||||
explicit CsvParser();
|
||||
|
||||
static bool isCsvCompatible(const rapidcsv::Document& doc);
|
||||
static QList<ModelItemValues> createListItemsFromCsvEntries(const rapidcsv::Document& doc);
|
||||
static QHash<QString, std::vector<std::string>> extractColumnValues(
|
||||
const QList<QString> headerNames,
|
||||
const rapidcsv::Document& doc);
|
||||
static ModelItemValues getItemValuesForRow(
|
||||
const QList<QString>& headerNames,
|
||||
const QHash<QString, std::vector<std::string>>& columnValueMap,
|
||||
const int row);
|
||||
static QVariant parseItemValue(const int role, const std::string& valueString);
|
||||
};
|
||||
|
||||
#endif // CSVPARSER_H
|
||||
100
formats/jsonparser.cpp
Normal file
100
formats/jsonparser.cpp
Normal file
@ -0,0 +1,100 @@
|
||||
#include "jsonparser.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "../model/metadata.h"
|
||||
|
||||
QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData,
|
||||
const QString& objectName) {
|
||||
QList<ModelItemValues> result;
|
||||
|
||||
if (jsonData.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonArray itemArray = extractItemArray(jsonData, objectName);
|
||||
|
||||
foreach (QJsonValue value, itemArray) {
|
||||
QJsonObject itemJsonObject = value.toObject();
|
||||
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
|
||||
result.append(values);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray JsonParser::itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
|
||||
const QString& objectName) {
|
||||
QJsonDocument jsonDoc;
|
||||
QJsonObject rootObject;
|
||||
QJsonArray itemArray;
|
||||
for (const QHash<int, QVariant>& itemValues : itemValuesList) {
|
||||
QJsonObject itemObject;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = itemValues.value(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toString());
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toInt());
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toDouble());
|
||||
} else {
|
||||
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
|
||||
itemArray.append(itemObject);
|
||||
}
|
||||
|
||||
rootObject.insert(objectName, itemArray);
|
||||
jsonDoc.setObject(rootObject);
|
||||
|
||||
return jsonDoc.toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
JsonParser::JsonParser() {}
|
||||
|
||||
QJsonArray JsonParser::extractItemArray(const QByteArray& jsonData, const QString& objectName) {
|
||||
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
||||
QJsonArray itemArray;
|
||||
if (objectName.isEmpty()) {
|
||||
itemArray = doc.array();
|
||||
|
||||
} else {
|
||||
QJsonObject rootObject = doc.object();
|
||||
itemArray = rootObject.value(objectName).toArray();
|
||||
}
|
||||
|
||||
return itemArray;
|
||||
}
|
||||
|
||||
ModelItemValues JsonParser::jsonObjectToItemValues(const QJsonObject& itemJsonObject) {
|
||||
ModelItemValues values;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, role);
|
||||
values.insert(keyValuePair.first, keyValuePair.second);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
pair<int, QVariant> JsonParser::getKeyValuePair(const QJsonObject& itemJsonObject, const int role) {
|
||||
QVariant result;
|
||||
const QJsonValue jsonValue = itemJsonObject[ROLE_NAMES.value(role)];
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
result = jsonValue.toString();
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
result = jsonValue.toInt();
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
result = jsonValue.toDouble();
|
||||
} else {
|
||||
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
|
||||
}
|
||||
return pair<int, QVariant>(role, result);
|
||||
}
|
||||
31
formats/jsonparser.h
Normal file
31
formats/jsonparser.h
Normal file
@ -0,0 +1,31 @@
|
||||
#ifndef JSONPARSER_H
|
||||
#define JSONPARSER_H
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
class QJsonObject;
|
||||
class QString;
|
||||
class QByteArray;
|
||||
class QJsonArray;
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
using namespace std;
|
||||
|
||||
class JsonParser {
|
||||
public:
|
||||
static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData,
|
||||
const QString& objectName = "");
|
||||
static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
|
||||
const QString& objectName = "");
|
||||
|
||||
private:
|
||||
explicit JsonParser();
|
||||
|
||||
static QJsonArray extractItemArray(const QByteArray& jsonData, const QString& objectName);
|
||||
static ModelItemValues jsonObjectToItemValues(const QJsonObject& itemJsonObject);
|
||||
|
||||
static pair<int, QVariant> getKeyValuePair(const QJsonObject& itemJsonObject, const int role);
|
||||
};
|
||||
|
||||
#endif // JSONPARSER_H
|
||||
171
genericcore.cpp
171
genericcore.cpp
@ -1,3 +1,172 @@
|
||||
#include "genericcore.h"
|
||||
|
||||
GenericCore::GenericCore() {}
|
||||
#include <QCoreApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QJsonDocument>
|
||||
#include <QProcess>
|
||||
#include <QSettings>
|
||||
#include <QString>
|
||||
|
||||
#include "../../ApplicationConfig.h"
|
||||
#include "CoreConfig.h"
|
||||
#include "constants.h"
|
||||
#include "data/filehandler.h"
|
||||
#include "model/metadata.h"
|
||||
#include "model/tablemodel.h"
|
||||
|
||||
#include <QtGui/QUndoStack>
|
||||
|
||||
using namespace std;
|
||||
|
||||
GenericCore::GenericCore() {
|
||||
qDebug() << "Creating core...";
|
||||
|
||||
QCoreApplication::setOrganizationName("Working-Copy Collective");
|
||||
QCoreApplication::setOrganizationDomain("working-copy.org");
|
||||
|
||||
#ifdef QT_DEBUG
|
||||
QCoreApplication::setApplicationName(QString(APPLICATION_NAME) + "-dev");
|
||||
#else
|
||||
QCoreApplication::setApplicationName(QString(APPLICATION_NAME));
|
||||
#endif
|
||||
|
||||
// TODO let the model own its undo stack (& use TableModel::getUndoStack() if necessary)
|
||||
m_modelUndoStack = new QUndoStack(this);
|
||||
|
||||
setupModels();
|
||||
}
|
||||
|
||||
GenericCore::~GenericCore() { qDebug() << "Destroying core..."; }
|
||||
|
||||
QString GenericCore::toString() const {
|
||||
return QString("%1 (Version %2)").arg(CORE_NAME).arg(CORE_VERSION);
|
||||
}
|
||||
|
||||
void GenericCore::sayHello() const { qDebug() << "Hello from the core!"; }
|
||||
|
||||
bool GenericCore::isApplicationUpdateAvailable() {
|
||||
QProcess process;
|
||||
const QString programmString = getMaintenanceToolFilePath();
|
||||
const QStringList checkArgs("--checkupdates");
|
||||
process.start(programmString, checkArgs);
|
||||
process.waitForFinished();
|
||||
|
||||
const int exitCode = process.exitCode();
|
||||
if (process.error() != QProcess::UnknownError) {
|
||||
qDebug() << "Error checking for updates";
|
||||
emit displayStatusMessage("Error checking for updates");
|
||||
return false;
|
||||
}
|
||||
|
||||
QByteArray data = process.readAllStandardOutput();
|
||||
|
||||
QSettings settings;
|
||||
settings.beginGroup("Application");
|
||||
settings.setValue("lastCheckForUpdate", QDateTime::currentDateTimeUtc());
|
||||
settings.endGroup();
|
||||
settings.sync();
|
||||
|
||||
if (data.isEmpty() || data.contains("currently no updates")) {
|
||||
qInfo() << "No updates available";
|
||||
emit displayStatusMessage("No updates available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void GenericCore::triggerApplicationUpdate() {
|
||||
// TODO include cleaness of undo stack
|
||||
// if (!m_undoStack->isClean()) {
|
||||
// saveItems();
|
||||
// }
|
||||
// QStringList args("update componentA componentB");
|
||||
QStringList args("--start-updater");
|
||||
QString toolFilePath = getMaintenanceToolFilePath();
|
||||
QProcess::startDetached(toolFilePath, args);
|
||||
}
|
||||
|
||||
QUndoStack* GenericCore::getModelUndoStack() const { return m_modelUndoStack; }
|
||||
|
||||
std::shared_ptr<TableModel> GenericCore::getModel() const { return m_mainModel; }
|
||||
|
||||
/**
|
||||
* Save items to default file (in standard location).
|
||||
* @brief GenericCore::saveItems Saves item fo file.
|
||||
*/
|
||||
void GenericCore::saveItems() {
|
||||
qDebug() << "saving items...";
|
||||
|
||||
const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc();
|
||||
const bool successfulSave = FileHandler::saveToFile(doc, ITEM_FILE_NAME);
|
||||
if (successfulSave) {
|
||||
m_modelUndoStack->setClean();
|
||||
emit displayStatusMessage(QString("Items saved."));
|
||||
} else {
|
||||
emit displayStatusMessage(QString("Error: Items couldn't be saved."));
|
||||
}
|
||||
}
|
||||
|
||||
void GenericCore::importCSVFile(const QString& filePath) {
|
||||
qInfo() << "importing items from CSV...";
|
||||
qDebug() << "filePath:" << filePath;
|
||||
const QList<ModelItemValues> itemValuesList = FileHandler::getItemValuesFromCSVFile(filePath);
|
||||
// NEXT inform UI on errors
|
||||
if (itemValuesList.isEmpty()) {
|
||||
qDebug() << "No items found. Doing nothing...";
|
||||
return;
|
||||
}
|
||||
// qDebug() << "CSV file content:" << itemValuesList;
|
||||
m_mainModel->insertItems(m_mainModel->rowCount(), itemValuesList);
|
||||
}
|
||||
|
||||
bool GenericCore::exportCSVFile(const QString& filePath) {
|
||||
qInfo() << "exporting items to CSV...";
|
||||
qDebug() << "filePath:" << filePath;
|
||||
const QList<QStringList> itemsAsStringLists = m_mainModel->getItemsAsStringLists();
|
||||
return FileHandler::exportToCSVFile(itemsAsStringLists, filePath);
|
||||
}
|
||||
|
||||
void GenericCore::setupModels() {
|
||||
m_mainModel = make_shared<TableModel>(m_modelUndoStack, this);
|
||||
// TODO add QAbstractItemModelTester
|
||||
initModelData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializing model with data. Tries to read items from default file. Generating example items as
|
||||
* fallback.
|
||||
* @brief GenericCore::initModelData
|
||||
*/
|
||||
void GenericCore::initModelData() {
|
||||
qInfo() << "Trying to read model data from file...";
|
||||
const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEM_FILE_NAME);
|
||||
// qDebug() << "jsonDoc:" << jsonDoc;
|
||||
// TODO decide on lack of file(s) (config, data) if example items should be generated
|
||||
// (see welcome wizard)
|
||||
if (jsonDoc.isEmpty()) {
|
||||
qDebug() << "No item content in file. Generating example items...";
|
||||
const QByteArray exampleItems = m_mainModel->generateExampleItems();
|
||||
m_mainModel->insertItems(0, exampleItems);
|
||||
} else {
|
||||
qDebug() << "Item in file found.";
|
||||
m_mainModel->insertItems(0, jsonDoc);
|
||||
}
|
||||
m_modelUndoStack->clear();
|
||||
}
|
||||
|
||||
QString GenericCore::getMaintenanceToolFilePath() const {
|
||||
QString applicationDirPath = QCoreApplication::applicationDirPath();
|
||||
|
||||
/// setting the applicationDirPath hard coded to test update feature from IDE
|
||||
#ifdef QT_DEBUG
|
||||
applicationDirPath = QString("/opt/%1").arg(APPLICATION_NAME);
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_MAC
|
||||
applicationDirPath.append("/../../..");
|
||||
#endif
|
||||
const QString filePath = applicationDirPath + "/" + UPDATER_EXE;
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@ -1,10 +1,45 @@
|
||||
#ifndef GENERICCORE_H
|
||||
#define GENERICCORE_H
|
||||
|
||||
class GenericCore
|
||||
{
|
||||
public:
|
||||
GenericCore();
|
||||
#include <QObject>
|
||||
|
||||
class QUndoStack;
|
||||
class QAbstractItemModel;
|
||||
class QString;
|
||||
|
||||
class TableModel;
|
||||
|
||||
class GenericCore : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
GenericCore();
|
||||
~GenericCore();
|
||||
|
||||
QString toString() const;
|
||||
void sayHello() const;
|
||||
|
||||
bool isApplicationUpdateAvailable();
|
||||
void triggerApplicationUpdate();
|
||||
|
||||
QUndoStack* getModelUndoStack() const;
|
||||
std::shared_ptr<TableModel> getModel() const;
|
||||
|
||||
void saveItems();
|
||||
void importCSVFile(const QString& filePath);
|
||||
bool exportCSVFile(const QString& filePath);
|
||||
|
||||
signals:
|
||||
void displayStatusMessage(QString message);
|
||||
|
||||
private:
|
||||
QUndoStack* m_modelUndoStack;
|
||||
std::shared_ptr<TableModel> m_mainModel;
|
||||
|
||||
void setupModels();
|
||||
void initModelData();
|
||||
|
||||
QString getMaintenanceToolFilePath() const;
|
||||
};
|
||||
|
||||
#endif // GENERICCORE_H
|
||||
#endif // GENERICCORE_H
|
||||
|
||||
75
model/commands/edititemcommand.cpp
Normal file
75
model/commands/edititemcommand.cpp
Normal file
@ -0,0 +1,75 @@
|
||||
#include "edititemcommand.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "../metadata.h"
|
||||
#include "../tablemodel.h"
|
||||
|
||||
EditItemCommand::EditItemCommand(TableModel* model,
|
||||
const QModelIndex& index,
|
||||
QMap<int, QVariant>& changedValues,
|
||||
QUndoCommand* parent)
|
||||
: QUndoCommand(parent)
|
||||
, m_model(model)
|
||||
, m_row(index.row()) {
|
||||
qInfo() << "New EditCommand...";
|
||||
QString commandText;
|
||||
|
||||
if (changedValues.size() == 1) {
|
||||
qDebug() << "Only one value to change. Using more specific command text...";
|
||||
const int role = changedValues.firstKey();
|
||||
const QVariant value = changedValues.first();
|
||||
QString roleName = model->roleNames().value(role);
|
||||
|
||||
if (USER_FACING_ROLES.contains(role)) {
|
||||
commandText = QString("Setting '%1' of item '%2' to '%3'")
|
||||
.arg(roleName)
|
||||
.arg(index.data(DEFAULT_ROLE).toString())
|
||||
.arg(value.toString());
|
||||
} else {
|
||||
qWarning() << "Role didn't match! Using a generic command text...";
|
||||
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
|
||||
}
|
||||
} else {
|
||||
qDebug() << "More than one value to change. Using a generic command text...";
|
||||
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
|
||||
}
|
||||
setText(commandText);
|
||||
|
||||
m_newValues = changedValues;
|
||||
|
||||
/// storing old values for undo step
|
||||
m_oldValues = getOldValues(index, changedValues);
|
||||
}
|
||||
|
||||
void EditItemCommand::undo() {
|
||||
qDebug() << "Undoing the EditCommand...";
|
||||
m_model->execEditItemData(m_row, m_oldValues);
|
||||
}
|
||||
|
||||
void EditItemCommand::redo() {
|
||||
qDebug() << "(Re-)doing the EditCommand...";
|
||||
m_model->execEditItemData(m_row, m_newValues);
|
||||
}
|
||||
|
||||
const QMap<int, QVariant> EditItemCommand::getOldValues(
|
||||
const QModelIndex& index,
|
||||
const QMap<int, QVariant>& changedValues) const {
|
||||
QMap<int, QVariant> result;
|
||||
QMap<int, QVariant>::const_iterator i;
|
||||
for (i = changedValues.constBegin(); i != changedValues.constEnd(); ++i) {
|
||||
const int role = i.key();
|
||||
const QVariant newValue = i.value();
|
||||
const QVariant oldValue = index.data(role);
|
||||
// TODO check if role is a editable role?
|
||||
if (oldValue != newValue) {
|
||||
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
|
||||
result.insert(role, oldValue);
|
||||
} else {
|
||||
qInfo() << "oldValue is already the same as newValue:" << oldValue;
|
||||
}
|
||||
}
|
||||
// QVariant oldModifiedDate = index.data(ModifiedDateUTCRole);
|
||||
// result.insert(ModifiedDateUTCRole, oldModifiedDate);
|
||||
return result;
|
||||
}
|
||||
33
model/commands/edititemcommand.h
Normal file
33
model/commands/edititemcommand.h
Normal file
@ -0,0 +1,33 @@
|
||||
#ifndef EDITITEMCOMMAND_H
|
||||
#define EDITITEMCOMMAND_H
|
||||
|
||||
#include <QMap>
|
||||
#include <QUndoCommand>
|
||||
|
||||
class TableModel;
|
||||
|
||||
class EditItemCommand : public QUndoCommand {
|
||||
public:
|
||||
// TODO don't use simple pointer to model
|
||||
/// Using simple pointer to model because there was a crash when closing the application with an
|
||||
/// unclean undo stack
|
||||
EditItemCommand(TableModel* model,
|
||||
const QModelIndex& index,
|
||||
QMap<int, QVariant>& changedValues,
|
||||
QUndoCommand* parent = nullptr);
|
||||
/// QUndoCommand interface
|
||||
void undo();
|
||||
void redo();
|
||||
|
||||
private:
|
||||
TableModel* m_model = nullptr;
|
||||
const int m_row;
|
||||
QMap<int, QVariant> m_oldValues;
|
||||
QMap<int, QVariant> m_newValues;
|
||||
|
||||
/// private functions
|
||||
const QMap<int, QVariant> getOldValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& changedValues) const;
|
||||
};
|
||||
|
||||
#endif // EDITITEMCOMMAND_H
|
||||
33
model/commands/insertrowscommand.cpp
Normal file
33
model/commands/insertrowscommand.cpp
Normal file
@ -0,0 +1,33 @@
|
||||
#include "insertrowscommand.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "../tablemodel.h"
|
||||
|
||||
InsertRowsCommand::InsertRowsCommand(TableModel* model,
|
||||
int startRow,
|
||||
QList<ModelItemValues> valueList,
|
||||
QUndoCommand* parent)
|
||||
: QUndoCommand(parent)
|
||||
, m_tableModel(model)
|
||||
, m_startRow(startRow)
|
||||
, m_valueList(valueList) {
|
||||
qInfo() << "New InsertCommand...";
|
||||
const QString commandText =
|
||||
QString("inserting %1 item(s) on row %2").arg(valueList.length()).arg(startRow);
|
||||
setText(commandText);
|
||||
}
|
||||
|
||||
void InsertRowsCommand::undo() {
|
||||
qDebug() << "Undoing the InsertCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
|
||||
}
|
||||
}
|
||||
|
||||
void InsertRowsCommand::redo() {
|
||||
qDebug() << "(Re-)doing the InsertCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execInsertItems(m_startRow, m_valueList);
|
||||
}
|
||||
}
|
||||
30
model/commands/insertrowscommand.h
Normal file
30
model/commands/insertrowscommand.h
Normal file
@ -0,0 +1,30 @@
|
||||
#ifndef INSERTROWSCOMMAND_H
|
||||
#define INSERTROWSCOMMAND_H
|
||||
|
||||
#include <QUndoCommand>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
class TableModel;
|
||||
|
||||
class InsertRowsCommand : public QUndoCommand {
|
||||
public:
|
||||
// TODO don't use simple pointer to model
|
||||
/// Using simple pointer to model because there was a crash when closing the application with an
|
||||
/// unclean undo stack
|
||||
InsertRowsCommand(TableModel* model,
|
||||
int startRow,
|
||||
QList<ModelItemValues> valueList,
|
||||
QUndoCommand* parent = nullptr);
|
||||
|
||||
/// QUndoCommand interface
|
||||
void undo() override;
|
||||
void redo() override;
|
||||
|
||||
private:
|
||||
TableModel* m_tableModel;
|
||||
const int m_startRow;
|
||||
const QList<ModelItemValues> m_valueList;
|
||||
};
|
||||
|
||||
#endif // INSERTROWSCOMMAND_H
|
||||
41
model/commands/removerowscommand.cpp
Normal file
41
model/commands/removerowscommand.cpp
Normal file
@ -0,0 +1,41 @@
|
||||
#include "removerowscommand.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "../tablemodel.h"
|
||||
|
||||
RemoveRowsCommand::RemoveRowsCommand(TableModel* model,
|
||||
const int startRow,
|
||||
const int nRows,
|
||||
QUndoCommand* parent)
|
||||
: QUndoCommand(parent)
|
||||
, m_tableModel(model)
|
||||
, m_startRow(startRow) {
|
||||
qInfo() << "New RemoveCommand...";
|
||||
const QString commandText =
|
||||
QString("removing %1 item(s) on position %2").arg(nRows).arg(startRow);
|
||||
setText(commandText);
|
||||
|
||||
for (int row = 0; row < nRows; ++row) {
|
||||
const int rowPosition = startRow + row;
|
||||
QModelIndex index = m_tableModel->index(rowPosition, 0);
|
||||
|
||||
ModelItemValues values = m_tableModel->getItemValues(index);
|
||||
|
||||
m_valueList.append(values);
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveRowsCommand::undo() {
|
||||
qDebug() << "Undoing the RemoveCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execInsertItems(m_startRow, m_valueList);
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveRowsCommand::redo() {
|
||||
qDebug() << "(Re-)doing the RemoveCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
|
||||
}
|
||||
}
|
||||
30
model/commands/removerowscommand.h
Normal file
30
model/commands/removerowscommand.h
Normal file
@ -0,0 +1,30 @@
|
||||
#ifndef REMOVEROWSCOMMAND_H
|
||||
#define REMOVEROWSCOMMAND_H
|
||||
|
||||
#include <QUndoCommand>
|
||||
|
||||
class TableModel;
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
class RemoveRowsCommand : public QUndoCommand {
|
||||
public:
|
||||
// TODO don't use simple pointer to model
|
||||
/// Using simple pointer to model because there was a crash when closing the application with an
|
||||
/// unclean undo stack
|
||||
RemoveRowsCommand(TableModel* model,
|
||||
const int startRow,
|
||||
const int nRows,
|
||||
QUndoCommand* parent = nullptr);
|
||||
|
||||
/// QUndoCommand interface
|
||||
void undo() override;
|
||||
void redo() override;
|
||||
|
||||
private:
|
||||
TableModel* m_tableModel;
|
||||
const int m_startRow;
|
||||
QList<ModelItemValues> m_valueList;
|
||||
};
|
||||
|
||||
#endif // REMOVEROWSCOMMAND_H
|
||||
62
model/metadata.h
Normal file
62
model/metadata.h
Normal file
@ -0,0 +1,62 @@
|
||||
#ifndef METADATA_H
|
||||
#define METADATA_H
|
||||
|
||||
#include <QDebug>
|
||||
#include <QHash>
|
||||
#include <QList>
|
||||
#include <QString>
|
||||
|
||||
/// model data
|
||||
enum UserRoles { NameRole = Qt::UserRole + 1, DescriptionRole, InfoRole, AmountRole, FactorRole };
|
||||
static UserRoles DEFAULT_ROLE = NameRole;
|
||||
static QList<UserRoles> USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole, AmountRole,
|
||||
FactorRole};
|
||||
static QHash<int, QByteArray> ROLE_NAMES = {{NameRole, "Name"},
|
||||
{DescriptionRole, "Description"},
|
||||
{InfoRole, "Info"},
|
||||
{AmountRole, "Amount"},
|
||||
{FactorRole, "Factor"}};
|
||||
static QList<UserRoles> STRING_ROLES = {NameRole, DescriptionRole, InfoRole};
|
||||
static QList<UserRoles> INT_ROLES = {AmountRole};
|
||||
static QList<UserRoles> DOUBLE_ROLES = {FactorRole};
|
||||
|
||||
/// JSON keys
|
||||
static const QString ITEM_KEY_STRING = "items";
|
||||
|
||||
/// file naming
|
||||
static const QString ITEM_FILE_NAME = ITEM_KEY_STRING + ".json";
|
||||
|
||||
/// functions
|
||||
static int GET_ROLE_FOR_COLUMN(const int column) {
|
||||
switch (column) {
|
||||
case 0:
|
||||
return NameRole;
|
||||
break;
|
||||
case 1:
|
||||
return DescriptionRole;
|
||||
break;
|
||||
case 2:
|
||||
return InfoRole;
|
||||
break;
|
||||
case 3:
|
||||
return AmountRole;
|
||||
break;
|
||||
case 4:
|
||||
return FactorRole;
|
||||
break;
|
||||
default:
|
||||
qWarning() << QString("No role found for column %1! Returning 'NameRole'...").arg(column);
|
||||
return NameRole;
|
||||
break;
|
||||
}
|
||||
}
|
||||
static QList<QString> GET_HEADER_NAMES() {
|
||||
QList<QString> result;
|
||||
for (const UserRoles& role : USER_FACING_ROLES) {
|
||||
const QString headerName = ROLE_NAMES.value(role);
|
||||
result.append(headerName);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif // METADATA_H
|
||||
67
model/modelitem.cpp
Normal file
67
model/modelitem.cpp
Normal file
@ -0,0 +1,67 @@
|
||||
#include "modelitem.h"
|
||||
|
||||
#include "metadata.h"
|
||||
|
||||
#include <QJsonObject>
|
||||
#include <QJsonValue>
|
||||
|
||||
ModelItem::ModelItem(const ModelItemValues values)
|
||||
: m_values(values) {}
|
||||
|
||||
QVariant ModelItem::data(int role) const { return m_values.value(role); }
|
||||
|
||||
bool ModelItem::setData(const QVariant& value, int role) {
|
||||
bool valueChanged = false;
|
||||
if (m_values.contains(role)) {
|
||||
if (m_values.value(role) != value) {
|
||||
valueChanged = true;
|
||||
}
|
||||
}
|
||||
m_values[role] = value;
|
||||
|
||||
return valueChanged;
|
||||
}
|
||||
|
||||
bool ModelItem::setItemData(const QMap<int, QVariant>& changedValues) {
|
||||
bool valueChanged = false;
|
||||
|
||||
QMap<int, QVariant>::const_iterator citer = changedValues.constBegin();
|
||||
|
||||
while (citer != changedValues.constEnd()) {
|
||||
const int role = citer.key();
|
||||
const QVariant value = citer.value();
|
||||
|
||||
if (m_values.contains(role)) {
|
||||
if (m_values.value(role) != value) {
|
||||
valueChanged = true;
|
||||
}
|
||||
}
|
||||
m_values[role] = value;
|
||||
|
||||
citer++;
|
||||
}
|
||||
|
||||
return valueChanged;
|
||||
}
|
||||
|
||||
QJsonObject ModelItem::toJsonObject() const {
|
||||
QJsonObject itemObject;
|
||||
// TODO add UUID and dates (entry, modification, end)
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = data(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toString());
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toInt());
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toDouble());
|
||||
} else {
|
||||
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
return itemObject;
|
||||
}
|
||||
24
model/modelitem.h
Normal file
24
model/modelitem.h
Normal file
@ -0,0 +1,24 @@
|
||||
#ifndef MODELITEM_H
|
||||
#define MODELITEM_H
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
class ModelItem {
|
||||
public:
|
||||
ModelItem(const ModelItemValues values);
|
||||
|
||||
QVariant data(int role) const;
|
||||
bool setData(const QVariant& value, int role);
|
||||
// TODO change return value to list of changed roles
|
||||
bool setItemData(const QMap<int, QVariant>& changedValues);
|
||||
|
||||
// QString toString() const;
|
||||
QJsonObject toJsonObject() const;
|
||||
|
||||
private:
|
||||
QHash<int, QVariant> m_values;
|
||||
};
|
||||
|
||||
#endif // MODELITEM_H
|
||||
277
model/tablemodel.cpp
Normal file
277
model/tablemodel.cpp
Normal file
@ -0,0 +1,277 @@
|
||||
#include "tablemodel.h"
|
||||
|
||||
#include "../formats/jsonparser.h"
|
||||
#include "commands/edititemcommand.h"
|
||||
#include "commands/insertrowscommand.h"
|
||||
#include "commands/removerowscommand.h"
|
||||
#include "metadata.h"
|
||||
#include "modelitem.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
QByteArray TableModel::generateExampleItems() {
|
||||
QJsonDocument doc = QJsonDocument();
|
||||
QJsonObject rootObject;
|
||||
QJsonArray array;
|
||||
|
||||
for (int row = 0; row < 5; ++row) {
|
||||
QJsonObject itemObject;
|
||||
// itemObject.insert("uuid", m_uuid.toString());
|
||||
// itemObject.insert("entryDateUTC", m_entryDateUTC.toString(Qt::ISODate));
|
||||
itemObject.insert(ROLE_NAMES.value(NameRole), QString("Item %1").arg(row));
|
||||
itemObject.insert(ROLE_NAMES.value(DescriptionRole), QString("This is item %1").arg(row));
|
||||
itemObject.insert(ROLE_NAMES.value(InfoRole), QString("Info of item %1").arg(row));
|
||||
itemObject.insert(ROLE_NAMES.value(AmountRole), row);
|
||||
itemObject.insert(ROLE_NAMES.value(FactorRole), row * 1.1);
|
||||
|
||||
array.append(itemObject);
|
||||
}
|
||||
rootObject.insert(ITEM_KEY_STRING, array);
|
||||
|
||||
doc.setObject(rootObject);
|
||||
return doc.toJson();
|
||||
}
|
||||
|
||||
TableModel::TableModel(QUndoStack* undoStack, QObject* parent)
|
||||
: QAbstractTableModel{parent}
|
||||
, m_undoStack(undoStack) {}
|
||||
|
||||
Qt::ItemFlags TableModel::flags(const QModelIndex& index) const {
|
||||
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> TableModel::roleNames() const { return ROLE_NAMES; }
|
||||
|
||||
int TableModel::rowCount(const QModelIndex& parent) const {
|
||||
Q_UNUSED(parent);
|
||||
return m_items.size();
|
||||
}
|
||||
|
||||
int TableModel::columnCount(const QModelIndex& parent) const {
|
||||
Q_UNUSED(parent);
|
||||
return ROLE_NAMES.size();
|
||||
}
|
||||
|
||||
QVariant TableModel::data(const QModelIndex& index, int role) const {
|
||||
const int row = index.row();
|
||||
const int column = index.column();
|
||||
|
||||
if (!index.isValid()) {
|
||||
return QVariant();
|
||||
}
|
||||
if (row >= rowCount(QModelIndex()) || column >= columnCount(QModelIndex())) {
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole:
|
||||
return m_items.at(row)->data(roleForColumn);
|
||||
case NameRole:
|
||||
case DescriptionRole:
|
||||
case InfoRole:
|
||||
case AmountRole:
|
||||
case FactorRole:
|
||||
return m_items.at(row)->data(role);
|
||||
}
|
||||
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const {
|
||||
if (role == Qt::DisplayRole) {
|
||||
if (orientation == Qt::Horizontal) {
|
||||
const int columnRole = GET_ROLE_FOR_COLUMN(section);
|
||||
const QString headerName = ROLE_NAMES.value(columnRole);
|
||||
return QString("%1").arg(headerName);
|
||||
} else {
|
||||
return QString("%1").arg(section);
|
||||
}
|
||||
}
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
bool TableModel::setData(const QModelIndex& index, const QVariant& value, int role) {
|
||||
if (role == Qt::EditRole && checkIndex(index)) {
|
||||
const int column = index.column();
|
||||
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
return setItemData(index, {{roleForColumn, value}});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TableModel::setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) {
|
||||
if (!checkIndex(index)) {
|
||||
return false;
|
||||
}
|
||||
// if (isRoleReadOnly(roleForColumn)) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
QMap<int, QVariant> changedValues = onlyChangedValues(index, roles);
|
||||
if (changedValues.size() > 0) {
|
||||
EditItemCommand* editCommand = new EditItemCommand(this, index, changedValues);
|
||||
m_undoStack->push(editCommand);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ModelItemValues TableModel::getItemValues(const QModelIndex& index) const {
|
||||
ModelItemValues values;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
values.insert(role, data(index, role));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
QJsonDocument TableModel::getAllItemsAsJsonDoc() const {
|
||||
QJsonDocument doc = QJsonDocument();
|
||||
QJsonObject rootObject;
|
||||
QJsonArray array;
|
||||
|
||||
foreach (shared_ptr<ModelItem> item, m_items) {
|
||||
QJsonObject itemObject = item->toJsonObject();
|
||||
array.append(itemObject);
|
||||
}
|
||||
rootObject.insert(ITEM_KEY_STRING, array);
|
||||
|
||||
doc.setObject(rootObject);
|
||||
return doc;
|
||||
}
|
||||
|
||||
QList<QStringList> TableModel::getItemsAsStringLists() const {
|
||||
QList<QStringList> result;
|
||||
foreach (shared_ptr<ModelItem> item, m_items) {
|
||||
QStringList valueList;
|
||||
for (int column = 0; column < columnCount(); ++column) {
|
||||
QString value = item->data(GET_ROLE_FOR_COLUMN(column)).toString();
|
||||
valueList.append(value);
|
||||
}
|
||||
result.append(valueList);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
|
||||
if (parentIndex != QModelIndex()) {
|
||||
qWarning() << "Removing of child rows is not supported yet!";
|
||||
return false;
|
||||
}
|
||||
|
||||
const int lastRow = firstRow + nRows - 1;
|
||||
if (firstRow < 0 || lastRow >= m_items.size()) {
|
||||
qWarning() << "Trying to remove rows is out of bounds!";
|
||||
return false;
|
||||
}
|
||||
|
||||
RemoveRowsCommand* removeCommand = new RemoveRowsCommand(this, firstRow, nRows);
|
||||
m_undoStack->push(removeCommand);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void TableModel::appendItems(const QByteArray& jsonDoc) { insertItems(-1, jsonDoc, QModelIndex()); }
|
||||
|
||||
void TableModel::insertItems(int startPosition,
|
||||
const QByteArray& jsonDoc,
|
||||
const QModelIndex& parentIndex) {
|
||||
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEM_KEY_STRING);
|
||||
|
||||
insertItems(startPosition, valueList, parentIndex);
|
||||
}
|
||||
|
||||
void TableModel::insertItems(int startPosition,
|
||||
const QList<ModelItemValues>& itemValuesList,
|
||||
const QModelIndex& parentIndex) {
|
||||
qInfo() << "Inserting item(s) into model...";
|
||||
if (parentIndex != QModelIndex()) {
|
||||
qWarning()
|
||||
<< "Using invalid parent index (no child support for now)! Using root index as parent...";
|
||||
}
|
||||
if (startPosition == -1 || startPosition > m_items.size()) {
|
||||
/// Appending item(s)
|
||||
startPosition = m_items.size();
|
||||
}
|
||||
|
||||
InsertRowsCommand* insertCommand = new InsertRowsCommand(this, startPosition, itemValuesList);
|
||||
m_undoStack->push(insertCommand);
|
||||
}
|
||||
|
||||
void TableModel::execInsertItems(const int firstRow, const QList<ModelItemValues> valueList) {
|
||||
const int nRows = valueList.size();
|
||||
qDebug() << "Inserting" << nRows << "items...";
|
||||
|
||||
const int lastRow = firstRow + nRows - 1;
|
||||
beginInsertRows(QModelIndex(), firstRow, lastRow);
|
||||
for (int row = 0; row < nRows; ++row) {
|
||||
const int rowPosition = firstRow + row;
|
||||
shared_ptr<ModelItem> item = make_unique<ModelItem>(valueList.at(row));
|
||||
m_items.insert(rowPosition, std::move(item));
|
||||
}
|
||||
endInsertRows();
|
||||
}
|
||||
|
||||
void TableModel::execRemoveItems(const int firstRow, const int nRows) {
|
||||
const int lastRow = firstRow + nRows - 1;
|
||||
beginRemoveRows(QModelIndex(), firstRow, lastRow);
|
||||
m_items.remove(firstRow, nRows);
|
||||
endRemoveRows();
|
||||
}
|
||||
|
||||
void TableModel::execEditItemData(const int row, const QMap<int, QVariant>& changedValues) {
|
||||
shared_ptr<ModelItem> item = m_items.at(row);
|
||||
bool isDataChanged = item->setItemData(changedValues);
|
||||
|
||||
if (isDataChanged) {
|
||||
/// FIXME due to the mapping from roles to the DisplayRole of different columns the complete row
|
||||
/// is getting notified about (potential) data changes; dataChanged should be called only for
|
||||
/// the affected columns
|
||||
const QModelIndex firstIndex = this->index(row, 0);
|
||||
const QModelIndex lastIndex = this->index(row, ROLE_NAMES.size() - 1);
|
||||
QList<int> roles = changedValues.keys();
|
||||
roles.insert(0, Qt::DisplayRole);
|
||||
emit dataChanged(firstIndex, lastIndex, roles.toVector());
|
||||
}
|
||||
}
|
||||
|
||||
QMap<int, QVariant> TableModel::onlyChangedValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& roleValueMap) const {
|
||||
QMap<int, QVariant> result;
|
||||
QMap<int, QVariant>::const_iterator i;
|
||||
for (i = roleValueMap.constBegin(); i != roleValueMap.constEnd(); ++i) {
|
||||
const int role = i.key();
|
||||
const QVariant newValue = i.value();
|
||||
const QVariant oldValue = index.data(role);
|
||||
// TODO check if role is a editable role?
|
||||
if (oldValue != newValue) {
|
||||
bool emptyValueIsEqualToZero = isEmptyValueEqualToZero(role);
|
||||
if (emptyValueIsEqualToZero && oldValue == QVariant() && newValue == 0) {
|
||||
qDebug() << "oldValue:" << oldValue << "& newValue:" << newValue
|
||||
<< "mean the same. Ignoring...";
|
||||
continue;
|
||||
}
|
||||
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
|
||||
result.insert(role, newValue);
|
||||
} else {
|
||||
qInfo() << "oldValue is already the same as newValue:" << oldValue << "-> ignoring...";
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool TableModel::isEmptyValueEqualToZero(const int role) const {
|
||||
if (INT_ROLES.contains(role)) {
|
||||
return true;
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
71
model/tablemodel.h
Normal file
71
model/tablemodel.h
Normal file
@ -0,0 +1,71 @@
|
||||
#ifndef TABLEMODEL_H
|
||||
#define TABLEMODEL_H
|
||||
|
||||
#include <QAbstractTableModel>
|
||||
|
||||
class QUndoStack;
|
||||
class ModelItem;
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
|
||||
class TableModel : public QAbstractTableModel {
|
||||
Q_OBJECT
|
||||
|
||||
friend class InsertRowsCommand;
|
||||
friend class RemoveRowsCommand;
|
||||
friend class EditItemCommand;
|
||||
|
||||
public:
|
||||
static QByteArray generateExampleItems();
|
||||
|
||||
explicit TableModel(QUndoStack* undoStack, QObject* parent = nullptr);
|
||||
|
||||
/// QAbstractItemModel interface
|
||||
Qt::ItemFlags flags(const QModelIndex& index) const override;
|
||||
QHash<int, QByteArray> roleNames() const override;
|
||||
|
||||
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
|
||||
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
|
||||
QVariant data(const QModelIndex& index, int role) const override;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
|
||||
|
||||
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
|
||||
bool setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) override;
|
||||
|
||||
ModelItemValues getItemValues(const QModelIndex& index) const;
|
||||
QJsonDocument getAllItemsAsJsonDoc() const;
|
||||
QList<QStringList> getItemsAsStringLists() const;
|
||||
|
||||
public slots:
|
||||
// bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex())
|
||||
// override;
|
||||
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
|
||||
void appendItems(const QByteArray& jsonDoc);
|
||||
void insertItems(int startPosition,
|
||||
const QByteArray& jsonDoc,
|
||||
const QModelIndex& parentIndex = QModelIndex());
|
||||
void insertItems(int startPosition,
|
||||
const QList<ModelItemValues>& itemValuesList,
|
||||
const QModelIndex& parentIndex = QModelIndex());
|
||||
|
||||
private:
|
||||
/// *** members ***
|
||||
// TODO shared_ptr -> unique_ptr
|
||||
QList<shared_ptr<ModelItem>> m_items;
|
||||
QUndoStack* m_undoStack;
|
||||
|
||||
/// *** functions ***
|
||||
/// undo/redo functions
|
||||
void execInsertItems(const int firstRow, const QList<ModelItemValues> valueList);
|
||||
void execRemoveItems(const int firstRow, const int nRows);
|
||||
void execEditItemData(const int row, const QMap<int, QVariant>& changedValues);
|
||||
|
||||
/// misc functions
|
||||
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& roleValueMap) const;
|
||||
bool isEmptyValueEqualToZero(const int role) const;
|
||||
};
|
||||
|
||||
#endif // TABLEMODEL_H
|
||||
Reference in New Issue
Block a user