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.

958 lines
31KB

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