QtPass 1.5.1
Multi-platform GUI for pass, the standard unix password manager.
Loading...
Searching...
No Matches
singleapplication.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
3#include "singleapplication.h"
4#include <QLocalSocket>
5#include <utility>
6#ifdef QT_DEBUG
7#include "debughelper.h"
8#endif
9
17SingleApplication::SingleApplication(int &argc, char *argv[], QString uniqueKey)
18 : QApplication(argc, argv), _uniqueKey(std::move(uniqueKey)) {
19 sharedMemory.setKey(_uniqueKey);
20 if (sharedMemory.attach()) {
21 _isRunning = true;
22 } else {
23 _isRunning = false;
24 // create shared memory.
25 if (!sharedMemory.create(1)) {
26#ifdef QT_DEBUG
27 dbg() << "Unable to create single instance.";
28#endif
29 return;
30 }
31 // create local server and listen to incomming messages from other
32 // instances.
33 localServer.reset(new QLocalServer(this));
34 connect(localServer.data(), &QLocalServer::newConnection, this,
36 localServer->listen(_uniqueKey);
37 }
38}
39
40// public slots.
41
47 QLocalSocket *localSocket = localServer->nextPendingConnection();
48 if (!localSocket->waitForReadyRead(timeout)) {
49#ifdef QT_DEBUG
50 dbg() << localSocket->errorString().toLatin1();
51#endif
52 return;
53 }
54 QByteArray byteArray = localSocket->readAll();
55 QString message = QString::fromUtf8(byteArray.constData());
56 emit messageAvailable(message);
57 localSocket->disconnectFromServer();
58}
59
60// public functions.
66auto SingleApplication::isRunning() -> bool { return _isRunning; }
67
74auto SingleApplication::sendMessage(const QString &message) -> bool {
75 if (!_isRunning) {
76 return false;
77 }
78 QLocalSocket localSocket(this);
79 localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
80 if (!localSocket.waitForConnected(timeout)) {
81#ifdef QT_DEBUG
82 dbg() << localSocket.errorString().toLatin1();
83#endif
84 return false;
85 }
86 QByteArray payload = message.toUtf8();
87 if (payload.isEmpty()) {
88 payload = QByteArray(1, '\0');
89 }
90 localSocket.write(payload);
91 if (!localSocket.waitForBytesWritten(timeout)) {
92#ifdef QT_DEBUG
93 dbg() << localSocket.errorString().toLatin1();
94#endif
95 return false;
96 }
97 localSocket.disconnectFromServer();
98 return true;
99}
void receiveMessage()
SingleApplication::receiveMessage we have received (a command line) message.
SingleApplication(int &argc, char *argv[], QString uniqueKey)
SingleApplication::SingleApplication this replaces the QApplication allowing for local socket based c...
auto isRunning() -> bool
SingleApplication::isRunning is there already a QtPass instance running, to check wether to be server...
void messageAvailable(const QString &message)
messageAvailable notification from commandline
auto sendMessage(const QString &message) -> bool
SingleApplication::sendMessage send a message (from commandline) to an already running QtPass instanc...
#define dbg()
Definition debughelper.h:9