IPC.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef IPC_H
  2. #define IPC_H
  3. #include <QMap>
  4. #include <QObject>
  5. #include <QSharedMemory>
  6. #include <QTimer>
  7. #include <ctime>
  8. #include <functional>
  9. using IPCEventHandler = std::function<bool(const QByteArray&)>;
  10. #define IPC_PROTOCOL_VERSION "1"
  11. class IPC : public QObject
  12. {
  13. Q_OBJECT
  14. protected:
  15. static const int EVENT_TIMER_MS = 1000;
  16. static const int EVENT_GC_TIMEOUT = 5;
  17. static const int EVENT_QUEUE_SIZE = 32;
  18. static const int OWNERSHIP_TIMEOUT_S = 5;
  19. public:
  20. IPC(uint32_t profileId);
  21. ~IPC();
  22. struct IPCEvent
  23. {
  24. uint32_t dest;
  25. int32_t sender;
  26. char name[16];
  27. char data[128];
  28. time_t posted;
  29. time_t processed;
  30. uint32_t flags;
  31. bool accepted;
  32. bool global;
  33. };
  34. struct IPCMemory
  35. {
  36. uint64_t globalId;
  37. time_t lastEvent;
  38. time_t lastProcessed;
  39. IPCEvent events[IPC::EVENT_QUEUE_SIZE];
  40. };
  41. time_t postEvent(const QString& name, const QByteArray& data = QByteArray(), uint32_t dest = 0);
  42. bool isCurrentOwner();
  43. void registerEventHandler(const QString& name, IPCEventHandler handler);
  44. bool isEventAccepted(time_t time);
  45. bool waitUntilAccepted(time_t time, int32_t timeout = -1);
  46. bool isAttached() const;
  47. public slots:
  48. void setProfileId(uint32_t profileId);
  49. private:
  50. IPCMemory* global();
  51. bool runEventHandler(IPCEventHandler handler, const QByteArray& arg);
  52. IPCEvent* fetchEvent();
  53. void processEvents();
  54. bool isCurrentOwnerNoLock();
  55. private:
  56. QTimer timer;
  57. uint64_t globalId;
  58. uint32_t profileId;
  59. QSharedMemory globalMemory;
  60. QMap<QString, IPCEventHandler> eventHandlers;
  61. };
  62. #endif // IPC_H