summaryrefslogtreecommitdiff
path: root/plugin/src/Caelestia/Services/service.cpp
blob: bc919c965049ee6c07cf074aaa736698213e93f0 (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
#include "service.hpp"

#include <qdebug.h>
#include <qpointer.h>

namespace caelestia {

Service::Service(QObject* parent)
    : QObject(parent)
    , m_refCount(0) {}

int Service::refCount() const {
    QMutexLocker locker(&m_mutex);
    return m_refCount;
}

void Service::ref() {
    bool needsStart = false;

    {
        QMutexLocker locker(&m_mutex);
        if (m_refCount == 0) {
            needsStart = true;
        }
        m_refCount++;
    }
    emit refCountChanged();

    if (needsStart) {
        const QPointer<Service> self(this);
        QMetaObject::invokeMethod(
            this,
            [self]() {
                if (self) {
                    self->start();
                }
            },
            Qt::QueuedConnection);
    }
}

void Service::unref() {
    bool needsStop = false;

    {
        QMutexLocker locker(&m_mutex);
        if (m_refCount == 0) {
            return;
        }
        m_refCount--;
        if (m_refCount == 0) {
            needsStop = true;
        }
    }
    emit refCountChanged();

    if (needsStop) {
        const QPointer<Service> self(this);
        QMetaObject::invokeMethod(
            this,
            [self]() {
                if (self) {
                    self->stop();
                }
            },
            Qt::QueuedConnection);
    }
}

} // namespace caelestia