| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "miscellaneous/singleapplication.h" |
| 4 | |
| 5 | #include <QDataStream> |
| 6 | #include <QLocalServer> |
| 7 | #include <QLocalSocket> |
| 8 | |
| 9 | SingleApplication::SingleApplication(const QString& id, int& argc, char** argv) |
| 10 | : QApplication(argc, argv), m_id(id), m_server(new QLocalServer(this)) {} |
| 11 | |
| 12 | SingleApplication::~SingleApplication() { |
| 13 | finish(); |
| 14 | } |
| 15 | |
| 16 | void SingleApplication::finish() { |
| 17 | if (m_server->isListening()) { |
| 18 | m_server->close(); |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | bool SingleApplication::isOtherInstanceRunning(const QString& message) { |
| 23 | QLocalSocket sck; |
| 24 | |
| 25 | sck.connectToServer(m_id); |
| 26 | |
| 27 | if (sck.waitForConnected(200)) { |
| 28 | if (!message.isEmpty()) { |
| 29 | QDataStream out(&sck); |
| 30 | |
| 31 | out.setVersion(QDataStream::Version::Qt_5_5); |
| 32 | |
| 33 | out << quint32(message.size()); |
| 34 | out << message; |
| 35 | |
| 36 | sck.flush(); |
| 37 | sck.waitForBytesWritten(200); |
| 38 | } |
| 39 | |
| 40 | sck.disconnectFromServer(); |
| 41 | sck.abort(); |
| 42 | return true; |
| 43 | } |
| 44 | |
| 45 | QLocalServer::removeServer(m_id); |
| 46 | auto i_am_first = m_server->listen(m_id); |
| 47 | |
| 48 | if (i_am_first) { |
| 49 | connect(m_server, &QLocalServer::newConnection, this, &SingleApplication::processMessageFromOtherInstance); |
| 50 | } |
| 51 | |
| 52 | return !i_am_first; |
| 53 | } |
| 54 | |
| 55 | bool SingleApplication::sendMessage(const QString& message) { |
| 56 | return isOtherInstanceRunning(message); |
| 57 | } |
| 58 | |
| 59 | void SingleApplication::processMessageFromOtherInstance() { |
| 60 | auto* sck = m_server->nextPendingConnection(); |
| 61 | |
| 62 | if (sck == nullptr) { |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | quint32 block_size = 0; |
| 67 | QEventLoop loop; |
| 68 | QDataStream in(sck); |
| 69 | |
| 70 | in.setVersion(QDataStream::Version::Qt_5_5); |
| 71 | |
| 72 | connect(sck, &QLocalSocket::disconnected, sck, &QLocalSocket::deleteLater); |
| 73 | connect(sck, &QLocalSocket::readyRead, this, [this, sck, &loop, &in, &block_size]() { |
| 74 | if (block_size == 0) { |
| 75 | if (sck->bytesAvailable() < int(sizeof(quint32))) { |
| 76 | return; |
| 77 | } |
| 78 | |
| 79 | in >> block_size; |
| 80 | } |
| 81 | |
| 82 | if (sck->bytesAvailable() < block_size || in.atEnd()) { |
| 83 | return; |
| 84 | } |
| 85 | |
| 86 | QString dat; |
| 87 | in >> dat; |
| 88 | |
| 89 | emit messageReceived(dat); |
| 90 | loop.exit(); |
| 91 | }); |
| 92 | |
| 93 | sck->flush(); |
| 94 | loop.exec(); |
| 95 | } |