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.

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