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.

378 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: ChildProcessDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Launches applications as child processes.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics
  26. exporters: xcode_mac, vs2022, linux_make
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Console
  29. mainClass: ChildProcessDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. //==============================================================================
  36. // This is a token that's used at both ends of our parent-child processes, to
  37. // act as a unique token in the command line arguments.
  38. static const char* demoCommandLineUID = "demoUID";
  39. // A few quick utility functions to convert between raw data and ValueTrees
  40. static ValueTree memoryBlockToValueTree (const MemoryBlock& mb)
  41. {
  42. return ValueTree::readFromData (mb.getData(), mb.getSize());
  43. }
  44. static MemoryBlock valueTreeToMemoryBlock (const ValueTree& v)
  45. {
  46. MemoryOutputStream mo;
  47. v.writeToStream (mo);
  48. return mo.getMemoryBlock();
  49. }
  50. static String valueTreeToString (const ValueTree& v)
  51. {
  52. if (auto xml = v.createXml())
  53. return xml->toString (XmlElement::TextFormat().singleLine().withoutHeader());
  54. return {};
  55. }
  56. //==============================================================================
  57. class ChildProcessDemo final : public Component,
  58. private MessageListener
  59. {
  60. public:
  61. ChildProcessDemo()
  62. {
  63. setOpaque (true);
  64. addAndMakeVisible (launchButton);
  65. launchButton.onClick = [this] { launchChildProcess(); };
  66. addAndMakeVisible (pingButton);
  67. pingButton.onClick = [this] { pingChildProcess(); };
  68. addAndMakeVisible (killButton);
  69. killButton.onClick = [this] { killChildProcess(); };
  70. addAndMakeVisible (testResultsBox);
  71. testResultsBox.setMultiLine (true);
  72. testResultsBox.setFont ({ Font::getDefaultMonospacedFontName(), 12.0f, Font::plain });
  73. logMessage (String ("This demo uses the ChildProcessCoordinator and ChildProcessWorker classes to launch and communicate "
  74. "with a child process, sending messages in the form of serialised ValueTree objects.") + newLine
  75. + String ("In this demo, the child process will automatically quit if it fails to receive a ping message at least every ")
  76. + String (timeoutSeconds)
  77. + String (" seconds. To keep the process alive, press the \"")
  78. + pingButton.getButtonText()
  79. + String ("\" button periodically.") + newLine);
  80. setSize (500, 500);
  81. }
  82. ~ChildProcessDemo() override
  83. {
  84. coordinatorProcess.reset();
  85. }
  86. void paint (Graphics& g) override
  87. {
  88. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  89. }
  90. void resized() override
  91. {
  92. auto area = getLocalBounds();
  93. auto top = area.removeFromTop (40);
  94. launchButton.setBounds (top.removeFromLeft (180).reduced (8));
  95. pingButton .setBounds (top.removeFromLeft (180).reduced (8));
  96. killButton .setBounds (top.removeFromLeft (180).reduced (8));
  97. testResultsBox.setBounds (area.reduced (8));
  98. }
  99. // Appends a message to the textbox that's shown in the demo as the console
  100. void logMessage (const String& message)
  101. {
  102. postMessage (new LogMessage (message));
  103. }
  104. // invoked by the 'launch' button.
  105. void launchChildProcess()
  106. {
  107. if (coordinatorProcess.get() == nullptr)
  108. {
  109. coordinatorProcess = std::make_unique<DemoCoordinatorProcess> (*this);
  110. if (coordinatorProcess->launchWorkerProcess (File::getSpecialLocation (File::currentExecutableFile),
  111. demoCommandLineUID,
  112. timeoutMillis))
  113. {
  114. logMessage ("Child process started");
  115. }
  116. }
  117. }
  118. // invoked by the 'ping' button.
  119. void pingChildProcess()
  120. {
  121. if (coordinatorProcess != nullptr)
  122. coordinatorProcess->sendPingMessageToWorker();
  123. else
  124. logMessage ("Child process is not running!");
  125. }
  126. // invoked by the 'kill' button.
  127. void killChildProcess()
  128. {
  129. if (coordinatorProcess.get() != nullptr)
  130. {
  131. coordinatorProcess.reset();
  132. logMessage ("Child process killed");
  133. }
  134. }
  135. //==============================================================================
  136. // This class is used by the main process, acting as the coordinator and receiving messages
  137. // from the worker process.
  138. class DemoCoordinatorProcess final : public ChildProcessCoordinator,
  139. private DeletedAtShutdown,
  140. private AsyncUpdater
  141. {
  142. public:
  143. DemoCoordinatorProcess (ChildProcessDemo& d) : demo (d) {}
  144. ~DemoCoordinatorProcess() override { cancelPendingUpdate(); }
  145. // This gets called when a message arrives from the worker process..
  146. void handleMessageFromWorker (const MemoryBlock& mb) override
  147. {
  148. auto incomingMessage = memoryBlockToValueTree (mb);
  149. demo.logMessage ("Received: " + valueTreeToString (incomingMessage));
  150. }
  151. // This gets called if the worker process dies.
  152. void handleConnectionLost() override
  153. {
  154. demo.logMessage ("Connection lost to child process!");
  155. triggerAsyncUpdate();
  156. }
  157. void handleAsyncUpdate() override
  158. {
  159. demo.killChildProcess();
  160. }
  161. void sendPingMessageToWorker()
  162. {
  163. ValueTree message ("MESSAGE");
  164. message.setProperty ("count", count++, nullptr);
  165. demo.logMessage ("Sending: " + valueTreeToString (message));
  166. sendMessageToWorker (valueTreeToMemoryBlock (message));
  167. }
  168. ChildProcessDemo& demo;
  169. int count = 0;
  170. };
  171. //==============================================================================
  172. std::unique_ptr<DemoCoordinatorProcess> coordinatorProcess;
  173. static constexpr auto timeoutSeconds = 10;
  174. static constexpr auto timeoutMillis = timeoutSeconds * 1000;
  175. private:
  176. TextButton launchButton { "Launch Child Process" };
  177. TextButton pingButton { "Send Ping" };
  178. TextButton killButton { "Kill Child Process" };
  179. TextEditor testResultsBox;
  180. struct LogMessage final : public Message
  181. {
  182. LogMessage (const String& m) : message (m) {}
  183. String message;
  184. };
  185. void handleMessage (const Message& message) override
  186. {
  187. testResultsBox.moveCaretToEnd();
  188. testResultsBox.insertTextAtCaret (static_cast<const LogMessage&> (message).message + newLine);
  189. testResultsBox.moveCaretToEnd();
  190. }
  191. void lookAndFeelChanged() override
  192. {
  193. testResultsBox.applyFontToAllText (testResultsBox.getFont());
  194. }
  195. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessDemo)
  196. };
  197. //==============================================================================
  198. /* This class gets instantiated in the child process, and receives messages from
  199. the coordinator process.
  200. */
  201. class DemoWorkerProcess final : public ChildProcessWorker,
  202. private DeletedAtShutdown
  203. {
  204. public:
  205. DemoWorkerProcess() = default;
  206. void handleMessageFromCoordinator (const MemoryBlock& mb) override
  207. {
  208. ValueTree incomingMessage (memoryBlockToValueTree (mb));
  209. /* In this demo we're only expecting one type of message, which will contain a 'count' parameter -
  210. we'll just increment that number and send back a new message containing the new number.
  211. Obviously in a real app you'll probably want to look at the type of the message, and do
  212. some more interesting behaviour.
  213. */
  214. ValueTree reply ("REPLY");
  215. reply.setProperty ("countPlusOne", static_cast<int> (incomingMessage["count"]) + 1, nullptr);
  216. sendMessageToCoordinator (valueTreeToMemoryBlock (reply));
  217. }
  218. void handleConnectionMade() override
  219. {
  220. // This method is called when the connection is established, and in response, we'll just
  221. // send off a message to say hello.
  222. ValueTree reply ("HelloWorld");
  223. sendMessageToCoordinator (valueTreeToMemoryBlock (reply));
  224. }
  225. /* If no pings are received from the coordinator process for a number of seconds, then this will get invoked.
  226. Typically, you'll want to use this as a signal to kill the process as quickly as possible, as you
  227. don't want to leave it hanging around as a zombie.
  228. */
  229. void handleConnectionLost() override
  230. {
  231. JUCEApplication::quit();
  232. }
  233. };
  234. //==============================================================================
  235. /* The JUCEApplication::initialise method calls this function to allow the
  236. child process to launch when the command line parameters indicate that we're
  237. being asked to run as a child process.
  238. */
  239. inline bool invokeChildProcessDemo (const String& commandLine)
  240. {
  241. auto worker = std::make_unique<DemoWorkerProcess>();
  242. if (worker->initialiseFromCommandLine (commandLine, demoCommandLineUID, ChildProcessDemo::timeoutMillis))
  243. {
  244. worker.release(); // allow the worker object to stay alive - it'll handle its own deletion.
  245. return true;
  246. }
  247. return false;
  248. }
  249. #ifndef JUCE_DEMO_RUNNER
  250. //==============================================================================
  251. // As we need to modify the JUCEApplication::initialise method to launch the child process
  252. // based on the command line parameters, we can't just use the normal auto-generated Main.cpp.
  253. // Instead, we don't do anything in Main.cpp and create a JUCEApplication subclass here with
  254. // the necessary modifications.
  255. class Application final : public JUCEApplication
  256. {
  257. public:
  258. //==============================================================================
  259. Application() {}
  260. const String getApplicationName() override { return "ChildProcessDemo"; }
  261. const String getApplicationVersion() override { return "1.0.0"; }
  262. void initialise (const String& commandLine) override
  263. {
  264. // launches the child process if the command line parameters contain the demo UID
  265. if (invokeChildProcessDemo (commandLine))
  266. return;
  267. mainWindow = std::make_unique<MainWindow> ("ChildProcessDemo", std::make_unique<ChildProcessDemo>());
  268. }
  269. void shutdown() override { mainWindow = nullptr; }
  270. private:
  271. class MainWindow final : public DocumentWindow
  272. {
  273. public:
  274. MainWindow (const String& name, std::unique_ptr<Component> c)
  275. : DocumentWindow (name,
  276. Desktop::getInstance().getDefaultLookAndFeel()
  277. .findColour (ResizableWindow::backgroundColourId),
  278. DocumentWindow::allButtons)
  279. {
  280. setUsingNativeTitleBar (true);
  281. setContentOwned (c.release(), true);
  282. centreWithSize (getWidth(), getHeight());
  283. setVisible (true);
  284. }
  285. void closeButtonPressed() override
  286. {
  287. JUCEApplication::getInstance()->systemRequestedQuit();
  288. }
  289. private:
  290. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  291. };
  292. std::unique_ptr<MainWindow> mainWindow;
  293. };
  294. //==============================================================================
  295. START_JUCE_APPLICATION (Application)
  296. #endif