summaryrefslogtreecommitdiffstats
path: root/common/modelresult.cpp
blob: 57f5ce8480f19fbad1e2d24b48d2a7d08bc5a9fd (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
 * Copyright (C) 2014 Christian Mollekopf <chrigi_1@fastmail.fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "modelresult.h"

#include <QDebug>
#include <QThread>
#include <QPointer>

#include "log.h"
#include "notifier.h"
#include "notification.h"

using namespace Sink;

static uint getInternalIdentifer(const QByteArray &resourceId, const QByteArray &entityId)
{
    return qHash(resourceId + entityId);
}

static uint qHash(const Sink::ApplicationDomain::ApplicationDomainType &type)
{
    Q_ASSERT(!type.identifier().isEmpty());
    return getInternalIdentifer(type.resourceInstanceIdentifier(), type.identifier());
}

static qint64 getIdentifier(const QModelIndex &idx)
{
    if (!idx.isValid()) {
        return 0;
    }
    return idx.internalId();
}

template <class T, class Ptr>
ModelResult<T, Ptr>::ModelResult(const Sink::Query &query, const QList<QByteArray> &propertyColumns, const Sink::Log::Context &ctx)
    : QAbstractItemModel(), mLogCtx(ctx.subContext("modelresult")), mPropertyColumns(propertyColumns), mQuery(query)
{
    if (query.flags().testFlag(Sink::Query::UpdateStatus)) {
        Sink::Query resourceQuery;
        resourceQuery.setFilter(query.getResourceFilter());
        mNotifier.reset(new Sink::Notifier{resourceQuery});
        mNotifier->registerHandler([this](const Notification &notification) {
            switch (notification.type) {
                case Notification::Status:
                case Notification::Warning:
                case Notification::Error:
                case Notification::Info:
                case Notification::Progress:
                    //These are the notifications we care about
                    break;
                default:
                    //We're not interested
                    return;
            };
            if (notification.resource.isEmpty() || notification.entities.isEmpty()) {
                return;
            }

            QVector<qint64> idList;
            for (const auto &entity : notification.entities) {
                auto id = getInternalIdentifer(notification.resource, entity);
                if (mEntities.contains(id)) {
                    idList << id;
                }
            }

            if (idList.isEmpty()) {
                //We don't have this entity in our model
                return;
            }
            const int newStatus = [&] {
                if (notification.type == Notification::Warning || notification.type == Notification::Error) {
                    return ApplicationDomain::SyncStatus::SyncError;
                }
                if (notification.type == Notification::Info) {
                    switch (notification.code) {
                        case ApplicationDomain::SyncInProgress:
                            return ApplicationDomain::SyncInProgress;
                        case ApplicationDomain::SyncSuccess:
                            return ApplicationDomain::SyncSuccess;
                        case ApplicationDomain::SyncError:
                            return ApplicationDomain::SyncError;
                        case ApplicationDomain::NoSyncStatus:
                            break;
                    }
                    return ApplicationDomain::NoSyncStatus;
                }
                if (notification.type == Notification::Progress) {
                    return ApplicationDomain::SyncStatus::SyncInProgress;
                }
                return ApplicationDomain::NoSyncStatus;
            }();

            for (const auto id : idList) {
                const auto oldStatus = mEntityStatus.value(id);
                QVector<int> changedRoles;
                if (oldStatus != newStatus) {
                    SinkTraceCtx(mLogCtx) << "Status changed for entity:" << newStatus << ", id: " << id;
                    mEntityStatus.insert(id, newStatus);
                    changedRoles << StatusRole;
                }

                if (notification.type == Notification::Progress) {
                    changedRoles << ProgressRole;
                } else if (notification.type == Notification::Warning || notification.type == Notification::Error) {
                    changedRoles << WarningRole;
                }

                if (!changedRoles.isEmpty()) {
                    const auto idx = createIndexFromId(id);
                    SinkTraceCtx(mLogCtx) << "Index changed:" << idx << changedRoles;
                    //We don't emit the changedRoles because the consuming model likely remaps the role anyways and would then need to translate dataChanged signals as well.
                    emit dataChanged(idx, idx);
                }
            }
        });
    }
}

template <class T, class Ptr>
ModelResult<T, Ptr>::~ModelResult()
{
    if (mEmitter) {
        mEmitter->waitForMethodExecutionEnd();
    }
}

template <class T, class Ptr>
qint64 ModelResult<T, Ptr>::parentId(const Ptr &value)
{
    if (!mQuery.parentProperty().isEmpty()) {
        const auto identifier = value->getProperty(mQuery.parentProperty()).toByteArray();
        if (!identifier.isEmpty()) {
            return getInternalIdentifer(value->resourceInstanceIdentifier(), identifier);
        }
    }
    return 0;
}

template <class T, class Ptr>
int ModelResult<T, Ptr>::rowCount(const QModelIndex &parent) const
{
    Q_ASSERT(QThread::currentThread() == this->thread());
    return mTree[getIdentifier(parent)].size();
}

template <class T, class Ptr>
int ModelResult<T, Ptr>::columnCount(const QModelIndex &parent) const
{
    Q_ASSERT(QThread::currentThread() == this->thread());
    return mPropertyColumns.size();
}

template <class T, class Ptr>
QVariant ModelResult<T, Ptr>::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole) {
        if (section < mPropertyColumns.size()) {
            return mPropertyColumns.at(section);
        }
    }
    return QVariant();
}

template <class T, class Ptr>
QVariant ModelResult<T, Ptr>::data(const QModelIndex &index, int role) const
{
    Q_ASSERT(QThread::currentThread() == this->thread());
    if (role == DomainObjectRole && index.isValid()) {
        Q_ASSERT(mEntities.contains(index.internalId()));
        return QVariant::fromValue(mEntities.value(index.internalId()));
    }
    if (role == DomainObjectBaseRole && index.isValid()) {
        Q_ASSERT(mEntities.contains(index.internalId()));
        return QVariant::fromValue(mEntities.value(index.internalId()).template staticCast<Sink::ApplicationDomain::ApplicationDomainType>());
    }
    if (role == ChildrenFetchedRole) {
        return childrenFetched(index);
    }
    if (role == StatusRole) {
        auto it = mEntityStatus.constFind(index.internalId());
        if (it != mEntityStatus.constEnd()) {
            return *it;
        }
        return {};
    }
    if (role == Qt::DisplayRole && index.isValid()) {
        if (index.column() < mPropertyColumns.size()) {
            Q_ASSERT(mEntities.contains(index.internalId()));
            auto entity = mEntities.value(index.internalId());
            return entity->getProperty(mPropertyColumns.at(index.column())).toString();
        } else {
            return "No data available";
        }
    }
    return QVariant();
}

template <class T, class Ptr>
QModelIndex ModelResult<T, Ptr>::index(int row, int column, const QModelIndex &parent) const
{
    Q_ASSERT(QThread::currentThread() == this->thread());
    const auto id = getIdentifier(parent);
    const auto list = mTree.value(id);
    if (list.size() > row) {
        const auto childId = list.at(row);
        return createIndex(row, column, childId);
    }
    SinkWarningCtx(mLogCtx) << "Index not available " << row << column << parent;
    return QModelIndex();
}

template <class T, class Ptr>
QModelIndex ModelResult<T, Ptr>::createIndexFromId(const qint64 &id) const
{
    Q_ASSERT(QThread::currentThread() == this->thread());
    if (id == 0) {
        return QModelIndex();
    }
    auto grandParentId = mParents.value(id, 0);
    auto row = mTree.value(grandParentId).indexOf(id);
    Q_ASSERT(row >= 0);
    return createIndex(row, 0, id);
}

template <class T, class Ptr>
QModelIndex ModelResult<T, Ptr>::parent(const QModelIndex &index) const
{
    auto id = getIdentifier(index);
    auto parentId = mParents.value(id);
    return createIndexFromId(parentId);
}

template <class T, class Ptr>
bool ModelResult<T, Ptr>::hasChildren(const QModelIndex &parent) const
{
    if (mQuery.parentProperty().isEmpty() && parent.isValid()) {
        return false;
    }
    return QAbstractItemModel::hasChildren(parent);
}

template <class T, class Ptr>
bool ModelResult<T, Ptr>::canFetchMore(const QModelIndex &parent) const
{
    //We fetch trees immediately so can never fetch more
    if (parent.isValid() || mFetchedAll) {
        return false;
    }
    return true;
}

template <class T, class Ptr>
void ModelResult<T, Ptr>::fetchMore(const QModelIndex &parent)
{
    SinkTraceCtx(mLogCtx) << "Fetching more: " << parent;
    Q_ASSERT(QThread::currentThread() == this->thread());
    //We only suppor fetchMore for flat lists
    if (parent.isValid()) {
        return;
    }
    //There is already a fetch in progress, don't fetch again.
    if (mFetchInProgress) {
        SinkTraceCtx(mLogCtx) << "A fetch is already in progress.";
        return;
    }
    mFetchInProgress = true;
    mFetchComplete = false;
    SinkTraceCtx(mLogCtx) << "Fetching more.";
    if (loadEntities) {
        loadEntities();
    } else {
        SinkWarningCtx(mLogCtx) << "No way to fetch entities";
    }
}

template <class T, class Ptr>
bool ModelResult<T, Ptr>::allParentsAvailable(qint64 id) const
{
    auto p = id;
    while (p) {
        if (!mEntities.contains(p)) {
            return false;
        }
        p = mParents.value(p, 0);
    }
    return true;
}

template <class T, class Ptr>
void ModelResult<T, Ptr>::add(const Ptr &value)
{
    const auto childId = qHash(*value);
    const auto pId = parentId(value);
    if (mEntities.contains(childId)) {
        SinkWarningCtx(mLogCtx) << "Entity already in model: " << value->identifier();
        return;
    }
    const auto keys = mTree[pId];
    int idx = 0;
    for (; idx < keys.size(); idx++) {
        if (childId < keys.at(idx)) {
            break;
        }
    }
    bool parentIsVisible = allParentsAvailable(pId);
    // SinkTraceCtx(mLogCtx) << "Inserting rows " << index << parent;
    if (parentIsVisible) {
        auto parent = createIndexFromId(pId);
        beginInsertRows(parent, idx, idx);
    }
    mEntities.insert(childId, value);
    mTree[pId].insert(idx, childId);
    mParents.insert(childId, pId);
    if (parentIsVisible) {
        endInsertRows();
    }
    // SinkTraceCtx(mLogCtx) << "Inserted rows " << mTree[id].size();
}


template <class T, class Ptr>
void ModelResult<T, Ptr>::remove(const Ptr &value)
{
    auto childId = qHash(*value);
    if (!mEntities.contains(childId)) {
        return;
    }
    //The removed entity will have no properties, but we at least need the parent property.
    auto actualEntity = mEntities.value(childId);
    auto id = parentId(actualEntity);
    auto parent = createIndexFromId(id);
    SinkTraceCtx(mLogCtx) << "Removed entity" << childId;
    auto index = mTree[id].indexOf(childId);
    if (index >= 0) {
        beginRemoveRows(parent, index, index);
        mEntities.remove(childId);
        mTree[id].removeAll(childId);
        mParents.remove(childId);
        // TODO remove children
        endRemoveRows();
    }
}

template <class T, class Ptr>
void ModelResult<T, Ptr>::setFetcher(const std::function<void()> &fetcher)
{
    SinkTraceCtx(mLogCtx) << "Setting fetcher";
    loadEntities = fetcher;
}

template <class T, class Ptr>
void ModelResult<T, Ptr>::setEmitter(const typename Sink::ResultEmitter<Ptr>::Ptr &emitter)
{
    setFetcher([this]() { mEmitter->fetch(); });

    QPointer<QObject> guard(this);
    emitter->onAdded([this, guard](const Ptr &value) {
        SinkTraceCtx(mLogCtx) << "Received addition: " << value->identifier();
        Q_ASSERT(guard);
        threadBoundary.callInMainThread([this, value, guard]() {
            Q_ASSERT(guard);
            add(value);
        });
    });
    emitter->onModified([this, guard](const Ptr &value) {
        SinkTraceCtx(mLogCtx) << "Received modification: " << value->identifier();
        Q_ASSERT(guard);
        threadBoundary.callInMainThread([this, value]() {
            modify(value);
        });
    });
    emitter->onRemoved([this, guard](const Ptr &value) {
        SinkTraceCtx(mLogCtx) << "Received removal: " << value->identifier();
        Q_ASSERT(guard);
        threadBoundary.callInMainThread([this, value]() {
            remove(value);
        });
    });
    emitter->onInitialResultSetComplete([this, guard](bool fetchedAll) {
        SinkTraceCtx(mLogCtx) << "Initial result set complete. Fetched all: " << fetchedAll;
        Q_ASSERT(guard);
        Q_ASSERT(QThread::currentThread() == this->thread());
        mFetchInProgress = false;
        mFetchedAll = fetchedAll;
        mFetchComplete = true;
        emit dataChanged({}, {}, QVector<int>() << ChildrenFetchedRole);
    });
    mEmitter = emitter;
}

template <class T, class Ptr>
bool ModelResult<T, Ptr>::childrenFetched(const QModelIndex &index) const
{
    return mFetchComplete;
}

template <class T, class Ptr>
void ModelResult<T, Ptr>::modify(const Ptr &value)
{
    auto childId = qHash(*value);
    if (!mEntities.contains(childId)) {
        //Happens because the DatabaseQuery emits modifiations also if the item used to be filtered.
        SinkTraceCtx(mLogCtx) << "Tried to modify a value that is not yet part of the model";
        add(value);
        return;
    }
    auto id = parentId(value);
    auto parent = createIndexFromId(id);
    SinkTraceCtx(mLogCtx) << "Modified entity:" << value->identifier() << ", id: " << childId;
    auto i = mTree[id].indexOf(childId);
    Q_ASSERT(i >= 0);
    mEntities.remove(childId);
    mEntities.insert(childId, value);
    // TODO check for change of parents
    auto idx = index(i, 0, parent);
    emit dataChanged(idx, idx);
}

#define REGISTER_TYPE(T) \
    template class ModelResult<T, T::Ptr>; \

SINK_REGISTER_TYPES()