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.

964 lines
32KB

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