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