forked from psemiletov/tea-qt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_application.cpp
105 lines (77 loc) · 2.27 KB
/
single_application.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
98
99
100
101
102
103
104
// "single_application.cpp"
/*
* taken from http://www.qtcentre.org/wiki/index.php?title=SingleApplication
* LGPL'ed source code
* modified by Peter Semiletov
*
*/
#include <QLocalSocket>
#include <QDebug>
#include "single_application.h"
SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv), _uniqueKey(uniqueKey)
{
#ifndef Q_OS_OS2
qDebug() << "SingleApplication::SingleApplication";
sharedMemory.setKey(_uniqueKey);
if (sharedMemory.attach())
_isRunning = true;
else
{
_isRunning = false;
// create shared memory.
if (! sharedMemory.create(1))
{
qDebug() << "Unable to create single instance.";
return;
}
// create local server and listen to incomming messages from other instances.
localServer = new QLocalServer (this);
connect (localServer, SIGNAL(newConnection()), this, SLOT(receiveMessage()));
localServer->listen (_uniqueKey);
}
#endif
}
// public slots.
void SingleApplication::receiveMessage()
{
QLocalSocket *localSocket = localServer->nextPendingConnection();
if (localSocket == 0)
return;
if (! localSocket->waitForReadyRead (timeout))
{
qDebug() << localSocket->errorString();
return;
}
QByteArray byteArray = localSocket->readAll();
QString message = QString::fromUtf8(byteArray.constData());
emit messageAvailable(message);
localSocket->disconnectFromServer();
delete localSocket;
}
// public functions.
bool SingleApplication::isRunning()
{
return _isRunning;
}
bool SingleApplication::sendMessage(const QString &message)
{
if (! _isRunning)
return false;
if (message.isNull() || message.isEmpty())
return false;
QLocalSocket localSocket (this);
localSocket.connectToServer (_uniqueKey, QIODevice::WriteOnly);
if (! localSocket.waitForConnected (timeout))
{
qDebug() << localSocket.errorString();
return false;
}
localSocket.write (message.toUtf8());
if (! localSocket.waitForBytesWritten (timeout))
{
qDebug() << localSocket.errorString();
return false;
}
localSocket.disconnectFromServer();
return true;
}