The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

372 lines
10KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. struct InterprocessConnection::ConnectionThread : public Thread
  20. {
  21. ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
  22. void run() override { owner.runThread(); }
  23. InterprocessConnection& owner;
  24. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  25. };
  26. //==============================================================================
  27. InterprocessConnection::InterprocessConnection (bool callbacksOnMessageThread, uint32 magicMessageHeaderNumber)
  28. : useMessageThread (callbacksOnMessageThread),
  29. magicMessageHeader (magicMessageHeaderNumber)
  30. {
  31. thread.reset (new ConnectionThread (*this));
  32. }
  33. InterprocessConnection::~InterprocessConnection()
  34. {
  35. callbackConnectionState = false;
  36. disconnect();
  37. masterReference.clear();
  38. thread.reset();
  39. }
  40. //==============================================================================
  41. bool InterprocessConnection::connectToSocket (const String& hostName,
  42. int portNumber, int timeOutMillisecs)
  43. {
  44. disconnect();
  45. const ScopedLock sl (pipeAndSocketLock);
  46. socket.reset (new StreamingSocket());
  47. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  48. {
  49. connectionMadeInt();
  50. thread->startThread();
  51. return true;
  52. }
  53. socket.reset();
  54. return false;
  55. }
  56. bool InterprocessConnection::connectToPipe (const String& pipeName, int timeoutMs)
  57. {
  58. disconnect();
  59. std::unique_ptr<NamedPipe> newPipe (new NamedPipe());
  60. if (newPipe->openExisting (pipeName))
  61. {
  62. const ScopedLock sl (pipeAndSocketLock);
  63. pipeReceiveMessageTimeout = timeoutMs;
  64. initialiseWithPipe (newPipe.release());
  65. return true;
  66. }
  67. return false;
  68. }
  69. bool InterprocessConnection::createPipe (const String& pipeName, int timeoutMs, bool mustNotExist)
  70. {
  71. disconnect();
  72. std::unique_ptr<NamedPipe> newPipe (new NamedPipe());
  73. if (newPipe->createNewPipe (pipeName, mustNotExist))
  74. {
  75. const ScopedLock sl (pipeAndSocketLock);
  76. pipeReceiveMessageTimeout = timeoutMs;
  77. initialiseWithPipe (newPipe.release());
  78. return true;
  79. }
  80. return false;
  81. }
  82. void InterprocessConnection::disconnect()
  83. {
  84. thread->signalThreadShouldExit();
  85. {
  86. const ScopedLock sl (pipeAndSocketLock);
  87. if (socket != nullptr) socket->close();
  88. if (pipe != nullptr) pipe->close();
  89. }
  90. thread->stopThread (4000);
  91. deletePipeAndSocket();
  92. connectionLostInt();
  93. }
  94. void InterprocessConnection::deletePipeAndSocket()
  95. {
  96. const ScopedLock sl (pipeAndSocketLock);
  97. socket.reset();
  98. pipe.reset();
  99. }
  100. bool InterprocessConnection::isConnected() const
  101. {
  102. const ScopedLock sl (pipeAndSocketLock);
  103. return ((socket != nullptr && socket->isConnected())
  104. || (pipe != nullptr && pipe->isOpen()))
  105. && thread->isThreadRunning();
  106. }
  107. String InterprocessConnection::getConnectedHostName() const
  108. {
  109. {
  110. const ScopedLock sl (pipeAndSocketLock);
  111. if (pipe == nullptr && socket == nullptr)
  112. return {};
  113. if (socket != nullptr && ! socket->isLocal())
  114. return socket->getHostName();
  115. }
  116. return IPAddress::local().toString();
  117. }
  118. //==============================================================================
  119. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  120. {
  121. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  122. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  123. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  124. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  125. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  126. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  127. }
  128. int InterprocessConnection::writeData (void* data, int dataSize)
  129. {
  130. const ScopedLock sl (pipeAndSocketLock);
  131. if (socket != nullptr)
  132. return socket->write (data, dataSize);
  133. if (pipe != nullptr)
  134. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  135. return 0;
  136. }
  137. //==============================================================================
  138. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  139. {
  140. jassert (socket == nullptr && pipe == nullptr);
  141. socket.reset (newSocket);
  142. connectionMadeInt();
  143. thread->startThread();
  144. }
  145. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  146. {
  147. jassert (socket == nullptr && pipe == nullptr);
  148. pipe.reset (newPipe);
  149. connectionMadeInt();
  150. thread->startThread();
  151. }
  152. //==============================================================================
  153. struct ConnectionStateMessage : public MessageManager::MessageBase
  154. {
  155. ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
  156. : owner (ipc), connectionMade (connected)
  157. {}
  158. void messageCallback() override
  159. {
  160. if (auto* ipc = owner.get())
  161. {
  162. if (connectionMade)
  163. ipc->connectionMade();
  164. else
  165. ipc->connectionLost();
  166. }
  167. }
  168. WeakReference<InterprocessConnection> owner;
  169. bool connectionMade;
  170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  171. };
  172. void InterprocessConnection::connectionMadeInt()
  173. {
  174. if (! callbackConnectionState)
  175. {
  176. callbackConnectionState = true;
  177. if (useMessageThread)
  178. (new ConnectionStateMessage (this, true))->post();
  179. else
  180. connectionMade();
  181. }
  182. }
  183. void InterprocessConnection::connectionLostInt()
  184. {
  185. if (callbackConnectionState)
  186. {
  187. callbackConnectionState = false;
  188. if (useMessageThread)
  189. (new ConnectionStateMessage (this, false))->post();
  190. else
  191. connectionLost();
  192. }
  193. }
  194. struct DataDeliveryMessage : public Message
  195. {
  196. DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
  197. : owner (ipc), data (d)
  198. {}
  199. void messageCallback() override
  200. {
  201. if (auto* ipc = owner.get())
  202. ipc->messageReceived (data);
  203. }
  204. WeakReference<InterprocessConnection> owner;
  205. MemoryBlock data;
  206. };
  207. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  208. {
  209. jassert (callbackConnectionState);
  210. if (useMessageThread)
  211. (new DataDeliveryMessage (this, data))->post();
  212. else
  213. messageReceived (data);
  214. }
  215. //==============================================================================
  216. int InterprocessConnection::readData (void* data, int num)
  217. {
  218. if (socket != nullptr)
  219. return socket->read (data, num, true);
  220. if (pipe != nullptr)
  221. return pipe->read (data, num, pipeReceiveMessageTimeout);
  222. jassertfalse;
  223. return -1;
  224. }
  225. bool InterprocessConnection::readNextMessage()
  226. {
  227. uint32 messageHeader[2];
  228. auto bytes = readData (messageHeader, sizeof (messageHeader));
  229. if (bytes == sizeof (messageHeader)
  230. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  231. {
  232. auto bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  233. if (bytesInMessage > 0)
  234. {
  235. MemoryBlock messageData ((size_t) bytesInMessage, true);
  236. int bytesRead = 0;
  237. while (bytesInMessage > 0)
  238. {
  239. if (thread->threadShouldExit())
  240. return false;
  241. auto numThisTime = jmin (bytesInMessage, 65536);
  242. auto bytesIn = readData (addBytesToPointer (messageData.getData(), bytesRead), numThisTime);
  243. if (bytesIn <= 0)
  244. break;
  245. bytesRead += bytesIn;
  246. bytesInMessage -= bytesIn;
  247. }
  248. if (bytesRead >= 0)
  249. deliverDataInt (messageData);
  250. }
  251. return true;
  252. }
  253. if (bytes < 0)
  254. {
  255. if (socket != nullptr)
  256. deletePipeAndSocket();
  257. connectionLostInt();
  258. }
  259. return false;
  260. }
  261. void InterprocessConnection::runThread()
  262. {
  263. while (! thread->threadShouldExit())
  264. {
  265. if (socket != nullptr)
  266. {
  267. auto ready = socket->waitUntilReady (true, 100);
  268. if (ready < 0)
  269. {
  270. deletePipeAndSocket();
  271. connectionLostInt();
  272. break;
  273. }
  274. if (ready == 0)
  275. {
  276. thread->wait (1);
  277. continue;
  278. }
  279. }
  280. else if (pipe != nullptr)
  281. {
  282. if (! pipe->isOpen())
  283. {
  284. deletePipeAndSocket();
  285. connectionLostInt();
  286. break;
  287. }
  288. }
  289. else
  290. {
  291. break;
  292. }
  293. if (thread->threadShouldExit() || ! readNextMessage())
  294. break;
  295. }
  296. }
  297. } // namespace juce