singleinstanceguard.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #ifndef SINGLEINSTANCEGUARD_H
  2. #define SINGLEINSTANCEGUARD_H
  3. #include <QObject>
  4. #include <QString>
  5. #include <QSharedPointer>
  6. class QLocalServer;
  7. class QLocalSocket;
  8. namespace vnotex
  9. {
  10. class SingleInstanceGuard : public QObject
  11. {
  12. Q_OBJECT
  13. public:
  14. SingleInstanceGuard();
  15. ~SingleInstanceGuard();
  16. // Try to run. Return true on success.
  17. bool tryRun();
  18. // Server API.
  19. public:
  20. // A running instance requests to exit.
  21. void exit();
  22. // Clients API.
  23. public:
  24. void requestOpenFiles(const QStringList &p_files);
  25. void requestShow();
  26. signals:
  27. void openFilesRequested(const QStringList &p_files);
  28. void showRequested();
  29. private:
  30. enum OpCode
  31. {
  32. Null = 0,
  33. Show,
  34. OpenFiles
  35. };
  36. struct Command
  37. {
  38. void clear()
  39. {
  40. m_opCode = OpCode::Null;
  41. m_size = 0;
  42. }
  43. OpCode m_opCode = OpCode::Null;
  44. int m_size = 0;
  45. };
  46. QSharedPointer<QLocalSocket> tryConnect();
  47. QSharedPointer<QLocalServer> tryListen();
  48. void setupServer();
  49. void receiveCommand(QLocalSocket *p_socket);
  50. void sendRequest(QLocalSocket *p_socket, OpCode p_code, const QString &p_payload);
  51. // Whether succeeded to run.
  52. bool m_online = false;
  53. QSharedPointer<QLocalSocket> m_client;
  54. QSharedPointer<QLocalServer> m_server;
  55. bool m_ongoingConnect = false;
  56. Command m_command;
  57. static const QString c_serverName;
  58. static const QChar c_stringListSeparator;
  59. };
  60. } // ns vnotex
  61. #endif // SINGLEINSTANCEGUARD_H