aboutsummaryrefslogtreecommitdiffstats
path: root/src/imports/utils/quickstudiocsvtablemodel.cpp
blob: 6f08f39e96d8465a63bdb376b522d4b4168d4c51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/****************************************************************************
**
** Copyright (C) 2023 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Quick Dialogs module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "quickstudiocsvtablemodel_p.h"

#include <QColor>
#include <QFile>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QLoggingCategory>
#include <QRegularExpression>
#include <QTextStream>

static QVariant stringToVariant(const QString &value)
{
    constexpr QStringView typesPattern{u"(?<boolean>^(?:true|false)$)|"
                                       u"(?<number>^(?:-?(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?<=\\d|\\.)"
                                       u"(?:e-?(?:0|[1-9]\\d*))?|0x[0-9a-f]+)$)|"
                                       u"(?<color>^(?:#(?:(?:[0-9a-fA-F]{2}){3,4}|"
                                       u"(?:[0-9a-fA-F]){3,4}))$)"};

    static QRegularExpression validator(typesPattern.toString());
    const QString trimmedValue = value.trimmed();
    QRegularExpressionMatch match = validator.match(trimmedValue);

    if (!match.hasMatch())
        return value;

    if (!match.captured(u"boolean").isEmpty())
        return QVariant::fromValue<bool>(trimmedValue.at(0).toLower() == u't');

    if (!match.captured(u"number").isEmpty())
        return trimmedValue.toDouble();

    if (!match.captured(u"color").isEmpty())
        return QColor::fromString(trimmedValue);

    return value;
}

static QVariant stringToVariant(const QString &value, QMetaType::Type type, bool *ok = nullptr)
{
    if (type == QMetaType::Bool) {
        const QString lowerValue = value.toLower().trimmed();
        bool conversionOk = true;
        bool booleanValue = false;

        if (lowerValue == u"true")
            booleanValue = true;
        else if (lowerValue == u"false")
            booleanValue = false;
        else
            conversionOk = false;

        if (ok)
            *ok = conversionOk;

        if (conversionOk)
            return booleanValue;
    }

    if (type == QMetaType::Double) {
        bool conversionOk = false;
        double numericValue = value.toDouble(&conversionOk);
        if (ok)
            *ok = conversionOk;

        if (conversionOk)
            return numericValue;
    }

    if (type == QMetaType::QColor) {
        bool conversionOk = QColor::isValidColorName(value);
        if (ok)
            *ok = conversionOk;

        if (conversionOk)
            return QColor::fromString(value);
    }

    if (type == QMetaType::QString) {
        if (ok)
            *ok = !value.isEmpty();
    }

    return value;
}

static QString urlToLocalPath(const QUrl &url)
{
    QString localPath;

    if (url.isLocalFile())
        localPath = url.toLocalFile();

    if (url.scheme() == QLatin1String("qrc")) {
        const QString &path = url.path();
        localPath = QStringLiteral(":") + path;
    }

    return localPath;
}

static Q_LOGGING_CATEGORY(texttomodelMergerDebug, "qt.StudioCsvTableModel.debug", QtDebugMsg)
    QuickStudioCsvTableModel::QuickStudioCsvTableModel(QObject *parent)
    : QAbstractTableModel(parent)
    , m_fileWatcher(new QFileSystemWatcher(this))
{
    connect(m_fileWatcher,
            &QFileSystemWatcher::fileChanged,
            this,
            &QuickStudioCsvTableModel::checkPathAndReload);
}

int QuickStudioCsvTableModel::rowCount([[maybe_unused]] const QModelIndex &parent) const
{
    return m_rows.size();
}

int QuickStudioCsvTableModel::columnCount([[maybe_unused]] const QModelIndex &parent) const
{
    return m_headers.size();
}

QVariant QuickStudioCsvTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return {};

    const QHash<int, QVariant> &recordData = m_rows.at(index.row());

    if (role == Qt::DisplayRole)
        return recordData.value(index.column()).toString();

    return recordData.value(index.column());
}

QVariant QuickStudioCsvTableModel::headerData(int section,
                                              Qt::Orientation orientation,
                                              [[maybe_unused]] int role) const
{
    if (orientation == Qt::Horizontal) {
        if (section > -1 && section < m_headers.size())
            return m_headers.at(section);
    } else if (orientation == Qt::Vertical) {
        if (section > -1 && section < m_rows.size())
            return section;
    }

    return {};
}

QUrl QuickStudioCsvTableModel::source() const
{
    return m_source;
}

void QuickStudioCsvTableModel::setSource(const QUrl &newSource)
{
    if (m_source == newSource)
        return;

    m_source = newSource;
    emit this->sourceChanged(m_source);

    startWatchingSource();
    reloadModel();
}

void QuickStudioCsvTableModel::reloadModel()
{
    beginResetModel();
    m_headers.clear();
    m_rows.clear();
    m_types.clear();
    m_columnIsClean.clear();

    QString filePath = ::urlToLocalPath(source());
    QFile sourceFile(filePath);

    if (!sourceFile.open(QFile::ReadOnly)) {
        qWarning() << "File cannot be opened:" << sourceFile.errorString();
        endResetModel();
        return;
    }

    QTextStream stream(&sourceFile);

    if (!stream.atEnd())
        m_headers = stream.readLine().split(u',', Qt::KeepEmptyParts);

    m_types.insert(0, m_headers.size(), QMetaType::UnknownType);
    m_columnIsClean.insert(0, m_headers.size(), true);

    if (!m_headers.isEmpty()) {
        while (!stream.atEnd()) {
            const QStringList recordDataList = stream.readLine().split(u',', Qt::KeepEmptyParts);
            int column = -1;
            QHash<int, QVariant> recordData;
            for (const QString &cellString : recordDataList) {
                if (++column == m_headers.size())
                    break;

                if (!cellString.size())
                    continue;

                const QMetaType::Type &type = m_types.at(column);

                QVariant cellData;
                if (type == QMetaType::UnknownType) {
                    cellData = stringToVariant(cellString);
                    m_types.replace(column, QMetaType::Type(cellData.typeId()));
                } else {
                    bool columnIsClean = m_columnIsClean.at(column);
                    bool *ok = columnIsClean ? &columnIsClean : nullptr;
                    cellData = stringToVariant(cellString, type, ok);
                    if (ok)
                        m_columnIsClean.replace(column, *ok);
                }
                recordData.insert(column, cellData);
            }
            m_rows.append(recordData);
        }
    }

    endResetModel();
}

void QuickStudioCsvTableModel::checkPathAndReload(const QString &path)
{
    QString sourceLocalPath = ::urlToLocalPath(source());
    if (path == sourceLocalPath)
        reloadModel();
}

void QuickStudioCsvTableModel::startWatchingSource()
{
    qCDebug(texttomodelMergerDebug) << Q_FUNC_INFO << "Load file: " << source();

    const QStringList oldWatchingFiles = m_fileWatcher->files();
    if (oldWatchingFiles.size())
        m_fileWatcher->removePaths(oldWatchingFiles);

    QString localPath = ::urlToLocalPath(source());
    if (QFileInfo(localPath).isFile())
        m_fileWatcher->addPath(localPath);
}