Compare commits

...

48 Commits

Author SHA1 Message Date
caffa1c18a Added a ToStringRole to summarize the model items (for tool tip and QR code). 2026-01-15 14:04:37 +01:00
c15e5425a7 Bumped version to 0.2.0. 2026-01-14 10:27:33 +01:00
e06170dd59 Added the a function to find items containing the specified text. Returning an item selection. 2026-01-12 15:00:06 +01:00
738e1bdee1 Merge branch 'feature/proxySortFilterModel' into develop 2026-01-12 10:18:35 +01:00
d78fc734c1 Appending and removing items are done via GeneralSortFilterModel instead of TableModel directly. 2026-01-12 10:07:59 +01:00
a6512f2c67 Added a QSortFilterProxyModel subclass to enable sorting by different columns in the views. 2026-01-12 09:56:50 +01:00
3597fcf0b0 Merge branch 'feature/fileImportExportCsv' into develop 2026-01-06 10:20:02 +01:00
8d4260b18d Items can be saved before starting the updater. 2026-01-06 10:15:35 +01:00
99ed398c2f Simple implementation of CSV export. 2026-01-06 10:04:26 +01:00
3e6273cb7d Using the typedef ModelItemValues for "QHash<int, QVariant>". 2026-01-04 17:48:27 +01:00
2702b9c835 Simple implementation of CSV file import. Successfully imported items are appended to the model. 2026-01-04 13:38:54 +01:00
2ccbe3839a Merge branch 'feature/refactorModelMetaDataInCentralLocation' into develop 2026-01-01 10:27:02 +01:00
3266c99fc3 Bugfix: When parsing JSON data to item values all the values were converted to strings. 2026-01-01 10:26:29 +01:00
b8fe4e6502 Iterating over USER_FACING_ROLES to get all the item values when parsing and keeping them in edit and remove commands. Instead of using each role explicitly. 2025-12-31 10:39:32 +01:00
acb8be5602 Refactored JsonParser to not use roles (or their names) directly. 2025-12-29 13:03:09 +01:00
3610aa3841 Using "model/metadata.h" for file and JSON object naming as well. Using all upper case for naming static meta data constants and functions. 2025-12-29 10:35:00 +01:00
0c3d711513 Moved the model meta data for roles and columns into "model/metadata.h" to gather meta data like this in one central place. 2025-12-29 10:30:12 +01:00
b2f01a7990 Merge branch 'feature/saveLoadItemsInFromFile' into develop 2025-12-23 14:02:47 +01:00
1fc1b1715d Items are loaded from default JSON file in standard location at startup. If no items are found in file, example items are generated. 2025-12-23 13:40:33 +01:00
0e1a0d4959 Items can be saved to JSON file "items.json" (in standard location). 2025-12-23 10:14:13 +01:00
2c3d49db30 Setting the application name with "-dev" suffix in debug builds and setting the organization name (for storing configs and other files in proper directory). 2025-12-23 10:11:38 +01:00
c09aad88dc Merge branch 'feature/UndoRedoWithModelData' into develop 2025-12-22 11:38:13 +01:00
e54204e394 Editing an item is now undo/redo-able. 2025-12-15 18:04:14 +01:00
772ab6b2ff Reordered function implementations according to declarations in header file. 2025-12-12 13:22:27 +01:00
c75d35179b Deleting items from the model can now be made undone/redone. 2025-12-11 15:49:16 +01:00
0166a00d9d Adding new items to the model can now be made undone/redone. 2025-12-11 15:47:55 +01:00
432e81d4be Merge branch 'develop' into feature/UndoRedoWithModelData 2025-12-09 09:57:22 +01:00
e21c899aac Bugfix: Last row could not be removed due to miscalculations of the bounds. 2025-12-09 09:33:46 +01:00
169d8f9f1e Items can be deleted from the model. 2025-12-08 14:50:13 +01:00
d45b1098f9 Added default invalid parentIndex to TableModel::columnCount and added Q_UNUSED macro to suppress warnings. 2025-12-08 13:33:05 +01:00
4c906099eb Items can be added to model dynamically. 2025-12-08 13:25:02 +01:00
144460b5aa Start with the current data, when editing a table cell. 2025-12-06 14:34:17 +01:00
5b5713c89f Added a QUndoStack and made it accessible for UIs. 2025-12-06 10:34:44 +01:00
a07e03d80d Deducing the column count of the table model from the header names. 2025-12-04 15:54:53 +01:00
40e1dd3002 A very simple version of editing model data. 2025-12-04 11:30:30 +01:00
16c524f7a2 Proper header names for the columns. 2025-12-04 11:29:33 +01:00
0dba9639e6 Added a ModelItem class to hold the data for each row. 2025-12-03 11:07:39 +01:00
6a3725bde7 Added a simple read-only TableModel and made it accessible via GenericCore.
Basically like in this tutorial: https://doc.qt.io/qt-6/modelview.html#2-1-a-read-only-table
2025-12-02 16:09:34 +01:00
301d143b37 Updated core library project version to 0.1.0 2025-11-04 21:23:26 +01:00
13b53683a5 Retrieving Application name from umbrella project and using it to determine the path of the QtMaintenanceTool. 2025-11-01 10:52:04 +01:00
7ba0304232 Added SettingsHandler class. 2025-10-31 15:24:06 +01:00
d943f2d89a Added checking for update and triggering the updater. 2025-10-31 14:47:27 +01:00
bddb6df3ee Formatting CMakeLists.txt 2025-10-26 13:03:43 +01:00
7ec346b5a5 Retrieving core name and version from CMakeLists.txt and use it in GenericCore::toString(). 2025-10-03 11:15:06 +02:00
b631f4200e Added toString() method. 2025-10-02 16:22:47 +02:00
0bbac662f4 Using qDebug() instead of iostream::cout(). And formatted files with clangformat. 2025-10-02 16:22:01 +02:00
b3718c211f Using TARGET_APP variable in CMakeLists.txt. 2025-10-02 16:19:32 +02:00
fd32b85554 Added some console outputs to use library. 2025-10-02 13:42:13 +02:00
26 changed files with 1658 additions and 15 deletions

View File

@ -1,6 +1,7 @@
cmake_minimum_required(VERSION 3.16)
project(GenericCore LANGUAGES CXX)
set(TARGET_APP "GenericCore")
project(${TARGET_APP} VERSION 0.2.0 LANGUAGES CXX)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
@ -8,23 +9,41 @@ 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
model/generalsortfiltermodel.h model/generalsortfiltermodel.cpp
)
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
View File

@ -0,0 +1,2 @@
#define CORE_NAME "${PROJECT_NAME}"
#define CORE_VERSION "${PROJECT_VERSION}"

15
constants.h Normal file
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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

View File

@ -1,3 +1,177 @@
#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/generalsortfiltermodel.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(const bool saveChanges) {
if (saveChanges && !m_modelUndoStack->isClean()) {
saveItems();
}
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; }
std::shared_ptr<GeneralSortFilterModel> GenericCore::getSortFilterModel() const {
return m_sortFilterModel;
}
/**
* 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);
m_sortFilterModel = make_shared<GeneralSortFilterModel>(m_mainModel);
// 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;
}

View File

@ -1,10 +1,48 @@
#ifndef GENERICCORE_H
#define GENERICCORE_H
class GenericCore
{
public:
GenericCore();
#include <QObject>
class QUndoStack;
class QAbstractItemModel;
class QString;
class TableModel;
class GeneralSortFilterModel;
class GenericCore : public QObject {
Q_OBJECT
public:
GenericCore();
~GenericCore();
QString toString() const;
void sayHello() const;
bool isApplicationUpdateAvailable();
void triggerApplicationUpdate(const bool saveChanges);
QUndoStack* getModelUndoStack() const;
std::shared_ptr<TableModel> getModel() const;
std::shared_ptr<GeneralSortFilterModel> getSortFilterModel() 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;
std::shared_ptr<GeneralSortFilterModel> m_sortFilterModel;
void setupModels();
void initModelData();
QString getMaintenanceToolFilePath() const;
};
#endif // GENERICCORE_H
#endif // GENERICCORE_H

View 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;
}

View 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

View 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);
}
}

View 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

View 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());
}
}

View 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

View File

@ -0,0 +1,96 @@
#include "generalsortfiltermodel.h"
#include "metadata.h"
#include <QItemSelection>
GeneralSortFilterModel::GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel)
: QSortFilterProxyModel{sourceModel.get()}
, m_tableModel(sourceModel) {
setSourceModel(sourceModel.get());
m_collator.setNumericMode(true);
}
QItemSelection GeneralSortFilterModel::findItems(const QString& text) const {
QItemSelection result;
for (int i = 0; i < rowCount(); ++i) {
const QModelIndex localIndex = index(i, 0);
if (indexContainsText(localIndex, text)) {
result.select(localIndex, index(i, columnCount() - 1)); /// select entire row
}
}
return result;
}
void GeneralSortFilterModel::appendItems(const QByteArray& jsonDoc) {
m_tableModel->appendItems(jsonDoc);
}
bool GeneralSortFilterModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
const QModelIndex proxyIndex = index(firstRow, 0, parentIndex);
const QModelIndex sourceIndex = mapToSource(proxyIndex);
return m_tableModel->removeRows(sourceIndex.row(), nRows, sourceIndex.parent());
}
bool GeneralSortFilterModel::lessThan(const QModelIndex& source_left,
const QModelIndex& source_right) const {
if (source_left.column() != source_right.column()) {
return false;
}
QAbstractItemModel* localSourceModel = sourceModel();
const int role = GET_ROLE_FOR_COLUMN(source_left.column());
const QVariant leftData = localSourceModel->data(source_left);
const QVariant rightData = localSourceModel->data(source_right);
const bool isText = STRING_ROLES.contains(role);
if (isText) {
const QString leftString = leftData.toString();
const QString rightString = rightData.toString();
return m_collator.compare(leftString, rightString) > 0;
}
const bool isInt = INT_ROLES.contains(role);
if (isInt) {
const int leftInt = leftData.toInt();
const int rightInt = rightData.toInt();
return leftInt > rightInt;
}
const bool isDouble = DOUBLE_ROLES.contains(role);
if (isDouble) {
const int leftInt = leftData.toDouble();
const int rightInt = rightData.toDouble();
return leftInt > rightInt;
}
return false;
}
bool GeneralSortFilterModel::indexContainsText(const QModelIndex& index,
const QString& text) const {
// iterate over USER_FACING_ROLES and call roleDataContainsText(...);
// ...for each until text is found or no more roles to check;
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const bool isTextFound = roleDataContainsText(index, role, text);
if (isTextFound) {
// qInfo() << "Text is found in role:" << role;
return true;
// } else {
// qDebug() << QString("Can't find text in role %1. Continuing search...").arg(role);
}
}
// qWarning() << "Text not found in any role. Returning false...";
return false;
}
bool GeneralSortFilterModel::roleDataContainsText(const QModelIndex& index,
const int role,
const QString& text) const {
const QString dataString = index.data(role).toString();
if (dataString.contains(text, Qt::CaseInsensitive)) {
return true;
} else {
return false;
}
}

View File

@ -0,0 +1,36 @@
#ifndef GENERALSORTFILTERMODEL_H
#define GENERALSORTFILTERMODEL_H
#include <QCollator>
#include <QSortFilterProxyModel>
#include "tablemodel.h"
class GeneralSortFilterModel : public QSortFilterProxyModel {
Q_OBJECT
public:
explicit GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel = nullptr);
/** Returns a QItemSelection with all ModelIndexes which contain the given text.
* @brief Returns QItemSelection containing all successful ModelIndex results
* @param text To search for
* @return QItemSelection containing all successful ModelIndex results
*/
QItemSelection findItems(const QString& text) const;
public slots:
void appendItems(const QByteArray& jsonDoc);
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
/// QSortFilterProxyModel interface
protected:
bool lessThan(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
private:
std::shared_ptr<TableModel> m_tableModel;
QCollator m_collator; /// for sorting
bool indexContainsText(const QModelIndex& index, const QString& text) const;
bool roleDataContainsText(const QModelIndex& index, const int role, const QString& text) const;
};
#endif // GENERALSORTFILTERMODEL_H

70
model/metadata.h Normal file
View File

@ -0,0 +1,70 @@
#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,
/// helper roles
ToStringRole
};
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

81
model/modelitem.cpp Normal file
View File

@ -0,0 +1,81 @@
#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;
}
QString ModelItem::toString() const {
QString result;
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);
// result.append(value.toString());
result.append(QString("%1: %2\n").arg(roleName, data(role).toString()));
}
return result;
}
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
View 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

279
model/tablemodel.cpp Normal file
View File

@ -0,0 +1,279 @@
#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);
case ToStringRole:
return m_items.at(row)->toString();
}
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
View 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