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.

970 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. auto isVST3Host = project.getModules().isModuleEnabled ("juce_audio_processors")
  347. && project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3");
  348. auto isPluginProject = proj.getProjectType().isAudioPlugin();
  349. OwnedArray<LibraryModule> modules;
  350. proj.getModules().createRequiredModules (modules);
  351. for (Project::ExporterIterator exporter (proj); exporter.next();)
  352. {
  353. if (exporter->canLaunchProject())
  354. {
  355. for (const LibraryModule* m : modules)
  356. {
  357. const File localModuleFolder = proj.getModules().shouldCopyModuleFilesLocally (m->moduleInfo.getID()).getValue()
  358. ? proj.getLocalModuleFolder (m->moduleInfo.getID())
  359. : m->moduleInfo.getFolder();
  360. m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits,
  361. isPluginProject || isVST3Host ? ProjectType::Target::SharedCodeTarget
  362. : ProjectType::Target::unspecified);
  363. if (isPluginProject || isVST3Host)
  364. m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits, ProjectType::Target::StandalonePlugIn);
  365. }
  366. break;
  367. }
  368. }
  369. }
  370. for (int i = 0; ; ++i)
  371. {
  372. const File binaryDataCpp (proj.getBinaryDataCppFile (i));
  373. if (! binaryDataCpp.exists())
  374. break;
  375. compileUnits.add (binaryDataCpp);
  376. }
  377. for (int i = compileUnits.size(); --i >= 0;)
  378. if (compileUnits.getReference(i).hasFileExtension (".r"))
  379. compileUnits.remove (i);
  380. build.setFiles (compileUnits, userFiles);
  381. }
  382. static bool doesProjectMatchSavedHeaderState (Project& project)
  383. {
  384. ValueTree liveModules (project.getProjectRoot().getChildWithName (Ids::MODULES));
  385. ScopedPointer<XmlElement> xml (XmlDocument::parse (project.getFile()));
  386. if (xml == nullptr || ! xml->hasTagName (Ids::JUCERPROJECT.toString()))
  387. return false;
  388. ValueTree diskModules (ValueTree::fromXml (*xml).getChildWithName (Ids::MODULES));
  389. return liveModules.isEquivalentTo (diskModules);
  390. }
  391. static bool areAnyModulesMissing (Project& project)
  392. {
  393. OwnedArray<LibraryModule> modules;
  394. project.getModules().createRequiredModules (modules);
  395. for (auto* module : modules)
  396. if (! module->getFolder().isDirectory())
  397. return true;
  398. return false;
  399. }
  400. StringArray getUserIncludes()
  401. {
  402. StringArray paths;
  403. paths.add (project.getGeneratedCodeFolder().getFullPathName());
  404. paths.addArray (getSearchPathsFromString (ProjectProperties::getUserHeaderPathString (project)));
  405. return convertSearchPathsToAbsolute (paths);
  406. }
  407. StringArray getSystemIncludePaths()
  408. {
  409. StringArray paths;
  410. paths.addArray (getSearchPathsFromString (ProjectProperties::getSystemHeaderPathString (project)));
  411. auto isVST3Host = project.getModules().isModuleEnabled ("juce_audio_processors")
  412. && project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3");
  413. if (project.getProjectType().isAudioPlugin() || isVST3Host)
  414. paths.add (getAppSettings().getStoredPath (Ids::vst3Path).toString());
  415. OwnedArray<LibraryModule> modules;
  416. project.getModules().createRequiredModules (modules);
  417. for (auto* module : modules)
  418. paths.addIfNotAlreadyThere (module->getFolder().getParentDirectory().getFullPathName());
  419. return convertSearchPathsToAbsolute (paths);
  420. }
  421. StringArray convertSearchPathsToAbsolute (const StringArray& paths) const
  422. {
  423. StringArray s;
  424. const File root (project.getProjectFolder());
  425. for (String p : paths)
  426. s.add (root.getChildFile (p).getFullPathName());
  427. return s;
  428. }
  429. StringArray getExtraDLLs()
  430. {
  431. StringArray dlls;
  432. dlls.addTokens (ProjectProperties::getExtraDLLsString (project), "\n\r,", StringRef());
  433. dlls.trim();
  434. dlls.removeEmptyStrings();
  435. return dlls;
  436. }
  437. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcess)
  438. };
  439. //==============================================================================
  440. CompileEngineChildProcess::CompileEngineChildProcess (Project& p)
  441. : project (p),
  442. continuousRebuild (false)
  443. {
  444. ProjucerApplication::getApp().openDocumentManager.addListener (this);
  445. createProcess();
  446. errorList.setWarningsEnabled (! LiveBuildProjectSettings::areWarningsDisabled (project));
  447. }
  448. CompileEngineChildProcess::~CompileEngineChildProcess()
  449. {
  450. ProjucerApplication::getApp().openDocumentManager.removeListener (this);
  451. process = nullptr;
  452. lastComponentList.clear();
  453. }
  454. void CompileEngineChildProcess::createProcess()
  455. {
  456. jassert (process == nullptr);
  457. process = new ChildProcess (*this, project);
  458. if (! process->openedOk)
  459. process = nullptr;
  460. updateAllEditors();
  461. }
  462. void CompileEngineChildProcess::cleanAll()
  463. {
  464. if (process != nullptr)
  465. process->cleanAll();
  466. }
  467. void CompileEngineChildProcess::openPreview (const ClassDatabase::Class& comp)
  468. {
  469. if (process != nullptr)
  470. {
  471. MainWindow* projectWindow = nullptr;
  472. OwnedArray<MainWindow>& windows = ProjucerApplication::getApp().mainWindowList.windows;
  473. for (int i = 0; i < windows.size(); ++i)
  474. {
  475. if (MainWindow* w = windows[i])
  476. {
  477. if (w->getProject() == &project)
  478. {
  479. projectWindow = w;
  480. break;
  481. }
  482. }
  483. }
  484. Rectangle<int> mainWindowRect;
  485. if (projectWindow != nullptr)
  486. mainWindowRect = projectWindow->getBounds();
  487. MessageTypes::sendOpenPreview (*process->server, comp, mainWindowRect);
  488. }
  489. }
  490. void CompileEngineChildProcess::reinstantiatePreviews()
  491. {
  492. if (process != nullptr)
  493. process->reinstantiatePreviews();
  494. }
  495. void CompileEngineChildProcess::processActivationChanged (bool isForeground)
  496. {
  497. if (process != nullptr)
  498. MessageTypes::sendProcessActivationState (*process->server, isForeground);
  499. }
  500. //==============================================================================
  501. bool CompileEngineChildProcess::canLaunchApp() const
  502. {
  503. return process != nullptr
  504. && runningAppProcess == nullptr
  505. && activityList.getNumActivities() == 0
  506. && errorList.getNumErrors() == 0
  507. && project.getProjectType().isGUIApplication();
  508. }
  509. void CompileEngineChildProcess::launchApp()
  510. {
  511. if (process != nullptr)
  512. process->launchApp();
  513. }
  514. bool CompileEngineChildProcess::canKillApp() const
  515. {
  516. return runningAppProcess != nullptr;
  517. }
  518. void CompileEngineChildProcess::killApp()
  519. {
  520. runningAppProcess = nullptr;
  521. }
  522. void CompileEngineChildProcess::handleAppLaunched()
  523. {
  524. runningAppProcess = process;
  525. runningAppProcess->isRunningApp = true;
  526. createProcess();
  527. }
  528. void CompileEngineChildProcess::handleAppQuit()
  529. {
  530. DBG ("handleAppQuit");
  531. runningAppProcess = nullptr;
  532. }
  533. //==============================================================================
  534. struct CompileEngineChildProcess::Editor : private CodeDocument::Listener,
  535. private Timer
  536. {
  537. Editor (CompileEngineChildProcess& ccp, const File& f, CodeDocument& doc)
  538. : owner (ccp), file (f), document (doc), transactionTimer (doc)
  539. {
  540. sendFullUpdate();
  541. document.addListener (this);
  542. }
  543. ~Editor()
  544. {
  545. document.removeListener (this);
  546. }
  547. void codeDocumentTextInserted (const String& newText, int insertIndex) override
  548. {
  549. CodeChange (Range<int> (insertIndex, insertIndex), newText).addToList (pendingChanges);
  550. startEditorChangeTimer();
  551. transactionTimer.stopTimer();
  552. owner.lastComponentList.globalNamespace
  553. .nudgeAllCodeRanges (file.getFullPathName(), insertIndex, newText.length());
  554. }
  555. void codeDocumentTextDeleted (int start, int end) override
  556. {
  557. CodeChange (Range<int> (start, end), String()).addToList (pendingChanges);
  558. startEditorChangeTimer();
  559. transactionTimer.stopTimer();
  560. owner.lastComponentList.globalNamespace
  561. .nudgeAllCodeRanges (file.getFullPathName(), start, start - end);
  562. }
  563. void sendFullUpdate()
  564. {
  565. reset();
  566. if (owner.process != nullptr)
  567. MessageTypes::sendFileContentFullUpdate (*owner.process->server, file, document.getAllContent());
  568. }
  569. bool flushEditorChanges()
  570. {
  571. if (pendingChanges.size() > 0)
  572. {
  573. if (owner.process != nullptr && owner.process->server != nullptr)
  574. MessageTypes::sendFileChanges (*owner.process->server, pendingChanges, file);
  575. reset();
  576. return true;
  577. }
  578. stopTimer();
  579. return false;
  580. }
  581. void reset()
  582. {
  583. stopTimer();
  584. pendingChanges.clear();
  585. }
  586. void startTransactionTimer()
  587. {
  588. transactionTimer.startTimer (1000);
  589. }
  590. void startEditorChangeTimer()
  591. {
  592. startTimer (200);
  593. }
  594. CompileEngineChildProcess& owner;
  595. File file;
  596. CodeDocument& document;
  597. private:
  598. Array<CodeChange> pendingChanges;
  599. void timerCallback() override
  600. {
  601. if (owner.continuousRebuild)
  602. flushEditorChanges();
  603. else
  604. stopTimer();
  605. }
  606. struct TransactionTimer : public Timer
  607. {
  608. TransactionTimer (CodeDocument& doc) : document (doc) {}
  609. void timerCallback() override
  610. {
  611. stopTimer();
  612. document.newTransaction();
  613. }
  614. CodeDocument& document;
  615. };
  616. TransactionTimer transactionTimer;
  617. };
  618. void CompileEngineChildProcess::editorOpened (const File& file, CodeDocument& document)
  619. {
  620. editors.add (new Editor (*this, file, document));
  621. }
  622. bool CompileEngineChildProcess::documentAboutToClose (OpenDocumentManager::Document* document)
  623. {
  624. for (int i = editors.size(); --i >= 0;)
  625. {
  626. if (document->getFile() == editors.getUnchecked(i)->file)
  627. {
  628. const File f (editors.getUnchecked(i)->file);
  629. editors.remove (i);
  630. if (process != nullptr)
  631. MessageTypes::sendHandleFileReset (*process->server, f);
  632. }
  633. }
  634. return true;
  635. }
  636. void CompileEngineChildProcess::updateAllEditors()
  637. {
  638. for (int i = editors.size(); --i >= 0;)
  639. editors.getUnchecked(i)->sendFullUpdate();
  640. }
  641. //==============================================================================
  642. void CompileEngineChildProcess::handleCrash (const String& message)
  643. {
  644. Logger::writeToLog ("*** Child process crashed: " + message);
  645. if (crashHandler != nullptr)
  646. crashHandler (message);
  647. }
  648. void CompileEngineChildProcess::handleNewDiagnosticList (const ValueTree& l) { errorList.setList (l); }
  649. void CompileEngineChildProcess::handleActivityListChanged (const StringArray& l) { activityList.setList (l); }
  650. void CompileEngineChildProcess::handleCloseIDE()
  651. {
  652. if (JUCEApplication* app = JUCEApplication::getInstance())
  653. app->systemRequestedQuit();
  654. }
  655. void CompileEngineChildProcess::handleMissingSystemHeaders()
  656. {
  657. if (ProjectContentComponent* p = findProjectContentComponent())
  658. p->handleMissingSystemHeaders();
  659. }
  660. void CompileEngineChildProcess::handleKeyPress (const String& className, const KeyPress& key)
  661. {
  662. ApplicationCommandManager& commandManager = ProjucerApplication::getCommandManager();
  663. CommandID command = commandManager.getKeyMappings()->findCommandForKeyPress (key);
  664. if (command == StandardApplicationCommandIDs::undo)
  665. {
  666. handleUndoInEditor (className);
  667. }
  668. else if (command == StandardApplicationCommandIDs::redo)
  669. {
  670. handleRedoInEditor (className);
  671. }
  672. else if (ApplicationCommandTarget* const target = ApplicationCommandManager::findTargetForComponent (findProjectContentComponent()))
  673. {
  674. commandManager.setFirstCommandTarget (target);
  675. commandManager.getKeyMappings()->keyPressed (key, findProjectContentComponent());
  676. commandManager.setFirstCommandTarget (nullptr);
  677. }
  678. }
  679. void CompileEngineChildProcess::handleUndoInEditor (const String& /*className*/)
  680. {
  681. }
  682. void CompileEngineChildProcess::handleRedoInEditor (const String& /*className*/)
  683. {
  684. }
  685. void CompileEngineChildProcess::handleClassListChanged (const ValueTree& newList)
  686. {
  687. lastComponentList = ClassDatabase::ClassList::fromValueTree (newList);
  688. activityList.sendClassListChangedMessage (lastComponentList);
  689. }
  690. void CompileEngineChildProcess::handleBuildFailed()
  691. {
  692. auto* mcm = ModalComponentManager::getInstance();
  693. auto* pcc = findProjectContentComponent();
  694. if (mcm->getNumModalComponents() > 0 || pcc == nullptr || pcc->getCurrentTabIndex() == 1)
  695. return;
  696. if (errorList.getNumErrors() > 0)
  697. ProjucerApplication::getCommandManager().invokeDirectly (CommandIDs::showBuildTab, true);
  698. ProjucerApplication::getCommandManager().commandStatusChanged();
  699. }
  700. void CompileEngineChildProcess::handleChangeCode (const SourceCodeRange& location, const String& newText)
  701. {
  702. if (Editor* ed = getOrOpenEditorFor (location.file))
  703. {
  704. if (ed->flushEditorChanges())
  705. return; // client-side editor changes were pending, so deal with them first, and discard
  706. // the incoming change, whose position may now be wrong.
  707. ed->document.deleteSection (location.range.getStart(), location.range.getEnd());
  708. ed->document.insertText (location.range.getStart(), newText);
  709. // deliberately clear the messages that we just added, to avoid these changes being
  710. // sent to the server (which will already have processed the same ones locally)
  711. ed->reset();
  712. ed->startTransactionTimer();
  713. }
  714. }
  715. void CompileEngineChildProcess::handlePing()
  716. {
  717. }
  718. //==============================================================================
  719. void CompileEngineChildProcess::setContinuousRebuild (bool b)
  720. {
  721. continuousRebuild = b;
  722. }
  723. void CompileEngineChildProcess::flushEditorChanges()
  724. {
  725. for (Editor* ed : editors)
  726. ed->flushEditorChanges();
  727. }
  728. ProjectContentComponent* CompileEngineChildProcess::findProjectContentComponent() const
  729. {
  730. for (MainWindow* mw : ProjucerApplication::getApp().mainWindowList.windows)
  731. if (mw->getProject() == &project)
  732. return mw->getProjectContentComponent();
  733. return nullptr;
  734. }
  735. CompileEngineChildProcess::Editor* CompileEngineChildProcess::getOrOpenEditorFor (const File& file)
  736. {
  737. for (Editor* ed : editors)
  738. if (ed->file == file)
  739. return ed;
  740. if (ProjectContentComponent* pcc = findProjectContentComponent())
  741. if (pcc->showEditorForFile (file, false))
  742. return getOrOpenEditorFor (file);
  743. return nullptr;
  744. }
  745. void CompileEngineChildProcess::handleHighlightCode (const SourceCodeRange& location)
  746. {
  747. ProjectContentComponent* pcc = findProjectContentComponent();
  748. if (pcc != nullptr && pcc->showEditorForFile (location.file, false))
  749. {
  750. SourceCodeEditor* sce = dynamic_cast <SourceCodeEditor*> (pcc->getEditorComponent());
  751. if (sce != nullptr && sce->editor != nullptr)
  752. {
  753. sce->highlight (location.range, true);
  754. Process::makeForegroundProcess();
  755. CodeEditorComponent& ed = *sce->editor;
  756. ed.getTopLevelComponent()->toFront (false);
  757. ed.grabKeyboardFocus();
  758. }
  759. }
  760. }
  761. void CompileEngineChildProcess::cleanAllCachedFilesForProject (Project& p)
  762. {
  763. File cacheFolder (ProjectProperties::getCacheLocation (p));
  764. if (cacheFolder.isDirectory())
  765. cacheFolder.deleteRecursively();
  766. }