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.

358 lines
12KB

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