aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/designercore/include/modelcache.h
blob: 39eae38890dcdd18b0c2a985b687c7d028f9e7c4 (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#pragma once

#include <qmldesignercorelib_global.h>

#include <model.h>

#include <utils/optional.h>

#include <QHash>
#include <QQueue>

namespace QmlDesigner {

template<class DataType>
class ModelCache
{
public:
    ModelCache(int max = 20)
        : m_maxEntries(max)
    {}

    void insert(Model *model, const DataType &data)
    {
        QObject::connect(model, &Model::destroyed, [this](QObject *o) {
            QObject *deletedModel = o;

            if (deletedModel) {
                m_content.remove(deletedModel);
                m_queue.removeAll(deletedModel);
            }
        });

        m_content.insert(model, data);
        if (!m_queue.contains(model))
            m_queue.append(model);
        if (m_queue.length() > m_maxEntries) {
            QObject *first = m_queue.takeFirst();
            m_content.remove(first);
        }
    }

    Utils::optional<DataType> take(Model *model)
    {
        if (!m_content.contains(model))
            return {};
        m_queue.removeOne(model);
        return m_content.take(model);
    }

private:
    QHash<QObject *, DataType> m_content;
    QQueue<QObject *> m_queue;
    int m_maxEntries = 20;
};

} // namespace QmlDesigner