forked from notepadqq/notepadqq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleapplication.cpp
221 lines (185 loc) · 6.21 KB
/
singleapplication.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
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
#include "include/singleapplication.h"
#ifndef USE_DBUS
#include "include/localcommunication.h"
#include <QDataStream>
#include <QDir>
#include <QLocalSocket>
#include <QRegularExpression>
#endif
#if defined(Q_OS_WIN)
#include <QLibrary>
#include <qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif
#if defined(Q_OS_UNIX)
#include <unistd.h>
#endif
SingleApplication::SingleApplication(int &argc, char **argv) :
QApplication(argc, argv)
{
}
#ifdef USE_DBUS
#include <QtCore/QCoreApplication>
#include <QtDBus/QtDBus>
#define SERVICE_NAME "com.notepadqq.Notepadqq"
void SingleApplication::startServer()
{
if (!QDBusConnection::sessionBus().isConnected()) {
qDebug() << "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n";
Q_ASSERT(true);
}
if (!QDBusConnection::sessionBus().registerService(SERVICE_NAME)) {
qDebug() << qPrintable(QDBusConnection::sessionBus().lastError().message());
Q_ASSERT(true);
}
bool ok = QDBusConnection::sessionBus().registerObject("/", this, QDBusConnection::ExportScriptableSlots);
qDebug() << "Started and object registered: " << ok;
}
bool SingleApplication::attachToOtherInstance() {
QDBusInterface iface(SERVICE_NAME, "/", "", QDBusConnection::sessionBus());
if (!iface.isValid())
return false;
QDBusReply<void> reply = iface.call("receive", QDir::currentPath(), QApplication::arguments());
if (reply.isValid())
return true;
qDebug() << "Call to SingleApplication::receive() failed: " << reply.error().message();
return false;
}
void SingleApplication::receive(const QString& workingDirectory, const QStringList& arguments) {
if (arguments.isEmpty()) {
qWarning() << "Invalid DBus message with empty arguments parameter received.";
return;
}
emit receivedArguments(workingDirectory, arguments);
}
#else //ifdef USE_DBUS
/* ========= PROTOCOLS ===========
*
* |Ping:
*
* Client Server
* -- "NEW_CLIENT" -->
* <---- "HELLO" -----
* _______________________________
*
* |Passing arguments:
*
* Client Server
* ----- "ARGS" ----->
* <----- "OK" -------
* ---- ..data.. ----> where "data" is a list like
* [working_dir, arg0, ..., argn]
*/
QLocalSocket * SingleApplication::alreadyRunningInstance()
{
QLocalSocket *socket = new QLocalSocket(this);
socket->connectToServer(socketNameForUser());
if (socket->waitForConnected(2000))
{
LocalCommunication::send("NEW_CLIENT", socket);
QString reply = LocalCommunication::receive(socket);
if (reply == "HELLO") {
return socket;
}
}
return nullptr;
}
void SingleApplication::startServer()
{
if (m_localServer == nullptr) {
m_localServer = new QLocalServer(this);
connect(m_localServer, &QLocalServer::newConnection, this, &SingleApplication::newConnection);
QString socketName = socketNameForUser();
m_localServer->removeServer(socketName);
m_localServer->listen(socketName);
}
}
void SingleApplication::newConnection()
{
while (m_localServer->hasPendingConnections()) {
QLocalSocket *conn = m_localServer->nextPendingConnection();
connect(conn, &QLocalSocket::readyRead, this, [=]() {
QString message = LocalCommunication::receive(conn);
if (message == "NEW_CLIENT")
{
LocalCommunication::send("HELLO", conn);
}
else if (message == "ARGS")
{
LocalCommunication::send("OK", conn);
QByteArray ar = LocalCommunication::receiveRaw(conn);
QDataStream args(&ar, QIODevice::ReadOnly);
QStringList argList;
args >> argList;
if (!argList.isEmpty()) {
QString workingDir = argList.takeFirst();
emit receivedArguments(workingDir, argList);
}
}
});
}
}
QString SingleApplication::socketNameForUser()
{
QString id = "notepadqq";
QString prefix = id;
if (id.isEmpty()) {
id = QCoreApplication::applicationFilePath();
#if defined(Q_OS_WIN)
id = id.toLower();
#endif
prefix = id.section(QLatin1Char('/'), -1);
}
prefix.remove(QRegularExpression("[^a-zA-Z]"));
prefix.truncate(6);
QByteArray idc = id.toUtf8();
quint16 idNum = qChecksum(idc.constData(), idc.size());
QString socketName = QLatin1String("qtsingleapp-") + prefix
+ QLatin1Char('-') + QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId) {
QLibrary lib("kernel32");
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId) {
DWORD sessionId = 0;
pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
socketName += QLatin1Char('-') + QString::number(sessionId, 16);
}
#else
socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
return socketName;
}
bool SingleApplication::sendCommandLineArguments(QLocalSocket *socket)
{
LocalCommunication::send("ARGS", socket);
if (LocalCommunication::receive(socket) == "OK") {
QStringList data = QApplication::arguments();
data.prepend(QDir::currentPath());
QByteArray ar;
QDataStream args(&ar, QIODevice::WriteOnly);
args << data;
LocalCommunication::sendRaw(ar, socket);
// Ensure that all the bytes get written:
// after sendCommandLineArguments() returns, the
// application will probably exit.
return socket->waitForBytesWritten(5000);
}
return false;
}
bool SingleApplication::attachToOtherInstance()
{
// See if there are other instances open, and send them the arguments.
QLocalSocket *sck = alreadyRunningInstance();
if (sck != nullptr) {
bool ret = sendCommandLineArguments(sck);
sck->disconnectFromServer();
return ret;
}
return false;
}
#endif //ifdef USE_DBUS