UniqueApplication.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // Created by Tobias Hieta on 27/08/15.
  3. //
  4. #ifndef KONVERGO_UNIQUEAPPLICATION_H
  5. #define KONVERGO_UNIQUEAPPLICATION_H
  6. #include <QObject>
  7. #include "Paths.h"
  8. #include "LocalJsonServer.h"
  9. #include "LocalJsonClient.h"
  10. #include "utils/Utils.h"
  11. #define SOCKET_NAME "pmpUniqueApplication"
  12. class UniqueApplication : public QObject
  13. {
  14. Q_OBJECT
  15. public:
  16. explicit UniqueApplication(QObject* parent = nullptr, const QString& socketname = SOCKET_NAME) : QObject(parent)
  17. {
  18. m_socketName = socketname;
  19. }
  20. void listen()
  21. {
  22. m_server = new LocalJsonServer(m_socketName, this);
  23. connect(m_server, &LocalJsonServer::messageReceived, [=](const QVariant& message)
  24. {
  25. QVariantMap map = message.toMap();
  26. if (map.contains("command") && map.value("command").toString() == "appStart")
  27. emit otherApplicationStarted();
  28. });
  29. if (!m_server->listen())
  30. throw FatalException("Failed to listen to uniqueApp socket: " + m_server->errorString());
  31. }
  32. bool ensureUnique()
  33. {
  34. auto socket = new LocalJsonClient(m_socketName, this);
  35. socket->connectToServer();
  36. // we will just assume that the app isn't running if we get a error here
  37. if (!socket->waitForConnected(1000))
  38. {
  39. if (socket->error() != QLocalSocket::SocketTimeoutError)
  40. {
  41. // since we are unique we will start to listen and claim this socket.
  42. listen();
  43. return true;
  44. }
  45. }
  46. QVariantMap m;
  47. m.insert("command", "appStart");
  48. socket->sendMessage(m);
  49. socket->waitForBytesWritten(2000);
  50. socket->close();
  51. socket->deleteLater();
  52. return false;
  53. }
  54. Q_SIGNAL void otherApplicationStarted();
  55. private:
  56. LocalJsonServer* m_server;
  57. QString m_socketName;
  58. };
  59. #endif //KONVERGO_UNIQUEAPPLICATION_H