single_instance.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #pragma once
  8. #include "base/file_lock.h"
  9. #include <QtNetwork/QLocalServer>
  10. #include <QtNetwork/QLocalSocket>
  11. namespace base {
  12. class SingleInstance final {
  13. public:
  14. struct Message {
  15. uint32 id = 0;
  16. QByteArray data;
  17. };
  18. SingleInstance();
  19. ~SingleInstance();
  20. void start(
  21. const QString &uniqueApplicationName,
  22. const QString &path,
  23. Fn<void()> primary,
  24. Fn<void()> secondary,
  25. Fn<void()> fail);
  26. void send(const QByteArray &command, Fn<void()> done);
  27. [[nodiscard]] rpl::producer<Message> commands() const;
  28. void reply(uint32 commandId, QWidget *activate = nullptr);
  29. private:
  30. void clearSocket();
  31. void clearLock();
  32. [[nodiscard]] bool closeExisting();
  33. void newInstanceConnected();
  34. void readClient(not_null<QLocalSocket*> client);
  35. void removeClient(not_null<QLocalSocket*> client);
  36. QString _name;
  37. QLocalServer _server;
  38. QLocalSocket _socket;
  39. uint32 _lastMessageId = 0;
  40. base::flat_map<not_null<QLocalSocket*>, Message> _clients;
  41. rpl::event_stream<Message> _commands;
  42. QFile _lockFile;
  43. FileLock _lock;
  44. };
  45. } // namespace base