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.

951 lines
30KB

  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. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../Application/jucer_Headers.h"
  20. #include "../Application/jucer_Application.h"
  21. #include "../ProjectSaving/jucer_ProjectExporter.h"
  22. #include "jucer_MessageIDs.h"
  23. #include "jucer_CppHelpers.h"
  24. #include "jucer_SourceCodeRange.h"
  25. #include "jucer_ClassDatabase.h"
  26. #include "jucer_DiagnosticMessage.h"
  27. #include "jucer_ProjectBuildInfo.h"
  28. #include "jucer_ClientServerMessages.h"
  29. #include "jucer_CompileEngineClient.h"
  30. #include "../LiveBuildEngine/jucer_CompileEngineServer.h"
  31. #ifndef RUN_CLANG_IN_CHILD_PROCESS
  32. #error
  33. #endif
  34. //==============================================================================
  35. namespace ProjectProperties
  36. {
  37. const Identifier liveSettingsType ("LIVE_SETTINGS");
  38. #if JUCE_MAC
  39. const Identifier liveSettingsSubtype ("OSX");
  40. #elif JUCE_WINDOWS
  41. const Identifier liveSettingsSubtype ("WINDOWS");
  42. #elif JUCE_LINUX
  43. const Identifier liveSettingsSubtype ("LINUX");
  44. #endif
  45. static ValueTree getLiveSettings (Project& project)
  46. {
  47. return project.getProjectRoot().getOrCreateChildWithName (liveSettingsType, nullptr)
  48. .getOrCreateChildWithName (liveSettingsSubtype, nullptr);
  49. }
  50. static ValueWithDefault getLiveSetting (Project& p, const Identifier& i, var defaultValue = var())
  51. {
  52. auto tree = getLiveSettings (p);
  53. return { tree, i, p.getUndoManagerFor (tree), defaultValue };
  54. }
  55. static ValueWithDefault getUserHeaderPathValue (Project& p) { return getLiveSetting (p, Ids::headerPath); }
  56. static ValueWithDefault getSystemHeaderPathValue (Project& p) { return getLiveSetting (p, Ids::systemHeaderPath); }
  57. static ValueWithDefault getExtraDLLsValue (Project& p) { return getLiveSetting (p, Ids::extraDLLs); }
  58. static ValueWithDefault getExtraCompilerFlagsValue (Project& p) { return getLiveSetting (p, Ids::extraCompilerFlags); }
  59. static ValueWithDefault getExtraPreprocessorDefsValue (Project& p) { return getLiveSetting (p, Ids::defines); }
  60. static ValueWithDefault getWindowsTargetPlatformVersionValue (Project& p) { return getLiveSetting (p, Ids::liveWindowsTargetPlatformVersion, "10.0.16299.0"); }
  61. static File getProjucerTempFolder()
  62. {
  63. #if JUCE_MAC
  64. return File ("~/Library/Caches/com.juce.projucer");
  65. #else
  66. return File::getSpecialLocation (File::tempDirectory).getChildFile ("com.juce.projucer");
  67. #endif
  68. }
  69. static File getCacheLocation (Project& project)
  70. {
  71. auto cacheFolderName = project.getProjectFilenameRootString() + "_" + project.getProjectUIDString();
  72. #if JUCE_DEBUG
  73. cacheFolderName += "_debug";
  74. #endif
  75. return getProjucerTempFolder()
  76. .getChildFile ("Intermediate Files")
  77. .getChildFile (cacheFolderName);
  78. }
  79. }
  80. //==============================================================================
  81. void LiveBuildProjectSettings::getLiveSettings (Project& project, PropertyListBuilder& props)
  82. {
  83. using namespace ProjectProperties;
  84. props.addSearchPathProperty (getUserHeaderPathValue (project), "User Header Paths", "User header search paths.");
  85. props.addSearchPathProperty (getSystemHeaderPathValue (project), "System header paths", "System header search paths.");
  86. props.add (new TextPropertyComponent (getExtraPreprocessorDefsValue (project), "Preprocessor Definitions", 32768, true),
  87. "Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace or commas "
  88. "to separate the items - to include a space or comma in a definition, precede it with a backslash.");
  89. props.add (new TextPropertyComponent (getExtraCompilerFlagsValue (project), "Extra Compiler Flags", 2048, true),
  90. "Extra command-line flags to be passed to the compiler. This string can contain references to preprocessor"
  91. " definitions in the form ${NAME_OF_DEFINITION}, which will be replaced with their values.");
  92. props.add (new TextPropertyComponent (getExtraDLLsValue (project), "Extra Dynamic Libraries", 2048, true),
  93. "Extra dynamic libs that the running code may require. Use new-lines or commas to separate the items.");
  94. props.add (new TextPropertyComponent (getWindowsTargetPlatformVersionValue (project), "Windows Target Platform", 256, false),
  95. "The Windows target platform to use.");
  96. }
  97. void LiveBuildProjectSettings::updateNewlyOpenedProject (Project&) { /* placeholder */ }
  98. bool LiveBuildProjectSettings::isBuildDisabled (Project& p)
  99. {
  100. const bool defaultBuildDisabled = true;
  101. return p.getStoredProperties().getBoolValue ("buildDisabled", defaultBuildDisabled);
  102. }
  103. void LiveBuildProjectSettings::setBuildDisabled (Project& p, bool b) { p.getStoredProperties().setValue ("buildDisabled", b); }
  104. bool LiveBuildProjectSettings::areWarningsDisabled (Project& p) { return p.getStoredProperties().getBoolValue ("warningsDisabled"); }
  105. void LiveBuildProjectSettings::setWarningsDisabled (Project& p, bool b) { p.getStoredProperties().setValue ("warningsDisabled", b); }
  106. //==============================================================================
  107. class ClientIPC : public MessageHandler,
  108. private InterprocessConnection,
  109. private Timer
  110. {
  111. public:
  112. ClientIPC (CompileEngineChildProcess& cp)
  113. : InterprocessConnection (true), owner (cp)
  114. {
  115. launchServer();
  116. }
  117. ~ClientIPC()
  118. {
  119. #if RUN_CLANG_IN_CHILD_PROCESS
  120. if (childProcess.isRunning())
  121. {
  122. #if JUCE_DEBUG
  123. killServerPolitely();
  124. #else
  125. // in release builds we don't want to wait
  126. // for the server to clean up and shut down
  127. killServerWithoutMercy();
  128. #endif
  129. }
  130. #endif
  131. }
  132. void launchServer()
  133. {
  134. DBG ("Client: Launching Server...");
  135. const String pipeName ("ipc_" + String::toHexString (Random().nextInt64()));
  136. const String command (createCommandLineForLaunchingServer (pipeName,
  137. owner.project.getProjectUIDString(),
  138. ProjectProperties::getCacheLocation (owner.project)));
  139. #if RUN_CLANG_IN_CHILD_PROCESS
  140. if (! childProcess.start (command))
  141. {
  142. jassertfalse;
  143. }
  144. #else
  145. server = createClangServer (command);
  146. #endif
  147. bool ok = connectToPipe (pipeName, 10000);
  148. jassert (ok);
  149. if (ok)
  150. MessageTypes::sendPing (*this);
  151. startTimer (serverKeepAliveTimeout);
  152. }
  153. void killServerPolitely()
  154. {
  155. DBG ("Client: Killing Server...");
  156. MessageTypes::sendQuit (*this);
  157. disconnect();
  158. stopTimer();
  159. #if RUN_CLANG_IN_CHILD_PROCESS
  160. childProcess.waitForProcessToFinish (5000);
  161. #endif
  162. killServerWithoutMercy();
  163. }
  164. void killServerWithoutMercy()
  165. {
  166. disconnect();
  167. stopTimer();
  168. #if RUN_CLANG_IN_CHILD_PROCESS
  169. childProcess.kill();
  170. #else
  171. destroyClangServer (server);
  172. server = nullptr;
  173. #endif
  174. }
  175. void connectionMade()
  176. {
  177. DBG ("Client: connected");
  178. stopTimer();
  179. }
  180. void connectionLost()
  181. {
  182. DBG ("Client: disconnected");
  183. startTimer (100);
  184. }
  185. bool sendMessage (const ValueTree& m)
  186. {
  187. return InterprocessConnection::sendMessage (MessageHandler::convertMessage (m));
  188. }
  189. void messageReceived (const MemoryBlock& message)
  190. {
  191. #if RUN_CLANG_IN_CHILD_PROCESS
  192. startTimer (serverKeepAliveTimeout);
  193. #else
  194. stopTimer();
  195. #endif
  196. MessageTypes::dispatchToClient (owner, MessageHandler::convertMessage (message));
  197. }
  198. enum { serverKeepAliveTimeout = 10000 };
  199. private:
  200. CompileEngineChildProcess& owner;
  201. #if RUN_CLANG_IN_CHILD_PROCESS
  202. ChildProcess childProcess;
  203. #else
  204. void* server;
  205. #endif
  206. void timerCallback()
  207. {
  208. stopTimer();
  209. owner.handleCrash (String());
  210. }
  211. };
  212. //==============================================================================
  213. class CompileEngineChildProcess::ChildProcess : private ValueTree::Listener,
  214. private Timer
  215. {
  216. public:
  217. ChildProcess (CompileEngineChildProcess& proc, Project& p)
  218. : owner (proc), project (p)
  219. {
  220. projectRoot = project.getProjectRoot();
  221. restartServer();
  222. projectRoot.addListener (this);
  223. openedOk = true;
  224. }
  225. ~ChildProcess()
  226. {
  227. projectRoot.removeListener (this);
  228. if (isRunningApp && server != nullptr)
  229. server->killServerWithoutMercy();
  230. server.reset();
  231. }
  232. void restartServer()
  233. {
  234. server.reset();
  235. server = new ClientIPC (owner);
  236. sendRebuild();
  237. }
  238. void sendRebuild()
  239. {
  240. stopTimer();
  241. ProjectBuildInfo build;
  242. if (! doesProjectMatchSavedHeaderState (project))
  243. {
  244. MessageTypes::sendNewBuild (*server, build);
  245. owner.errorList.resetToError ("Project structure does not match the saved headers! "
  246. "Please re-save your project to enable compilation");
  247. return;
  248. }
  249. if (areAnyModulesMissing (project))
  250. {
  251. MessageTypes::sendNewBuild (*server, build);
  252. owner.errorList.resetToError ("Some of your JUCE modules can't be found! "
  253. "Please check that all the module paths are correct");
  254. return;
  255. }
  256. build.setSystemIncludes (getSystemIncludePaths());
  257. build.setUserIncludes (getUserIncludes());
  258. build.setGlobalDefs (getGlobalDefs (project));
  259. build.setCompileFlags (ProjectProperties::getExtraCompilerFlagsValue (project).get().toString().trim());
  260. build.setExtraDLLs (getExtraDLLs());
  261. build.setJuceModulesFolder (EnabledModuleList::findDefaultModulesFolder (project).getFullPathName());
  262. build.setUtilsCppInclude (project.getAppIncludeFile().getFullPathName());
  263. build.setWindowsTargetPlatformVersion (ProjectProperties::getWindowsTargetPlatformVersionValue (project).get().toString());
  264. scanForProjectFiles (project, build);
  265. owner.updateAllEditors();
  266. MessageTypes::sendNewBuild (*server, build);
  267. }
  268. void cleanAll()
  269. {
  270. MessageTypes::sendCleanAll (*server);
  271. sendRebuild();
  272. }
  273. void reinstantiatePreviews()
  274. {
  275. MessageTypes::sendReinstantiate (*server);
  276. }
  277. bool launchApp()
  278. {
  279. MessageTypes::sendLaunchApp (*server);
  280. return true;
  281. }
  282. ScopedPointer<ClientIPC> server;
  283. bool openedOk = false;
  284. bool isRunningApp = false;
  285. private:
  286. CompileEngineChildProcess& owner;
  287. Project& project;
  288. ValueTree projectRoot;
  289. void projectStructureChanged()
  290. {
  291. startTimer (100);
  292. }
  293. void timerCallback() override
  294. {
  295. sendRebuild();
  296. }
  297. void valueTreePropertyChanged (ValueTree&, const Identifier&) override { projectStructureChanged(); }
  298. void valueTreeChildAdded (ValueTree&, ValueTree&) override { projectStructureChanged(); }
  299. void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { projectStructureChanged(); }
  300. void valueTreeParentChanged (ValueTree&) override { projectStructureChanged(); }
  301. void valueTreeChildOrderChanged (ValueTree&, int, int) override {}
  302. static String getGlobalDefs (Project& proj)
  303. {
  304. String defs (ProjectProperties::getExtraPreprocessorDefsValue (proj).get().toString());
  305. for (Project::ExporterIterator exporter (proj); exporter.next();)
  306. if (exporter->canLaunchProject())
  307. defs << " " << exporter->getExporterIdentifierMacro() << "=1";
  308. // Use the JUCE implementation of std::function until the live build
  309. // engine can compile the one from the standard library
  310. defs << " _LIBCPP_FUNCTIONAL=1";
  311. return defs;
  312. }
  313. static void scanProjectItem (const Project::Item& projectItem, Array<File>& compileUnits, Array<File>& userFiles)
  314. {
  315. if (projectItem.isGroup())
  316. {
  317. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  318. scanProjectItem (projectItem.getChild(i), compileUnits, userFiles);
  319. return;
  320. }
  321. if (projectItem.shouldBeCompiled())
  322. {
  323. const File f (projectItem.getFile());
  324. if (f.exists())
  325. compileUnits.add (f);
  326. }
  327. if (projectItem.shouldBeAddedToTargetProject() && ! projectItem.shouldBeAddedToBinaryResources())
  328. {
  329. const File f (projectItem.getFile());
  330. if (f.exists())
  331. userFiles.add (f);
  332. }
  333. }
  334. void scanForProjectFiles (Project& proj, ProjectBuildInfo& build)
  335. {
  336. Array<File> compileUnits, userFiles;
  337. scanProjectItem (proj.getMainGroup(), compileUnits, userFiles);
  338. {
  339. auto isVST3Host = project.getModules().isModuleEnabled ("juce_audio_processors")
  340. && project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3");
  341. auto isPluginProject = proj.getProjectType().isAudioPlugin();
  342. OwnedArray<LibraryModule> modules;
  343. proj.getModules().createRequiredModules (modules);
  344. for (Project::ExporterIterator exporter (proj); exporter.next();)
  345. {
  346. if (exporter->canLaunchProject())
  347. {
  348. for (const LibraryModule* m : modules)
  349. {
  350. const File localModuleFolder = proj.getModules().shouldCopyModuleFilesLocally (m->moduleInfo.getID()).getValue()
  351. ? proj.getLocalModuleFolder (m->moduleInfo.getID())
  352. : m->moduleInfo.getFolder();
  353. m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits,
  354. isPluginProject || isVST3Host ? ProjectType::Target::SharedCodeTarget
  355. : ProjectType::Target::unspecified);
  356. if (isPluginProject || isVST3Host)
  357. m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits, ProjectType::Target::StandalonePlugIn);
  358. }
  359. break;
  360. }
  361. }
  362. }
  363. for (int i = 0; ; ++i)
  364. {
  365. const File binaryDataCpp (proj.getBinaryDataCppFile (i));
  366. if (! binaryDataCpp.exists())
  367. break;
  368. compileUnits.add (binaryDataCpp);
  369. }
  370. for (int i = compileUnits.size(); --i >= 0;)
  371. if (compileUnits.getReference(i).hasFileExtension (".r"))
  372. compileUnits.remove (i);
  373. build.setFiles (compileUnits, userFiles);
  374. }
  375. static bool doesProjectMatchSavedHeaderState (Project& project)
  376. {
  377. ValueTree liveModules (project.getProjectRoot().getChildWithName (Ids::MODULES));
  378. ScopedPointer<XmlElement> xml (XmlDocument::parse (project.getFile()));
  379. if (xml == nullptr || ! xml->hasTagName (Ids::JUCERPROJECT.toString()))
  380. return false;
  381. ValueTree diskModules (ValueTree::fromXml (*xml).getChildWithName (Ids::MODULES));
  382. return liveModules.isEquivalentTo (diskModules);
  383. }
  384. static bool areAnyModulesMissing (Project& project)
  385. {
  386. OwnedArray<LibraryModule> modules;
  387. project.getModules().createRequiredModules (modules);
  388. for (auto* module : modules)
  389. if (! module->getFolder().isDirectory())
  390. return true;
  391. return false;
  392. }
  393. StringArray getUserIncludes()
  394. {
  395. StringArray paths;
  396. paths.add (project.getGeneratedCodeFolder().getFullPathName());
  397. paths.addArray (getSearchPathsFromString (ProjectProperties::getUserHeaderPathValue (project).get().toString()));
  398. return convertSearchPathsToAbsolute (paths);
  399. }
  400. StringArray getSystemIncludePaths()
  401. {
  402. StringArray paths;
  403. paths.addArray (getSearchPathsFromString (ProjectProperties::getSystemHeaderPathValue (project).get().toString()));
  404. auto isVST3Host = project.getModules().isModuleEnabled ("juce_audio_processors")
  405. && project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3");
  406. if (project.getProjectType().isAudioPlugin() || isVST3Host)
  407. paths.add (getAppSettings().getStoredPath (Ids::vst3Path).toString());
  408. OwnedArray<LibraryModule> modules;
  409. project.getModules().createRequiredModules (modules);
  410. for (auto* module : modules)
  411. paths.addIfNotAlreadyThere (module->getFolder().getParentDirectory().getFullPathName());
  412. return convertSearchPathsToAbsolute (paths);
  413. }
  414. StringArray convertSearchPathsToAbsolute (const StringArray& paths) const
  415. {
  416. StringArray s;
  417. const File root (project.getProjectFolder());
  418. for (String p : paths)
  419. s.add (root.getChildFile (p).getFullPathName());
  420. return s;
  421. }
  422. StringArray getExtraDLLs()
  423. {
  424. StringArray dlls;
  425. dlls.addTokens (ProjectProperties::getExtraDLLsValue (project).get().toString(), "\n\r,", StringRef());
  426. dlls.trim();
  427. dlls.removeEmptyStrings();
  428. return dlls;
  429. }
  430. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcess)
  431. };
  432. //==============================================================================
  433. CompileEngineChildProcess::CompileEngineChildProcess (Project& p)
  434. : project (p),
  435. continuousRebuild (false)
  436. {
  437. ProjucerApplication::getApp().openDocumentManager.addListener (this);
  438. createProcess();
  439. errorList.setWarningsEnabled (! LiveBuildProjectSettings::areWarningsDisabled (project));
  440. }
  441. CompileEngineChildProcess::~CompileEngineChildProcess()
  442. {
  443. ProjucerApplication::getApp().openDocumentManager.removeListener (this);
  444. process.reset();
  445. lastComponentList.clear();
  446. }
  447. void CompileEngineChildProcess::createProcess()
  448. {
  449. jassert (process == nullptr);
  450. process = new ChildProcess (*this, project);
  451. if (! process->openedOk)
  452. process.reset();
  453. updateAllEditors();
  454. }
  455. void CompileEngineChildProcess::cleanAll()
  456. {
  457. if (process != nullptr)
  458. process->cleanAll();
  459. }
  460. void CompileEngineChildProcess::openPreview (const ClassDatabase::Class& comp)
  461. {
  462. if (process != nullptr)
  463. {
  464. MainWindow* projectWindow = nullptr;
  465. OwnedArray<MainWindow>& windows = ProjucerApplication::getApp().mainWindowList.windows;
  466. for (int i = 0; i < windows.size(); ++i)
  467. {
  468. if (MainWindow* w = windows[i])
  469. {
  470. if (w->getProject() == &project)
  471. {
  472. projectWindow = w;
  473. break;
  474. }
  475. }
  476. }
  477. Rectangle<int> mainWindowRect;
  478. if (projectWindow != nullptr)
  479. mainWindowRect = projectWindow->getBounds();
  480. MessageTypes::sendOpenPreview (*process->server, comp, mainWindowRect);
  481. }
  482. }
  483. void CompileEngineChildProcess::reinstantiatePreviews()
  484. {
  485. if (process != nullptr)
  486. process->reinstantiatePreviews();
  487. }
  488. void CompileEngineChildProcess::processActivationChanged (bool isForeground)
  489. {
  490. if (process != nullptr)
  491. MessageTypes::sendProcessActivationState (*process->server, isForeground);
  492. }
  493. //==============================================================================
  494. bool CompileEngineChildProcess::canLaunchApp() const
  495. {
  496. return process != nullptr
  497. && runningAppProcess == nullptr
  498. && activityList.getNumActivities() == 0
  499. && errorList.getNumErrors() == 0
  500. && project.getProjectType().isGUIApplication();
  501. }
  502. void CompileEngineChildProcess::launchApp()
  503. {
  504. if (process != nullptr)
  505. process->launchApp();
  506. }
  507. bool CompileEngineChildProcess::canKillApp() const
  508. {
  509. return runningAppProcess != nullptr;
  510. }
  511. void CompileEngineChildProcess::killApp()
  512. {
  513. runningAppProcess.reset();
  514. }
  515. void CompileEngineChildProcess::handleAppLaunched()
  516. {
  517. runningAppProcess = process;
  518. runningAppProcess->isRunningApp = true;
  519. createProcess();
  520. }
  521. void CompileEngineChildProcess::handleAppQuit()
  522. {
  523. DBG ("handleAppQuit");
  524. runningAppProcess.reset();
  525. }
  526. //==============================================================================
  527. struct CompileEngineChildProcess::Editor : private CodeDocument::Listener,
  528. private Timer
  529. {
  530. Editor (CompileEngineChildProcess& ccp, const File& f, CodeDocument& doc)
  531. : owner (ccp), file (f), document (doc), transactionTimer (doc)
  532. {
  533. sendFullUpdate();
  534. document.addListener (this);
  535. }
  536. ~Editor()
  537. {
  538. document.removeListener (this);
  539. }
  540. void codeDocumentTextInserted (const String& newText, int insertIndex) override
  541. {
  542. CodeChange (Range<int> (insertIndex, insertIndex), newText).addToList (pendingChanges);
  543. startEditorChangeTimer();
  544. transactionTimer.stopTimer();
  545. owner.lastComponentList.globalNamespace
  546. .nudgeAllCodeRanges (file.getFullPathName(), insertIndex, newText.length());
  547. }
  548. void codeDocumentTextDeleted (int start, int end) override
  549. {
  550. CodeChange (Range<int> (start, end), String()).addToList (pendingChanges);
  551. startEditorChangeTimer();
  552. transactionTimer.stopTimer();
  553. owner.lastComponentList.globalNamespace
  554. .nudgeAllCodeRanges (file.getFullPathName(), start, start - end);
  555. }
  556. void sendFullUpdate()
  557. {
  558. reset();
  559. if (owner.process != nullptr)
  560. MessageTypes::sendFileContentFullUpdate (*owner.process->server, file, document.getAllContent());
  561. }
  562. bool flushEditorChanges()
  563. {
  564. if (pendingChanges.size() > 0)
  565. {
  566. if (owner.process != nullptr && owner.process->server != nullptr)
  567. MessageTypes::sendFileChanges (*owner.process->server, pendingChanges, file);
  568. reset();
  569. return true;
  570. }
  571. stopTimer();
  572. return false;
  573. }
  574. void reset()
  575. {
  576. stopTimer();
  577. pendingChanges.clear();
  578. }
  579. void startTransactionTimer()
  580. {
  581. transactionTimer.startTimer (1000);
  582. }
  583. void startEditorChangeTimer()
  584. {
  585. startTimer (200);
  586. }
  587. CompileEngineChildProcess& owner;
  588. File file;
  589. CodeDocument& document;
  590. private:
  591. Array<CodeChange> pendingChanges;
  592. void timerCallback() override
  593. {
  594. if (owner.continuousRebuild)
  595. flushEditorChanges();
  596. else
  597. stopTimer();
  598. }
  599. struct TransactionTimer : public Timer
  600. {
  601. TransactionTimer (CodeDocument& doc) : document (doc) {}
  602. void timerCallback() override
  603. {
  604. stopTimer();
  605. document.newTransaction();
  606. }
  607. CodeDocument& document;
  608. };
  609. TransactionTimer transactionTimer;
  610. };
  611. void CompileEngineChildProcess::editorOpened (const File& file, CodeDocument& document)
  612. {
  613. editors.add (new Editor (*this, file, document));
  614. }
  615. bool CompileEngineChildProcess::documentAboutToClose (OpenDocumentManager::Document* document)
  616. {
  617. for (int i = editors.size(); --i >= 0;)
  618. {
  619. if (document->getFile() == editors.getUnchecked(i)->file)
  620. {
  621. const File f (editors.getUnchecked(i)->file);
  622. editors.remove (i);
  623. if (process != nullptr)
  624. MessageTypes::sendHandleFileReset (*process->server, f);
  625. }
  626. }
  627. return true;
  628. }
  629. void CompileEngineChildProcess::updateAllEditors()
  630. {
  631. for (int i = editors.size(); --i >= 0;)
  632. editors.getUnchecked(i)->sendFullUpdate();
  633. }
  634. //==============================================================================
  635. void CompileEngineChildProcess::handleCrash (const String& message)
  636. {
  637. Logger::writeToLog ("*** Child process crashed: " + message);
  638. if (crashHandler != nullptr)
  639. crashHandler (message);
  640. }
  641. void CompileEngineChildProcess::handleNewDiagnosticList (const ValueTree& l) { errorList.setList (l); }
  642. void CompileEngineChildProcess::handleActivityListChanged (const StringArray& l) { activityList.setList (l); }
  643. void CompileEngineChildProcess::handleCloseIDE()
  644. {
  645. if (JUCEApplication* app = JUCEApplication::getInstance())
  646. app->systemRequestedQuit();
  647. }
  648. void CompileEngineChildProcess::handleMissingSystemHeaders()
  649. {
  650. if (ProjectContentComponent* p = findProjectContentComponent())
  651. p->handleMissingSystemHeaders();
  652. }
  653. void CompileEngineChildProcess::handleKeyPress (const String& className, const KeyPress& key)
  654. {
  655. ApplicationCommandManager& commandManager = ProjucerApplication::getCommandManager();
  656. CommandID command = commandManager.getKeyMappings()->findCommandForKeyPress (key);
  657. if (command == StandardApplicationCommandIDs::undo)
  658. {
  659. handleUndoInEditor (className);
  660. }
  661. else if (command == StandardApplicationCommandIDs::redo)
  662. {
  663. handleRedoInEditor (className);
  664. }
  665. else if (ApplicationCommandTarget* const target = ApplicationCommandManager::findTargetForComponent (findProjectContentComponent()))
  666. {
  667. commandManager.setFirstCommandTarget (target);
  668. commandManager.getKeyMappings()->keyPressed (key, findProjectContentComponent());
  669. commandManager.setFirstCommandTarget (nullptr);
  670. }
  671. }
  672. void CompileEngineChildProcess::handleUndoInEditor (const String& /*className*/)
  673. {
  674. }
  675. void CompileEngineChildProcess::handleRedoInEditor (const String& /*className*/)
  676. {
  677. }
  678. void CompileEngineChildProcess::handleClassListChanged (const ValueTree& newList)
  679. {
  680. lastComponentList = ClassDatabase::ClassList::fromValueTree (newList);
  681. activityList.sendClassListChangedMessage (lastComponentList);
  682. }
  683. void CompileEngineChildProcess::handleBuildFailed()
  684. {
  685. ProjucerApplication::getCommandManager().commandStatusChanged();
  686. }
  687. void CompileEngineChildProcess::handleChangeCode (const SourceCodeRange& location, const String& newText)
  688. {
  689. if (Editor* ed = getOrOpenEditorFor (location.file))
  690. {
  691. if (ed->flushEditorChanges())
  692. return; // client-side editor changes were pending, so deal with them first, and discard
  693. // the incoming change, whose position may now be wrong.
  694. ed->document.deleteSection (location.range.getStart(), location.range.getEnd());
  695. ed->document.insertText (location.range.getStart(), newText);
  696. // deliberately clear the messages that we just added, to avoid these changes being
  697. // sent to the server (which will already have processed the same ones locally)
  698. ed->reset();
  699. ed->startTransactionTimer();
  700. }
  701. }
  702. void CompileEngineChildProcess::handlePing()
  703. {
  704. }
  705. //==============================================================================
  706. void CompileEngineChildProcess::setContinuousRebuild (bool b)
  707. {
  708. continuousRebuild = b;
  709. }
  710. void CompileEngineChildProcess::flushEditorChanges()
  711. {
  712. for (Editor* ed : editors)
  713. ed->flushEditorChanges();
  714. }
  715. ProjectContentComponent* CompileEngineChildProcess::findProjectContentComponent() const
  716. {
  717. for (MainWindow* mw : ProjucerApplication::getApp().mainWindowList.windows)
  718. if (mw->getProject() == &project)
  719. return mw->getProjectContentComponent();
  720. return nullptr;
  721. }
  722. CompileEngineChildProcess::Editor* CompileEngineChildProcess::getOrOpenEditorFor (const File& file)
  723. {
  724. for (Editor* ed : editors)
  725. if (ed->file == file)
  726. return ed;
  727. if (ProjectContentComponent* pcc = findProjectContentComponent())
  728. if (pcc->showEditorForFile (file, false))
  729. return getOrOpenEditorFor (file);
  730. return nullptr;
  731. }
  732. void CompileEngineChildProcess::handleHighlightCode (const SourceCodeRange& location)
  733. {
  734. ProjectContentComponent* pcc = findProjectContentComponent();
  735. if (pcc != nullptr && pcc->showEditorForFile (location.file, false))
  736. {
  737. SourceCodeEditor* sce = dynamic_cast <SourceCodeEditor*> (pcc->getEditorComponent());
  738. if (sce != nullptr && sce->editor != nullptr)
  739. {
  740. sce->highlight (location.range, true);
  741. Process::makeForegroundProcess();
  742. CodeEditorComponent& ed = *sce->editor;
  743. ed.getTopLevelComponent()->toFront (false);
  744. ed.grabKeyboardFocus();
  745. }
  746. }
  747. }
  748. void CompileEngineChildProcess::cleanAllCachedFilesForProject (Project& p)
  749. {
  750. File cacheFolder (ProjectProperties::getCacheLocation (p));
  751. if (cacheFolder.isDirectory())
  752. cacheFolder.deleteRecursively();
  753. }