single_instance.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. #include "base/single_instance.h"
  8. #include "base/crc32hash.h"
  9. #include "base/platform/base_platform_process.h"
  10. #include <QtCore/QStandardPaths>
  11. #include <QtWidgets/QWidget>
  12. #include <QtGui/QWindow>
  13. namespace base {
  14. namespace {
  15. [[nodiscard]] QString NameForPath(
  16. const QString &uniqueApplicationName,
  17. const QString &path) {
  18. const auto hash = [](const QString &text) {
  19. return crc32(text.data(), text.size() * sizeof(QChar));
  20. };
  21. const auto ints = std::array{ hash(uniqueApplicationName), hash(path) };
  22. auto raw = QByteArray(ints.size() * sizeof(ints[0]), Qt::Uninitialized);
  23. memcpy(raw.data(), ints.data(), raw.size());
  24. return QString::fromLatin1(raw.toBase64(QByteArray::Base64UrlEncoding));
  25. }
  26. void CleanName(const QString &name) {
  27. #ifndef Q_OS_WIN
  28. QFile(name).remove();
  29. #endif // Q_OS_WIN
  30. }
  31. [[nodiscard]] QByteArray EncodeMessage(const QByteArray &message) {
  32. return message.toBase64(QByteArray::Base64UrlEncoding) + ';';
  33. }
  34. [[nodiscard]] std::optional<QByteArray> DecodeMessage(const QByteArray &message) {
  35. if (!message.endsWith(';')) {
  36. return std::nullopt;
  37. }
  38. return QByteArray::fromBase64(
  39. message.mid(0, message.size() - 1),
  40. QByteArray::Base64UrlEncoding);
  41. }
  42. } // namespace
  43. SingleInstance::SingleInstance() = default;
  44. void SingleInstance::start(
  45. const QString &uniqueApplicationName,
  46. const QString &path,
  47. Fn<void()> primary,
  48. Fn<void()> secondary,
  49. Fn<void()> fail) {
  50. const auto handleError = [=](QLocalSocket::LocalSocketError error) {
  51. clearSocket();
  52. QObject::connect(
  53. &_server,
  54. &QLocalServer::newConnection,
  55. [=] { newInstanceConnected(); });
  56. if (closeExisting() && _server.listen(_name)) {
  57. primary();
  58. } else {
  59. fail();
  60. }
  61. };
  62. QObject::connect(&_socket, &QLocalSocket::connected, secondary);
  63. QObject::connect(&_socket, &QLocalSocket::errorOccurred, handleError);
  64. QObject::connect(
  65. &_socket,
  66. &QLocalSocket::disconnected,
  67. [=] { handleError(QLocalSocket::PeerClosedError); });
  68. _lockFile.setFileName(path + "_single_instance.tmp");
  69. _name = NameForPath(uniqueApplicationName, path);
  70. _socket.connectToServer(_name);
  71. }
  72. SingleInstance::~SingleInstance() {
  73. clearSocket();
  74. clearLock();
  75. }
  76. bool SingleInstance::closeExisting() {
  77. if (!_lock.lock(_lockFile, QIODevice::WriteOnly)) {
  78. return false;
  79. }
  80. CleanName(_name);
  81. return true;
  82. }
  83. void SingleInstance::clearSocket() {
  84. QObject::disconnect(
  85. &_socket,
  86. &QLocalSocket::connected,
  87. nullptr,
  88. nullptr);
  89. QObject::disconnect(
  90. &_socket,
  91. &QLocalSocket::disconnected,
  92. nullptr,
  93. nullptr);
  94. QObject::disconnect(
  95. &_socket,
  96. &QLocalSocket::errorOccurred,
  97. nullptr,
  98. nullptr);
  99. QObject::disconnect(
  100. &_socket,
  101. &QLocalSocket::readyRead,
  102. nullptr,
  103. nullptr);
  104. _socket.close();
  105. }
  106. void SingleInstance::clearLock() {
  107. if (!_lock.locked()) {
  108. return;
  109. }
  110. _lock.unlock();
  111. _lockFile.close();
  112. _lockFile.remove();
  113. }
  114. void SingleInstance::send(const QByteArray &command, Fn<void()> done) {
  115. Expects(_socket.state() == QLocalSocket::ConnectedState);
  116. const auto received = std::make_shared<QByteArray>();
  117. const auto handleRead = [=] {
  118. Expects(_socket.state() == QLocalSocket::ConnectedState);
  119. received->append(_socket.readAll());
  120. if (const auto response = DecodeMessage(*received)) {
  121. static const auto RegExp = QRegularExpression(
  122. "^PID:(\\d+);WND:(\\d+);$"
  123. );
  124. const auto match = RegExp.match(QString::fromLatin1(*response));
  125. if (const auto pid = match.captured(1).toULongLong()) {
  126. Platform::ActivateProcessWindow(
  127. static_cast<int64>(pid),
  128. static_cast<WId>(match.captured(2).toULongLong()));
  129. }
  130. done();
  131. }
  132. };
  133. QObject::connect(&_socket, &QLocalSocket::readyRead, handleRead);
  134. _socket.write(EncodeMessage(command));
  135. }
  136. void SingleInstance::newInstanceConnected() {
  137. while (const auto client = _server.nextPendingConnection()) {
  138. _clients.emplace(client, Message{ ++_lastMessageId });
  139. QObject::connect(client, &QLocalSocket::readyRead, [=] {
  140. readClient(client);
  141. });
  142. QObject::connect(client, &QLocalSocket::disconnected, [=] {
  143. removeClient(client);
  144. });
  145. }
  146. }
  147. void SingleInstance::readClient(not_null<QLocalSocket*> client) {
  148. Expects(_clients.contains(client));
  149. auto &info = _clients[client];
  150. info.data.append(client->readAll());
  151. if (const auto message = DecodeMessage(info.data)) {
  152. _commands.fire({ info.id, *message });
  153. }
  154. }
  155. void SingleInstance::removeClient(not_null<QLocalSocket*> client) {
  156. QObject::disconnect(client, &QLocalSocket::readyRead, nullptr, nullptr);
  157. QObject::disconnect(
  158. client,
  159. &QLocalSocket::disconnected,
  160. nullptr,
  161. nullptr);
  162. _clients.remove(client);
  163. }
  164. auto SingleInstance::commands() const -> rpl::producer<Message> {
  165. return _commands.events();
  166. }
  167. void SingleInstance::reply(uint32 commandId, QWidget *activate) {
  168. const auto window = activate
  169. ? activate->window()->windowHandle()
  170. : nullptr;
  171. const auto wid = window
  172. ? static_cast<uint64>(window->winId())
  173. : 0ULL;
  174. const auto pid = wid
  175. ? static_cast<uint64>(QCoreApplication::applicationPid())
  176. : 0ULL;
  177. auto response = QString("PID:%1;WND:%2;").arg(pid).arg(wid).toLatin1();
  178. for (const auto &[client, data] : _clients) {
  179. if (data.id == commandId) {
  180. client->write(EncodeMessage(response));
  181. return;
  182. }
  183. }
  184. }
  185. } // namespace base