]> SALOME platform Git repositories - modules/gui.git/blob - src/HelpBrowser/qtlocalpeer.cpp
Salome HOME
Remove QT4 compatibility.
[modules/gui.git] / src / HelpBrowser / qtlocalpeer.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the Qt Solutions component.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 **   * Redistributions of source code must retain the above copyright
15 **     notice, this list of conditions and the following disclaimer.
16 **   * Redistributions in binary form must reproduce the above copyright
17 **     notice, this list of conditions and the following disclaimer in
18 **     the documentation and/or other materials provided with the
19 **     distribution.
20 **   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
21 **     of its contributors may be used to endorse or promote products derived
22 **     from this software without specific prior written permission.
23 **
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41
42 #include "qtlocalpeer.h"
43 #include <QCoreApplication>
44 #include <QTime>
45 #include <QDataStream>
46
47 #if defined(Q_OS_WIN)
48 #include <QLibrary>
49 #include <qt_windows.h>
50 typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
51 static PProcessIdToSessionId pProcessIdToSessionId = 0;
52 #endif
53 #if defined(Q_OS_UNIX)
54 #include <sys/types.h>
55 #include <time.h>
56 #include <unistd.h>
57 #endif
58
59 namespace QtLP_Private {
60 #include "qtlockedfile.cpp"
61 #if defined(Q_OS_WIN)
62 #include "qtlockedfile_win.cpp"
63 #else
64 #include "qtlockedfile_unix.cpp"
65 #endif
66 }
67
68 const char* QtLocalPeer::ack = "ack";
69
70 QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
71     : QObject(parent), id(appId)
72 {
73     QString prefix = id;
74     if (id.isEmpty()) {
75         id = QCoreApplication::applicationFilePath();
76 #if defined(Q_OS_WIN)
77         id = id.toLower();
78 #endif
79         prefix = id.section(QLatin1Char('/'), -1);
80     }
81     prefix.remove(QRegExp("[^a-zA-Z]"));
82     prefix.truncate(6);
83
84     QByteArray idc = id.toUtf8();
85     quint16 idNum = qChecksum(idc.constData(), idc.size());
86     socketName = QLatin1String("qtsingleapp-") + prefix
87                  + QLatin1Char('-') + QString::number(idNum, 16);
88
89 #if defined(Q_OS_WIN)
90     if (!pProcessIdToSessionId) {
91         QLibrary lib("kernel32");
92         pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
93     }
94     if (pProcessIdToSessionId) {
95         DWORD sessionId = 0;
96         pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
97         socketName += QLatin1Char('-') + QString::number(sessionId, 16);
98     }
99 #else
100     socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
101 #endif
102
103     server = new QLocalServer(this);
104     QString lockName = QDir(QDir::tempPath()).absolutePath()
105                        + QLatin1Char('/') + socketName
106                        + QLatin1String("-lockfile");
107     lockFile.setFileName(lockName);
108     lockFile.open(QIODevice::ReadWrite);
109 }
110
111
112
113 bool QtLocalPeer::isClient()
114 {
115     if (lockFile.isLocked())
116         return false;
117
118     if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
119         return true;
120
121     bool res = server->listen(socketName);
122     if (!res)
123         qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
124     QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
125     return false;
126 }
127
128
129 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
130 {
131     if (!isClient())
132         return false;
133
134     QLocalSocket socket;
135     bool connOk = false;
136     for(int i = 0; i < 2; i++) {
137         // Try twice, in case the other instance is just starting up
138         socket.connectToServer(socketName);
139         connOk = socket.waitForConnected(timeout/2);
140         if (connOk || i)
141             break;
142         int ms = 250;
143 #if defined(Q_OS_WIN)
144         Sleep(DWORD(ms));
145 #else
146         struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
147         nanosleep(&ts, NULL);
148 #endif
149     }
150     if (!connOk)
151         return false;
152
153     QByteArray uMsg(message.toUtf8());
154     QDataStream ds(&socket);
155     ds.writeBytes(uMsg.constData(), uMsg.size());
156     bool res = socket.waitForBytesWritten(timeout);
157     if (res) {
158         res &= socket.waitForReadyRead(timeout);   // wait for ack
159         if (res)
160             res &= (socket.read(qstrlen(ack)) == ack);
161     }
162     return res;
163 }
164
165
166 void QtLocalPeer::receiveConnection()
167 {
168     QLocalSocket* socket = server->nextPendingConnection();
169     if (!socket)
170         return;
171
172     while (socket->bytesAvailable() < (int)sizeof(quint32))
173         socket->waitForReadyRead();
174     QDataStream ds(socket);
175     QByteArray uMsg;
176     quint32 remaining;
177     ds >> remaining;
178     uMsg.resize(remaining);
179     int got = 0;
180     char* uMsgBuf = uMsg.data();
181     do {
182         got = ds.readRawData(uMsgBuf, remaining);
183         remaining -= got;
184         uMsgBuf += got;
185     } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
186     if (got < 0) {
187         qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
188         delete socket;
189         return;
190     }
191     QString message(QString::fromUtf8(uMsg));
192     socket->write(ack, qstrlen(ack));
193     socket->waitForBytesWritten(1000);
194     socket->waitForDisconnected(1000); // make sure client reads ack
195     delete socket;
196     emit messageReceived(message); //### (might take a long time to return)
197 }