summaryrefslogtreecommitdiff
path: root/jsonobjectfilesingleton.h
blob: f11b30a38fbd05070bca180a68490dfd226272ef (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
#pragma once

// qt
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileSystemWatcher>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMutex>
#include <QSharedPointer>
#include <QStandardPaths>
#include <QVariant>

#define JSON_OBJECT_FILE(classname) JsonObjectFile<classname>::get().data()

template <class T> class JsonObjectFile
{
public:
    static QSharedPointer<T> get()
    {
        static QMutex mtx;
        QMutexLocker l(&mtx);

        if (!m_instance)
        {
            m_instance = read();

            qDebug() << "add filepath" << filepath();
            if (!m_watcher.addPath(filepath()))
            {
                qt_noop();
            }
            qDebug() << m_watcher.directories() << m_watcher.files();

            QObject::connect(
                &m_watcher,
                &QFileSystemWatcher::directoryChanged,
                &m_watcher,
                [&](const QString& path) {
                    qDebug() << filepath() << "changed";
                    if (path == filename())
                    {
                        qDebug() << "file changed:" << filename();
                        *get() = *read();
                    }
                },
                Qt::DirectConnection
            );
        }

        return m_instance;
    }

    static QSharedPointer<T> read(const QString fileName = QString())
    {
        static QMutex mtx;
        QMutexLocker l(&mtx);

        if (!QDir(filepath()).exists())
        {
            QDir().mkpath(filepath());
        }

        QFile f(!fileName.isEmpty() ? fileName : filename());

        if (!f.open(QFile::ReadOnly))
        {
            qDebug() << Q_FUNC_INFO << ":"
                     << "cannot open file" << f.fileName() << ":\n"
                     << f.errorString();

            return QSharedPointer<T>();
        }

        auto data = f.readAll();
        QJsonValue json = QJsonDocument::fromJson(data).object();
        return QSharedPointer<T>(
            new T(json[T::staticMetaObject.className()]),
            &T::deleteLater
        );
    }

    static bool write(
        const QSharedPointer<T>& value,
        const QString fileName = QString()
    )
    {
        static QMutex mtx;
        QMutexLocker l(&mtx);

        QFile f(!fileName.isEmpty() ? fileName : filename());

        if (!QDir(filepath()).exists())
        {
            QDir().mkpath(filepath());
        }

        //        bool fileExists = f.exists();

        if (!f.open(QFile::WriteOnly))
        {
            qDebug() << Q_FUNC_INFO << ":"
                     << "cannot open file" << f.fileName() << ":\n"
                     << f.errorString();

            return false;
        }

        const auto json =
            QJsonObject{{T::staticMetaObject.className(), *value}};

        f.write(QJsonDocument(json).toJson());
        f.flush();

        m_instance = read();

        return true;
    }

    static bool remove(const QString fileName = QString())
    {
        static QMutex mtx;
        QMutexLocker l(&mtx);

        QFile f(!fileName.isEmpty() ? fileName : filename());

        if (!f.remove())
        {
            qDebug() << Q_FUNC_INFO << ":"
                     << "cannot delete file" << f.fileName() << ":\n"
                     << f.errorString();

            return false;
        }

        return true;
    }

    static QString filepath()
    {
        return QStandardPaths::writableLocation(
            QStandardPaths::AppConfigLocation
        );
    }

    static QString filename()
    {
        return filepath() + QDir::separator() +
               T::staticMetaObject.className() + "." + extension;
    }

    typedef QSharedPointer<T> FactorySharedPointer;

public:
    static const QString extension;

private:
    static FactorySharedPointer m_instance;
    static QFileSystemWatcher m_watcher;
};

template <typename T>
QString const JsonObjectFile<T>::extension = QStringLiteral("json");

template <class T>
typename JsonObjectFile<T>::FactorySharedPointer JsonObjectFile<T>::m_instance;

template <class T> QFileSystemWatcher JsonObjectFile<T>::m_watcher;