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.

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