Compare commits

...

76 Commits

Author SHA1 Message Date
5530aff2f3 Converting saveItems() into a public slot to be invokable from QML. 2026-03-09 15:44:51 +01:00
c1ee2135df TableModel::setData can now be called for column 0 with different roles to edit. (Doesn't rely on Qt::EditRole and RoleForColumn in all cases) 2026-03-09 07:46:28 +01:00
a6648b7d1e Added "display" as role name. (For the QML UI) 2026-03-05 12:30:43 +01:00
dbfaee27dc Added messagehandler.h (moved from widgets UI project). 2026-03-03 18:56:39 +01:00
f392efb54f Added static GET_HEADER_FOR_COLUMN(const int column) function. 2026-03-02 16:25:01 +01:00
057bd244bd Added type roles to the calculation if an item is equal to the given item values. 2026-03-01 11:37:00 +01:00
c9d67ff2cc In TableModel::data(...): Default to ModelItem::data(...) for non user facing roles too. 2026-03-01 11:35:26 +01:00
13dc22de9f Add type roles to the model sorting capabilities. 2026-03-01 11:34:06 +01:00
e68b446407 A new role doesn't have to be added to TableModel::data(...) anymore. 2026-03-01 11:33:08 +01:00
6fc3ffc537 Added missing type role to TableModel::data(...). 2026-03-01 11:25:57 +01:00
f694e0e5ed Further refactoring after the addition of the type role. 2026-03-01 11:11:46 +01:00
becde8c794 Added type role and column & refactored the JsonParser in the process. 2026-03-01 10:59:34 +01:00
1db5d9022a Hotfix: Using the correct member variable for the model tester of the proxy model in Release compilation. 2026-02-04 11:52:09 +01:00
cf55adc34e Bumped version to 0.3.0. 2026-02-04 11:28:08 +01:00
5318390749 Merge branch 'feature/restClient' into develop 2026-02-03 12:07:45 +01:00
b6c49dda20 Minor clean up in JsonParser. 2026-02-03 12:05:52 +01:00
7ae10e6ed7 Added GenericCore::getSettings(...) for the UIs (they don't need to use the NetworkHandler directly). 2026-02-03 11:19:24 +01:00
6adf18caeb Server settings are read from QSettings and applied if they are changed. 2026-02-03 11:17:26 +01:00
d4ff1ffb61 Split TableModel::updateItemsFromJson(...) into two functions and added support for multiple items in JSON data. 2026-02-02 16:48:42 +01:00
ba482e6e17 Added getUuid(itemIndex) to proxy model to prevent using IdRole in UI when an item should be referenced (i. e. for deletion on server). 2026-02-02 16:46:10 +01:00
db1ecbece0 Current items can be deleted by passing the UUID to the deleteItemFromServer signal. 2026-02-02 16:15:43 +01:00
63fe96fb2e On sending (posting) item to the server the generated UUID is added to the local item. 2026-02-02 16:13:44 +01:00
bedf8084d3 Retrieving the JSON data of the current index to send to the server through the proxy model. Sending this data happens by triggering the core. 2026-01-29 13:13:32 +01:00
2a152daa70 Using lower case role names for improved compatibility with the server. 2026-01-29 13:06:46 +01:00
08c2e3a093 Added IdRole for the server generated UUID of the items. 2026-01-29 09:27:50 +01:00
bc96a805f8 An item (with hard coded values) can be send to the server. Added signals for fetching and posting items to be triggered from the UI. 2026-01-29 08:54:47 +01:00
e29cd0aebf Basic JSON RESTful client fetching items from a local server at application start and adding them to the model. 2026-01-25 10:47:19 +01:00
e1bc779791 Added QAbstractItemModelTester to main and proxy model. And fixing errors in functions flags(...), rowCount(...) and columnCount(...). 2026-01-19 18:43:13 +01:00
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
30 changed files with 2352 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.3.0 LANGUAGES CXX)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
@ -8,23 +9,48 @@ 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)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Network)
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
model/generalsortfiltermodel.h model/generalsortfiltermodel.cpp
network/servercommunicator.h network/servercommunicator.cpp
network/apiroutes.h
# 3rd party libraries
../3rdParty/rapidcsv/src/rapidcsv.h
utils/messagehandler.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_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Test)
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Network)
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 QMap<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

162
formats/csvparser.cpp Normal file
View File

@ -0,0 +1,162 @@
#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) {
// TODO 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 (TYPE_ROLES.contains(role)) {
/// type values
// TODO validate string is allowed
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)) {
// // TODO 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 QMap<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

143
formats/jsonparser.cpp Normal file
View File

@ -0,0 +1,143 @@
#include "jsonparser.h"
#include <QJsonArray>
#include <QJsonObject>
#include "../model/metadata.h"
QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData,
const QString& rootValueName) {
QList<ModelItemValues> result;
if (jsonData.isEmpty()) {
return result;
}
// TODO tidy up the following code and encapsulate into functions;
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
/// case one: json value name in plural -> should contain an array of items
if (rootValueName == ITEMS_KEY_STRING) {
QJsonArray itemArray = extractItemArray(doc, rootValueName);
foreach (QJsonValue value, itemArray) {
QJsonObject itemJsonObject = value.toObject();
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
result.append(values);
}
}
/// case two: json value name in singular -> should contain an object of one item
if (rootValueName == ITEM_KEY_STRING) {
QJsonObject rootObject = doc.object();
QJsonObject itemJsonObject = rootObject.value(rootValueName).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 ModelItemValues& itemValues : itemValuesList) {
QJsonObject itemObject = itemValuesToJsonObject(itemValues);
itemArray.append(itemObject);
}
rootObject.insert(objectName, itemArray);
jsonDoc.setObject(rootObject);
return jsonDoc.toJson(QJsonDocument::Compact);
}
QJsonObject JsonParser::itemValuesToJsonObject(const ModelItemValues& itemValues) {
QJsonObject result;
// TODO add dates (entry, modification, end)
const UserRoles idRole = IdRole;
const QJsonValue idValue = extractJsonValue(itemValues, idRole);
if (!idValue.isNull()) {
const QString idRoleName = ROLE_NAMES.value(idRole);
result.insert(idRoleName, idValue);
}
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QJsonValue jsonValue = extractJsonValue(itemValues, role);
const QString roleName = ROLE_NAMES.value(role);
result.insert(roleName, jsonValue);
}
return result;
}
JsonParser::JsonParser() {}
QJsonArray JsonParser::extractItemArray(const QJsonDocument& doc, const QString& objectName) {
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;
const UserRoles idRole = IdRole;
const QString idRoleName = ROLE_NAMES.value(idRole);
// QVariant idValue = data(idRole);
if (itemJsonObject.contains(idRoleName)) {
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, idRole);
values.insert(keyValuePair.first, keyValuePair.second);
}
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 if (TYPE_ROLES.contains(role)) {
result = jsonValue.toString();
} else {
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
}
return pair<int, QVariant>(role, result);
}
QJsonValue JsonParser::extractJsonValue(const ModelItemValues& itemValues, const int role) {
QJsonValue result;
const QString roleName = ROLE_NAMES.value(role);
const QVariant value = itemValues.value(role);
if (STRING_ROLES.contains(role)) {
result = value.toString();
} else if (INT_ROLES.contains(role)) {
result = value.toInt();
} else if (DOUBLE_ROLES.contains(role)) {
result = value.toDouble();
} else if (TYPE_ROLES.contains(role)) {
result = value.toString();
} else {
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
}
return result;
}

34
formats/jsonparser.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef JSONPARSER_H
#define JSONPARSER_H
#include <QVariant>
class QJsonObject;
class QString;
class QByteArray;
class QJsonArray;
typedef QMap<int, QVariant> ModelItemValues;
using namespace std;
class JsonParser {
public:
static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData,
const QString& rootValueName = "");
static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
const QString& objectName = "");
static QJsonObject itemValuesToJsonObject(const ModelItemValues& itemValues);
private:
explicit JsonParser();
static QJsonArray extractItemArray(const QJsonDocument& doc, const QString& objectName);
static ModelItemValues jsonObjectToItemValues(const QJsonObject& itemJsonObject);
static pair<int, QVariant> getKeyValuePair(const QJsonObject& itemJsonObject, const int role);
static QJsonValue extractJsonValue(const ModelItemValues& itemValues, const int role);
};
#endif // JSONPARSER_H

View File

@ -1,3 +1,281 @@
#include "genericcore.h"
GenericCore::GenericCore() {}
#include <QAbstractItemModelTester>
#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 "data/settingshandler.h"
#include "model/generalsortfiltermodel.h"
#include "model/metadata.h"
#include "model/tablemodel.h"
#include "network/servercommunicator.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();
setupServerConfiguration();
}
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, ITEMS_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);
// TODO 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);
}
QVariantMap GenericCore::getSettings(QString group) const {
return SettingsHandler::getSettings(group);
}
void GenericCore::applySettings(QVariantMap settingMap, QString group) {
SettingsHandler::saveSettings(settingMap, group);
if (group == "Server") {
setupServerConfiguration();
}
}
bool GenericCore::isSyncServerSetup() const {
if (m_serverCommunicator) {
return true;
} else {
return false;
}
}
void GenericCore::onSendItemTriggered(const QByteArray& jsonData) {
m_serverCommunicator->postItems(jsonData);
}
void GenericCore::onItemsFetched(const QByteArray jsonData) {
emit displayStatusMessage("New items fetched.");
// TODO ? check compability of JSON structure beforehand?
// NEXT check if item already exists and apply changes (UUID,...) ? ;
m_mainModel->appendItems(jsonData);
}
void GenericCore::onItemsFetchFailure(const QString errorString) {
emit displayStatusMessage(QString("Error: %1").arg(errorString));
}
void GenericCore::onPostRequestSuccessful(const QByteArray responseData) {
const QString message = m_mainModel->updateItemsFromJson(responseData);
emit displayStatusMessage(message);
}
void GenericCore::onPostRequestFailure(const QString errorString) {
emit displayStatusMessage(QString("Error: %1").arg(errorString));
}
void GenericCore::onDeleteRequestSuccessful(const QByteArray responseData) {
qWarning() << "TODO: Process success response!!!";
}
void GenericCore::onDeleteRequestFailure(const QString errorString) {
qWarning() << "TODO: Process error response!!!";
}
void GenericCore::setupModels() {
m_mainModel = make_shared<TableModel>(m_modelUndoStack, this);
m_sortFilterModel = make_shared<GeneralSortFilterModel>(m_mainModel);
/// QAbstractItemModelTester
#ifdef QT_DEBUG
m_mainModelTester = make_unique<QAbstractItemModelTester>(
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
#else
m_mainModelTester = make_unique<QAbstractItemModelTester>(
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
#endif
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(ITEMS_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;
}
void GenericCore::setupServerConfiguration() {
m_serverCommunicator = make_unique<ServerCommunicator>(this);
/// request connections
connect(this, &GenericCore::fetchItemsFromServer, m_serverCommunicator.get(),
&ServerCommunicator::fetchItems);
connect(this, &GenericCore::postItemToServer, this, &GenericCore::onSendItemTriggered);
connect(this, &GenericCore::deleteItemFromServer, m_serverCommunicator.get(),
&ServerCommunicator::deleteItem);
/// response connections
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetched, this,
&GenericCore::onItemsFetched);
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetchFailure, this,
&GenericCore::onItemsFetchFailure);
connect(m_serverCommunicator.get(), &ServerCommunicator::postRequestSuccessful, this,
&GenericCore::onPostRequestSuccessful);
connect(m_serverCommunicator.get(), &ServerCommunicator::postRequestFailure, this,
&GenericCore::onPostRequestFailure);
connect(m_serverCommunicator.get(), &ServerCommunicator::deleteRequestSuccessful, this,
&GenericCore::onDeleteRequestSuccessful);
connect(m_serverCommunicator.get(), &ServerCommunicator::deleteRequestFailure, this,
&GenericCore::onDeleteRequestFailure);
applyServerConfiguration();
}
void GenericCore::applyServerConfiguration() {
const QVariantMap serverSettings = SettingsHandler::getSettings("Server");
const QString urlValue = serverSettings.value("url").toString();
if (!urlValue.isEmpty()) {
const QString emailValue = serverSettings.value("email").toString();
const QString passwordValue = serverSettings.value("password").toString();
m_serverCommunicator->setServerConfiguration(urlValue, emailValue, passwordValue);
}
}

View File

@ -1,10 +1,74 @@
#ifndef GENERICCORE_H
#define GENERICCORE_H
class GenericCore
{
public:
GenericCore();
#include <QObject>
class QUndoStack;
class QAbstractItemModel;
class QAbstractItemModelTester;
class QString;
class TableModel;
class GeneralSortFilterModel;
class ServerCommunicator;
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 importCSVFile(const QString& filePath);
bool exportCSVFile(const QString& filePath);
QVariantMap getSettings(QString group = "") const;
void applySettings(QVariantMap settingMap, QString group = "");
bool isSyncServerSetup() const;
public slots:
void saveItems();
void onSendItemTriggered(const QByteArray& jsonData);
void onItemsFetched(const QByteArray jsonData);
void onItemsFetchFailure(const QString errorString);
void onPostRequestSuccessful(const QByteArray responseData);
void onPostRequestFailure(const QString errorString);
void onDeleteRequestSuccessful(const QByteArray responseData);
void onDeleteRequestFailure(const QString errorString);
signals:
void displayStatusMessage(QString message);
void fetchItemsFromServer();
void postItemToServer(const QByteArray& jsonData);
void deleteItemFromServer(const QString& id);
private:
QUndoStack* m_modelUndoStack;
std::shared_ptr<TableModel> m_mainModel;
std::shared_ptr<GeneralSortFilterModel> m_sortFilterModel;
std::unique_ptr<QAbstractItemModelTester> m_mainModelTester;
std::unique_ptr<QAbstractItemModelTester> m_proxyModelTester;
void setupModels();
void initModelData();
QString getMaintenanceToolFilePath() const;
/// Network communication
std::unique_ptr<ServerCommunicator> m_serverCommunicator;
void setupServerConfiguration();
void applyServerConfiguration();
};
#endif // GENERICCORE_H
#endif // GENERICCORE_H

View File

@ -0,0 +1,80 @@
#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 if (role == IdRole) {
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 QMap<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 QMap<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,111 @@
#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;
}
QString GeneralSortFilterModel::getUuid(const QModelIndex& itemIndex) const {
return data(itemIndex, IdRole).toString();
}
QByteArray GeneralSortFilterModel::jsonDataForServer(const QModelIndex& proxyIndex) {
const QModelIndex sourceIndex = mapToSource(proxyIndex);
return m_tableModel->jsonDataForServer(sourceIndex);
}
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 isType = TYPE_ROLES.contains(role);
if (isType) {
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,39 @@
#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;
QString getUuid(const QModelIndex& itemIndex) const;
QByteArray jsonDataForServer(const QModelIndex& proxyIndex);
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

96
model/metadata.h Normal file
View File

@ -0,0 +1,96 @@
#ifndef METADATA_H
#define METADATA_H
#include <QDebug>
#include <QHash>
#include <QList>
#include <QString>
// TODO add namespace
/// model data
enum UserRoles {
NameRole = Qt::UserRole + 1,
DescriptionRole,
InfoRole,
TypeRole,
AmountRole,
FactorRole,
/// Non user facing
IdRole,
/// read only roles
ToStringRole,
ToJsonRole
};
static UserRoles DEFAULT_ROLE = NameRole;
// TODO ?rename USER_FACING_ROLES -> MAIN_ROLES ?
static QList<UserRoles> USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole,
TypeRole, AmountRole, FactorRole};
static QHash<int, QByteArray> ROLE_NAMES = {
{NameRole, "name"}, {DescriptionRole, "description"},
{InfoRole, "info"}, {TypeRole, "type"},
{AmountRole, "amount"}, {FactorRole, "factor"},
{ToStringRole, "ToString"}, {IdRole, "id"},
{Qt::DisplayRole, "display"}, {Qt::EditRole, "edit"}};
static QList<UserRoles> STRING_ROLES = {NameRole, DescriptionRole, InfoRole, IdRole};
static QList<UserRoles> INT_ROLES = {AmountRole};
static QList<UserRoles> DOUBLE_ROLES = {FactorRole};
static const QList<UserRoles> TYPE_ROLES = {TypeRole};
static const QList<QString> TYPES = {"A", "B", "C", ""};
/// JSON keys
static const QString ITEMS_KEY_STRING = "items";
static const QString ITEM_KEY_STRING = "item";
/// file naming
static const QString ITEMS_FILE_NAME = ITEMS_KEY_STRING + ".json";
/// functions
static UserRoles 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 TypeRole;
break;
case 4:
return AmountRole;
break;
case 5:
return FactorRole;
break;
default:
qWarning() << QString("No role found for column %1! Returning 'NameRole'...").arg(column);
return NameRole;
break;
}
}
static int GET_COLUMN_FOR_ROLE(const UserRoles role) { return USER_FACING_ROLES.indexOf(role); }
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;
}
static QString GET_HEADER_FOR_COLUMN(const int column) {
const UserRoles role = GET_ROLE_FOR_COLUMN(column);
const QString headerName = ROLE_NAMES.value(role);
return headerName;
}
#endif // METADATA_H

72
model/modelitem.cpp Normal file
View File

@ -0,0 +1,72 @@
#include "modelitem.h"
#include <QJsonObject>
#include <QJsonValue>
#include "../formats/jsonparser.h"
#include "metadata.h"
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()));
}
const UserRoles idRole = IdRole;
QVariant idValue = data(idRole);
if (!idValue.isNull()) {
const QString idRoleName = ROLE_NAMES.value(idRole);
result.append(QString("%1: %2\n").arg(idRoleName, idValue.toString()));
}
return result;
}
QJsonObject ModelItem::toJsonObject() const {
QJsonObject itemObject = JsonParser::itemValuesToJsonObject(m_values);
return itemObject;
}

24
model/modelitem.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef MODELITEM_H
#define MODELITEM_H
#include <QVariant>
typedef QMap<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:
ModelItemValues m_values;
};
#endif // MODELITEM_H

409
model/tablemodel.cpp Normal file
View File

@ -0,0 +1,409 @@
#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;
// TODO use JsonParser for the item generation
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(ITEMS_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 {
if (!index.isValid()) {
return QAbstractTableModel::flags(index);
}
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}
QHash<int, QByteArray> TableModel::roleNames() const { return ROLE_NAMES; }
int TableModel::rowCount(const QModelIndex& parent) const {
if (parent.isValid()) {
return 0; /// no children
}
return m_items.size();
}
int TableModel::columnCount(const QModelIndex& parent) const {
if (parent.isValid()) {
return 0; /// no children
}
return USER_FACING_ROLES.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 ToStringRole:
return m_items.at(row)->toString();
case ToJsonRole:
return m_items.at(row)->toJsonObject();
case IdRole:
return m_items.at(row)->data(role);
default:
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 (checkIndex(index)) {
const int adjustedRole = getAppropriateRoleForIndex(index, role);
return setItemData(index, {{adjustedRole, 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(ITEMS_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;
}
// TODO use item selection as parameter to wrap multiple items into JSON data structure
QByteArray TableModel::jsonDataForServer(const QModelIndex& currentIndex) const {
const QJsonObject itemObject = data(currentIndex, ToJsonRole).toJsonObject();
QJsonObject rootObject;
rootObject.insert(ITEM_KEY_STRING, itemObject);
const QJsonDocument jsonDoc(rootObject);
return jsonDoc.toJson(QJsonDocument::Compact);
}
QString TableModel::updateItemsFromJson(const QByteArray& jsonData) {
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonData, ITEM_KEY_STRING);
int nChangedItems = 0;
for (const ModelItemValues& itemValues : valueList) {
bool updateHappened = updateItem(itemValues);
if (updateHappened) {
nChangedItems++;
}
}
return QString("Found and updated %1 item(s).").arg(nChangedItems);
}
bool TableModel::updateItem(const ModelItemValues& itemValues) {
QModelIndex foundIndex = searchItemIndex(itemValues);
qDebug() << "Search done!";
if (foundIndex == QModelIndex()) {
const QString errorMessage = "No matching item found!";
qWarning() << errorMessage;
return false;
} else {
qInfo() << "Item found!";
/// update existing item
setItemData(foundIndex, itemValues);
return true;
}
}
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, ITEMS_KEY_STRING);
if (valueList.empty()) {
/// don't try inserting if no values to insert
qDebug() << "No items found in JSON document. Not adding anything...";
return;
}
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, USER_FACING_ROLES.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);
// REFACTOR the next if statement is too complex
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;
}
}
int TableModel::getAppropriateRoleForIndex(const QModelIndex& index, const int role) const {
/// cases:
/// 1. Qt::DisplayRole, Qt::EditRole
/// -> get role for column
/// 2. other roles
/// -> use role as given
const int column = index.column();
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return roleForColumn;
break;
default:
return role;
break;
}
}
QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const {
// iterate over indexes to search item : see searchItem(...);
// for (const shared_ptr<ModelItem>& item : m_items) {
for (int row = 0; row < rowCount(); ++row) {
qDebug() << "Processing item at row" << row << "...";
QModelIndex itemIndex = index(row, 0);
if (isItemEqualToItemValues(itemIndex, givenItemValues)) {
qInfo() << "Found item at row" << row << "! Returning its index...";
return itemIndex;
}
}
qDebug() << "No matching item found. Returning empty pointer...";
return {};
}
bool TableModel::isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const {
/// do both have a UUID?
QVariant idOfItem = data(itemIndex, IdRole);
QVariant given = givenItemValues.value(IdRole);
if (idOfItem.isValid() && given.isValid()) {
/// are the UUIDs the same?
if (idOfItem.toString() == given.toString()) {
qInfo() << "UUIDs are the same.";
return true;
} else {
qDebug() << "UUIDs are NOT the same.";
return false;
}
} else {
/// are all other values the same? (for now only USER_FACING_ROLES are checked)
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QString roleName = ROLE_NAMES.value(role);
const QVariant valueOfItem = data(itemIndex, role);
const QVariant givenValue = givenItemValues.value(role);
if (STRING_ROLES.contains(role)) {
if (valueOfItem.toString() != givenValue.toString()) {
return false;
}
} else if (TYPE_ROLES.contains(role)) {
if (valueOfItem.toString() != givenValue.toString()) {
return false;
}
} else if (INT_ROLES.contains(role)) {
if (valueOfItem.toInt() != givenValue.toInt()) {
return false;
}
} else if (DOUBLE_ROLES.contains(role)) {
if (valueOfItem.toDouble() != givenValue.toDouble()) {
return false;
}
} else {
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
}
}
return true;
}
}

80
model/tablemodel.h Normal file
View File

@ -0,0 +1,80 @@
#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QAbstractTableModel>
class QUndoStack;
class ModelItem;
using namespace std;
typedef QMap<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;
QByteArray jsonDataForServer(const QModelIndex& currentIndex) const;
QString updateItemsFromJson(const QByteArray& jsonData);
bool updateItem(const ModelItemValues& itemValues);
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;
int getAppropriateRoleForIndex(const QModelIndex& index, const int role) const;
QModelIndex searchItemIndex(const ModelItemValues givenItemValues) const;
bool isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const;
};
#endif // TABLEMODEL_H

12
network/apiroutes.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef APIROUTES_H
#define APIROUTES_H
#include <QString>
// TODO add namespace
static const QString apiPrefix = "/api/";
static const QString ROUTE_ITEMS = apiPrefix + "items";
#endif // APIROUTES_H

View File

@ -0,0 +1,106 @@
#include "servercommunicator.h"
#include "apiroutes.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QRestReply>
using namespace Qt::StringLiterals;
ServerCommunicator::ServerCommunicator(QObject* parent)
: QObject{parent} {
m_netManager.setAutoDeleteReplies(true);
m_restManager = std::make_shared<QRestAccessManager>(&m_netManager);
m_serviceApi = std::make_shared<QNetworkRequestFactory>();
}
bool ServerCommunicator::sslSupported() {
#if QT_CONFIG(ssl)
return QSslSocket::supportsSsl();
#else
return false;
#endif
}
QUrl ServerCommunicator::url() const { return m_serviceApi->baseUrl(); }
void ServerCommunicator::setUrl(const QUrl& url) {
if (m_serviceApi->baseUrl() == url) {
return;
}
m_serviceApi->setBaseUrl(url);
QHttpHeaders authenticationHeaders;
authenticationHeaders.append(QHttpHeaders::WellKnownHeader::ContentType, "application/json");
m_serviceApi->setCommonHeaders(authenticationHeaders);
emit urlChanged();
}
void ServerCommunicator::fetchItems() {
/// Set up a GET request
m_restManager->get(m_serviceApi->createRequest(ROUTE_ITEMS), this, [this](QRestReply& reply) {
if (reply.isSuccess()) {
qInfo() << "Fetching items successful.";
const QJsonDocument doc = reply.readJson().value();
emit itemsFetched(doc.toJson());
} else {
if (reply.hasError()) {
const QString errorString = reply.errorString();
qCritical() << "ERROR:" << errorString;
emit itemsFetchFailure(errorString);
} else {
int statusCode = reply.httpStatus();
qCritical() << "ERROR:" << statusCode;
emit itemsFetchFailure(QString::number(statusCode));
emit itemsFetchFailure(QString("HTTP status code: %1").arg(statusCode));
}
}
});
}
void ServerCommunicator::postItems(const QByteArray& jsonData) {
QNetworkReply* reply = m_restManager->post(m_serviceApi->createRequest(ROUTE_ITEMS), jsonData);
QObject::connect(reply, &QNetworkReply::finished, [=]() {
if (reply->error() == QNetworkReply::NoError) {
QByteArray responseData = reply->readAll();
const QString message = QString("POST successful! Response: %1").arg(responseData);
qInfo() << message;
emit postRequestSuccessful(responseData);
} else {
const QString message = QString("Error: %1").arg(reply->errorString());
qDebug() << message;
emit postRequestFailure(message);
}
reply->deleteLater();
});
}
void ServerCommunicator::deleteItem(const QString& id) {
const QString deleteRoute = QString("%1/%2").arg(ROUTE_ITEMS, id);
QNetworkReply* reply = m_restManager->deleteResource(m_serviceApi->createRequest(deleteRoute));
QObject::connect(reply, &QNetworkReply::finished, [=]() {
if (reply->error() == QNetworkReply::NoError) {
QByteArray responseData = reply->readAll();
const QString message = QString("DELETE successful! Response: %1").arg(responseData);
qInfo() << message;
emit deleteRequestSuccessful(responseData);
} else {
const QString message = QString("Error: %1").arg(reply->errorString());
qDebug() << message;
emit deleteRequestFailure(message);
}
reply->deleteLater();
});
}
void ServerCommunicator::setServerConfiguration(const QString url,
const QString email,
const QString password) {
setUrl(url);
m_email = email;
m_password = password;
}

View File

@ -0,0 +1,46 @@
#ifndef SERVERCOMMUNICATOR_H
#define SERVERCOMMUNICATOR_H
#include <QNetworkAccessManager>
#include <QNetworkRequestFactory>
#include <QObject>
#include <QRestAccessManager>
class ServerCommunicator : public QObject {
Q_OBJECT
public:
explicit ServerCommunicator(QObject* parent = nullptr);
bool sslSupported();
QUrl url() const;
void setUrl(const QUrl& url);
void setServerConfiguration(const QString url, const QString email, const QString password);
public slots:
void fetchItems();
void postItems(const QByteArray& jsonData);
void deleteItem(const QString& id);
signals:
void urlChanged();
void itemsFetched(const QByteArray jsonDoc);
void itemsFetchFailure(const QString errorString);
void postRequestSuccessful(const QByteArray responseData);
void postRequestFailure(const QString errorString);
void deleteRequestSuccessful(const QByteArray responseData);
void deleteRequestFailure(const QString errorString);
private:
QNetworkAccessManager m_netManager;
std::shared_ptr<QRestAccessManager> m_restManager;
std::shared_ptr<QNetworkRequestFactory> m_serviceApi;
QString m_email;
QString m_password;
// QString m_authToken;
};
#endif // SERVERCOMMUNICATOR_H

164
utils/messagehandler.h Normal file
View File

@ -0,0 +1,164 @@
#ifndef MESSAGEHANDLER_H
#define MESSAGEHANDLER_H
/**
* Color and formatting codes
* @see: http://misc.flogisoft.com/bash/tip_colors_and_formatting
*/
#include <QObject>
// qSetMessagePattern("%{file}(%{line}): %{message}");
// qSetMessagePattern("%{type}(%{line}):\t%{message}");
// qSetMessagePattern("%{type}%{file}(%{line}):\t%{message}");
void consoleHandlerColoredVerbose(QtMsgType type,
const QMessageLogContext& context,
const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
// context.line, context.function, localMsg.constData()); // bold
fprintf(stderr, "\033[107;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtInfoMsg:
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtWarningMsg:
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
abort();
}
}
void consoleHandlerColoredVerboseInDarkTheme(QtMsgType type,
const QMessageLogContext& context,
const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
// context.line, context.function, localMsg.constData()); // bold
fprintf(stderr, "\033[107;37mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtInfoMsg:
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtWarningMsg:
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
abort();
}
}
void consoleHandlerColored(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "\033[1;30mDebug: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtInfoMsg:
fprintf(stderr, "\033[0;30mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtWarningMsg:
fprintf(stderr, "\033[1;33mWarning: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "\033[31mCritical: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "\033[31mFatal: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
abort();
}
}
void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
abort();
}
}
#ifdef Q_OS_ANDROID
#include <android/log.h>
const char* const applicationName = "Pensieve";
void androidMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QString report = msg;
if (context.file && !QString(context.file).isEmpty()) {
report += " in file ";
report += QString(context.file);
report += " line ";
report += QString::number(context.line);
}
if (context.function && !QString(context.function).isEmpty()) {
report += +" function ";
report += QString(context.function);
}
const char* const local = report.toLocal8Bit().constData();
switch (type) {
case QtDebugMsg:
__android_log_write(ANDROID_LOG_DEBUG, applicationName, local);
break;
case QtInfoMsg:
__android_log_write(ANDROID_LOG_INFO, applicationName, local);
break;
case QtWarningMsg:
__android_log_write(ANDROID_LOG_WARN, applicationName, local);
break;
case QtCriticalMsg:
__android_log_write(ANDROID_LOG_ERROR, applicationName, local);
break;
case QtFatalMsg:
default:
__android_log_write(ANDROID_LOG_FATAL, applicationName, local);
abort();
}
}
#endif
#endif // MESSAGEHANDLER_H