forked from psemiletov/tea-qt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_application_shared.cpp
97 lines (70 loc) · 2.17 KB
/
single_application_shared.cpp
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
// "single_application.cpp"
/*
taken from http://berenger.eu/blog/c-qt-singleapplication-single-app-instance/
code by Berenger Bramas
modified by Peter Semiletov
*/
#include <QTimer>
#include <QByteArray>
#include <QMessageBox>
#include "single_application_shared.h"
CSingleApplicationShared::CSingleApplicationShared (int &argc, char *argv[], const QString &uniqueKey): QApplication (argc, argv)
{
sharedMemory.setKey (uniqueKey);
// when can create it only if it doesn't exist
if (sharedMemory.create (8192))
{
sharedMemory.lock();
*(char*)sharedMemory.data() = '\0';
sharedMemory.unlock();
bAlreadyExists = false;
// start checking for messages of other instances.
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(checkForMessage()));
timer->start (200);
}
// it exits, so we can attach it?!
else
if (sharedMemory.attach())
bAlreadyExists = true;
}
// public slots
void CSingleApplicationShared::checkForMessage()
{
QStringList arguments;
sharedMemory.lock();
char *from = (char*)sharedMemory.data();
while (*from != '\0')
{
int sizeToRead = int(*from);
++from;
QByteArray byteArray = QByteArray (from, sizeToRead);
byteArray[sizeToRead] = '\0';
from += sizeToRead;
arguments << QString::fromUtf8 (byteArray.constData());
}
*(char*)sharedMemory.data() = '\0';
sharedMemory.unlock();
if (arguments.size()) emit messageAvailable (arguments);
}
bool CSingleApplicationShared::sendMessage (const QString &message)
{
//we cannot send message if we are master process!
if (isMasterApp())
return false;
QByteArray byteArray;
byteArray.append (char(message.size()));
byteArray.append (message.toUtf8());
byteArray.append ('\0');
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
while (*to != '\0')
{
int sizeToRead = int(*to);
to += sizeToRead + 1;
}
const char *from = byteArray.data();
memcpy (to, from, qMin(sharedMemory.size(), byteArray.size()));
sharedMemory.unlock();
return true;
}