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.

356 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - 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, vs2019, 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 : 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. setSize (500, 500);
  76. }
  77. ~ChildProcessDemo() override
  78. {
  79. coordinatorProcess.reset();
  80. }
  81. void paint (Graphics& g) override
  82. {
  83. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  84. }
  85. void resized() override
  86. {
  87. auto area = getLocalBounds();
  88. auto top = area.removeFromTop (40);
  89. launchButton.setBounds (top.removeFromLeft (180).reduced (8));
  90. pingButton .setBounds (top.removeFromLeft (180).reduced (8));
  91. killButton .setBounds (top.removeFromLeft (180).reduced (8));
  92. testResultsBox.setBounds (area.reduced (8));
  93. }
  94. // Appends a message to the textbox that's shown in the demo as the console
  95. void logMessage (const String& message)
  96. {
  97. postMessage (new LogMessage (message));
  98. }
  99. // invoked by the 'launch' button.
  100. void launchChildProcess()
  101. {
  102. if (coordinatorProcess.get() == nullptr)
  103. {
  104. coordinatorProcess.reset (new DemoCoordinatorProcess (*this));
  105. if (coordinatorProcess->launchWorkerProcess (File::getSpecialLocation (File::currentExecutableFile), demoCommandLineUID))
  106. logMessage ("Child process started");
  107. }
  108. }
  109. // invoked by the 'ping' button.
  110. void pingChildProcess()
  111. {
  112. if (coordinatorProcess.get() != nullptr)
  113. coordinatorProcess->sendPingMessageToWorker();
  114. else
  115. logMessage ("Child process is not running!");
  116. }
  117. // invoked by the 'kill' button.
  118. void killChildProcess()
  119. {
  120. if (coordinatorProcess.get() != nullptr)
  121. {
  122. coordinatorProcess.reset();
  123. logMessage ("Child process killed");
  124. }
  125. }
  126. //==============================================================================
  127. // This class is used by the main process, acting as the coordinator and receiving messages
  128. // from the worker process.
  129. class DemoCoordinatorProcess : public ChildProcessCoordinator,
  130. private DeletedAtShutdown
  131. {
  132. public:
  133. DemoCoordinatorProcess (ChildProcessDemo& d) : demo (d) {}
  134. // This gets called when a message arrives from the worker process..
  135. void handleMessageFromWorker (const MemoryBlock& mb) override
  136. {
  137. auto incomingMessage = memoryBlockToValueTree (mb);
  138. demo.logMessage ("Received: " + valueTreeToString (incomingMessage));
  139. }
  140. // This gets called if the worker process dies.
  141. void handleConnectionLost() override
  142. {
  143. demo.logMessage ("Connection lost to child process!");
  144. demo.killChildProcess();
  145. }
  146. void sendPingMessageToWorker()
  147. {
  148. ValueTree message ("MESSAGE");
  149. message.setProperty ("count", count++, nullptr);
  150. demo.logMessage ("Sending: " + valueTreeToString (message));
  151. sendMessageToWorker (valueTreeToMemoryBlock (message));
  152. }
  153. ChildProcessDemo& demo;
  154. int count = 0;
  155. };
  156. //==============================================================================
  157. std::unique_ptr<DemoCoordinatorProcess> coordinatorProcess;
  158. private:
  159. TextButton launchButton { "Launch Child Process" };
  160. TextButton pingButton { "Send Ping" };
  161. TextButton killButton { "Kill Child Process" };
  162. TextEditor testResultsBox;
  163. struct LogMessage : public Message
  164. {
  165. LogMessage (const String& m) : message (m) {}
  166. String message;
  167. };
  168. void handleMessage (const Message& message) override
  169. {
  170. testResultsBox.moveCaretToEnd();
  171. testResultsBox.insertTextAtCaret (static_cast<const LogMessage&> (message).message + newLine);
  172. testResultsBox.moveCaretToEnd();
  173. }
  174. void lookAndFeelChanged() override
  175. {
  176. testResultsBox.applyFontToAllText (testResultsBox.getFont());
  177. }
  178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessDemo)
  179. };
  180. //==============================================================================
  181. /* This class gets instantiated in the child process, and receives messages from
  182. the coordinator process.
  183. */
  184. class DemoWorkerProcess : public ChildProcessWorker,
  185. private DeletedAtShutdown
  186. {
  187. public:
  188. DemoWorkerProcess() = default;
  189. void handleMessageFromCoordinator (const MemoryBlock& mb) override
  190. {
  191. ValueTree incomingMessage (memoryBlockToValueTree (mb));
  192. /* In this demo we're only expecting one type of message, which will contain a 'count' parameter -
  193. we'll just increment that number and send back a new message containing the new number.
  194. Obviously in a real app you'll probably want to look at the type of the message, and do
  195. some more interesting behaviour.
  196. */
  197. ValueTree reply ("REPLY");
  198. reply.setProperty ("countPlusOne", static_cast<int> (incomingMessage["count"]) + 1, nullptr);
  199. sendMessageToCoordinator (valueTreeToMemoryBlock (reply));
  200. }
  201. void handleConnectionMade() override
  202. {
  203. // This method is called when the connection is established, and in response, we'll just
  204. // send off a message to say hello.
  205. ValueTree reply ("HelloWorld");
  206. sendMessageToCoordinator (valueTreeToMemoryBlock (reply));
  207. }
  208. /* If no pings are received from the coordinator process for a number of seconds, then this will get invoked.
  209. Typically you'll want to use this as a signal to kill the process as quickly as possible, as you
  210. don't want to leave it hanging around as a zombie..
  211. */
  212. void handleConnectionLost() override
  213. {
  214. JUCEApplication::quit();
  215. }
  216. };
  217. //==============================================================================
  218. /* The JUCEApplication::initialise method calls this function to allow the
  219. child process to launch when the command line parameters indicate that we're
  220. being asked to run as a child process..
  221. */
  222. bool invokeChildProcessDemo (const String& commandLine)
  223. {
  224. std::unique_ptr<DemoWorkerProcess> worker (new DemoWorkerProcess());
  225. if (worker->initialiseFromCommandLine (commandLine, demoCommandLineUID))
  226. {
  227. worker.release(); // allow the worker object to stay alive - it'll handle its own deletion.
  228. return true;
  229. }
  230. return false;
  231. }
  232. #ifndef JUCE_DEMO_RUNNER
  233. //==============================================================================
  234. // As we need to modify the JUCEApplication::initialise method to launch the child process
  235. // based on the command line parameters, we can't just use the normal auto-generated Main.cpp.
  236. // Instead, we don't do anything in Main.cpp and create a JUCEApplication subclass here with
  237. // the necessary modifications.
  238. class Application : public JUCEApplication
  239. {
  240. public:
  241. //==============================================================================
  242. Application() {}
  243. const String getApplicationName() override { return "ChildProcessDemo"; }
  244. const String getApplicationVersion() override { return "1.0.0"; }
  245. void initialise (const String& commandLine) override
  246. {
  247. // launches the child process if the command line parameters contain the demo UID
  248. if (invokeChildProcessDemo (commandLine))
  249. return;
  250. mainWindow.reset (new MainWindow ("ChildProcessDemo", new ChildProcessDemo()));
  251. }
  252. void shutdown() override { mainWindow = nullptr; }
  253. private:
  254. class MainWindow : public DocumentWindow
  255. {
  256. public:
  257. MainWindow (const String& name, Component* c) : DocumentWindow (name,
  258. Desktop::getInstance().getDefaultLookAndFeel()
  259. .findColour (ResizableWindow::backgroundColourId),
  260. DocumentWindow::allButtons)
  261. {
  262. setUsingNativeTitleBar (true);
  263. setContentOwned (c, true);
  264. centreWithSize (getWidth(), getHeight());
  265. setVisible (true);
  266. }
  267. void closeButtonPressed() override
  268. {
  269. JUCEApplication::getInstance()->systemRequestedQuit();
  270. }
  271. private:
  272. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  273. };
  274. std::unique_ptr<MainWindow> mainWindow;
  275. };
  276. //==============================================================================
  277. START_JUCE_APPLICATION (Application)
  278. #endif