aboutsummaryrefslogtreecommitdiffstats
path: root/src/shared/qtsingleapplication/qtsingleapplication.cpp
blob: 0f8fa8b6d13a047da0d650e7f199f17cfe25a800 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qtsingleapplication.h"
#include "qtlocalpeer.h"

#include <qtlockedfile.h>

#include <QDir>
#include <QFileOpenEvent>
#include <QSharedMemory>
#include <QWidget>

namespace SharedTools {

static const int instancesSize = 1024;

static QString instancesLockFilename(const QString &appSessionId)
{
    const QChar slash(QLatin1Char('/'));
    QString res = QDir::tempPath();
    if (!res.endsWith(slash))
        res += slash;
    return res + appSessionId + QLatin1String("-instances");
}

QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv)
    : QApplication(argc, argv),
      firstPeer(-1),
      pidPeer(0)
{
    this->appId = appId;

    const QString appSessionId = QtLocalPeer::appSessionId(appId);

    // This shared memory holds a zero-terminated array of active (or crashed) instances
    instances = new QSharedMemory(appSessionId, this);
    actWin = 0;
    block = false;

    // First instance creates the shared memory, later instances attach to it
    const bool created = instances->create(instancesSize);
    if (!created) {
        if (!instances->attach()) {
            qWarning() << "Failed to initialize instances shared memory: "
                       << instances->errorString();
            delete instances;
            instances = 0;
            return;
        }
    }

    // QtLockedFile is used to workaround QTBUG-10364
    QtLockedFile lockfile(instancesLockFilename(appSessionId));

    lockfile.open(QtLockedFile::ReadWrite);
    lockfile.lock(QtLockedFile::WriteLock);
    qint64 *pids = static_cast<qint64 *>(instances->data());
    if (!created) {
        // Find the first instance that it still running
        // The whole list needs to be iterated in order to append to it
        for (; *pids; ++pids) {
            if (firstPeer == -1 && isRunning(*pids))
                firstPeer = *pids;
        }
    }
    // Add current pid to list and terminate it
    *pids++ = QCoreApplication::applicationPid();
    *pids = 0;
    pidPeer = new QtLocalPeer(this, appId + QLatin1Char('-') +
                              QString::number(QCoreApplication::applicationPid()));
    connect(pidPeer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived);
    pidPeer->isClient();
    lockfile.unlock();
}

QtSingleApplication::~QtSingleApplication()
{
    if (!instances)
        return;
    const qint64 appPid = QCoreApplication::applicationPid();
    QtLockedFile lockfile(instancesLockFilename(QtLocalPeer::appSessionId(appId)));
    lockfile.open(QtLockedFile::ReadWrite);
    lockfile.lock(QtLockedFile::WriteLock);
    // Rewrite array, removing current pid and previously crashed ones
    qint64 *pids = static_cast<qint64 *>(instances->data());
    qint64 *newpids = pids;
    for (; *pids; ++pids) {
        if (*pids != appPid && isRunning(*pids))
            *newpids++ = *pids;
    }
    *newpids = 0;
    lockfile.unlock();
}

bool QtSingleApplication::event(QEvent *event)
{
    if (event->type() == QEvent::FileOpen) {
        QFileOpenEvent *foe = static_cast<QFileOpenEvent*>(event);
        emit fileOpenRequest(foe->file());
        return true;
    }
    return QApplication::event(event);
}

bool QtSingleApplication::isRunning(qint64 pid)
{
    if (pid == -1) {
        pid = firstPeer;
        if (pid == -1)
            return false;
    }

    QtLocalPeer peer(this, appId + QLatin1Char('-') + QString::number(pid, 10));
    return peer.isClient();
}

bool QtSingleApplication::sendMessage(const QString &message, int timeout, qint64 pid)
{
    if (pid == -1) {
        pid = firstPeer;
        if (pid == -1)
            return false;
    }

    QtLocalPeer peer(this, appId + QLatin1Char('-') + QString::number(pid, 10));
    return peer.sendMessage(message, timeout, block);
}

QString QtSingleApplication::applicationId() const
{
    return appId;
}

void QtSingleApplication::setBlock(bool value)
{
    block = value;
}

void QtSingleApplication::setActivationWindow(QWidget *aw, bool activateOnMessage)
{
    actWin = aw;
    if (!pidPeer)
        return;
    if (activateOnMessage)
        connect(pidPeer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow);
    else
        disconnect(pidPeer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow);
}

QWidget* QtSingleApplication::activationWindow() const
{
    return actWin;
}

void QtSingleApplication::activateWindow()
{
    if (actWin) {
        actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized);
        actWin->raise();
        actWin->activateWindow();
    }
}

static const char s_freezeDetector[] = "QTC_FREEZE_DETECTOR";

static std::optional<int> isUsingFreezeDetector()
{
    if (!qEnvironmentVariableIsSet(s_freezeDetector))
        return {};

    bool ok = false;
    const int threshold = qEnvironmentVariableIntValue(s_freezeDetector, &ok);
    return ok ? threshold : 100; // default value 100ms
}

class ApplicationWithFreezerDetector : public SharedTools::QtSingleApplication
{
public:
    ApplicationWithFreezerDetector(const QString &id, int &argc, char **argv)
        : QtSingleApplication(id, argc, argv)
        , m_align(21, QChar::Space)
    {}
    void setFreezeTreshold(std::chrono::milliseconds freezeAbove) { m_threshold = freezeAbove; }

    bool notify(QObject *receiver, QEvent *event) override {
        using namespace std::chrono;
        const auto start = system_clock::now();
        const QPointer<QObject> p(receiver);
        const QString className = QLatin1String(receiver->metaObject()->className());
        const QString name = receiver->objectName();

        const bool ret = QtSingleApplication::notify(receiver, event);

        const auto end = system_clock::now();
        const auto freeze = duration_cast<milliseconds>(end - start);
        if (freeze > m_threshold) {
            const QString time = QTime::currentTime().toString(Qt::ISODateWithMs);
            qDebug().noquote() << QString("FREEZE [%1]").arg(time)
                               << "of" << freeze.count() << "ms, on:" << event;
            const QString receiverMessage = name.isEmpty()
                ? QString("receiver class: %1").arg(className)
                : QString("receiver class: %1, object name: %2").arg(className, name);
            qDebug().noquote() << m_align << receiverMessage;
            if (!p)
                qDebug().noquote() << m_align << "THE RECEIVER GOT DELETED inside the event filter!";
        }
        return ret;
    }

private:
    const QString m_align;
    std::chrono::milliseconds m_threshold = std::chrono::milliseconds(100);
};

QtSingleApplication *createApplication(const QString &id, int &argc, char **argv)
{
    const std::optional<int> freezeDetector = isUsingFreezeDetector();
    if (!freezeDetector)
        return new SharedTools::QtSingleApplication(id, argc, argv);

    qDebug() << s_freezeDetector << "evn var is set. The freezes of main thread, above"
             << *freezeDetector << "ms, will be reported.";
    qDebug() << "Change the freeze detection threshold by setting the" << s_freezeDetector
             << "env var to a different numeric value (in ms).";
    ApplicationWithFreezerDetector *app = new ApplicationWithFreezerDetector(id, argc, argv);
    app->setFreezeTreshold(std::chrono::milliseconds(*freezeDetector));
    return app;
}

} // namespace SharedTools