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.

1606 lines
57KB

  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. void createGUIEditorMenu (PopupMenu&);
  20. void handleGUIEditorMenuCommand (int);
  21. void registerGUIEditorCommands();
  22. //==============================================================================
  23. struct ProjucerApplication::MainMenuModel : public MenuBarModel
  24. {
  25. MainMenuModel()
  26. {
  27. setApplicationCommandManagerToWatch (&getCommandManager());
  28. }
  29. StringArray getMenuBarNames() override
  30. {
  31. return getApp().getMenuNames();
  32. }
  33. PopupMenu getMenuForIndex (int /*topLevelMenuIndex*/, const String& menuName) override
  34. {
  35. PopupMenu menu;
  36. getApp().createMenu (menu, menuName);
  37. return menu;
  38. }
  39. void menuItemSelected (int menuItemID, int /*topLevelMenuIndex*/) override
  40. {
  41. getApp().handleMainMenuCommand (menuItemID);
  42. }
  43. };
  44. //==============================================================================
  45. ProjucerApplication::ProjucerApplication() : isRunningCommandLine (false)
  46. {
  47. }
  48. void ProjucerApplication::initialise (const String& commandLine)
  49. {
  50. if (commandLine.trimStart().startsWith ("--server"))
  51. {
  52. initialiseLogger ("Compiler_Log_");
  53. LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  54. #if JUCE_MAC
  55. Process::setDockIconVisible (false);
  56. #endif
  57. server = createClangServer (commandLine);
  58. }
  59. else
  60. {
  61. initialiseLogger ("IDE_Log_");
  62. Logger::writeToLog (SystemStats::getOperatingSystemName());
  63. Logger::writeToLog ("CPU: " + String (SystemStats::getCpuSpeedInMegahertz())
  64. + "MHz Cores: " + String (SystemStats::getNumCpus())
  65. + " " + String (SystemStats::getMemorySizeInMegabytes()) + "MB");
  66. initialiseBasics();
  67. isRunningCommandLine = commandLine.isNotEmpty()
  68. && ! commandLine.startsWith ("-NSDocumentRevisionsDebugMode");
  69. licenseController.reset (new LicenseController);
  70. licenseController->addLicenseStatusChangedCallback (this);
  71. if (isRunningCommandLine)
  72. {
  73. auto appReturnCode = performCommandLine (ArgumentList ("Projucer", commandLine));
  74. if (appReturnCode != commandLineNotPerformed)
  75. {
  76. setApplicationReturnValue (appReturnCode);
  77. quit();
  78. return;
  79. }
  80. isRunningCommandLine = false;
  81. }
  82. if (sendCommandLineToPreexistingInstance())
  83. {
  84. DBG ("Another instance is running - quitting...");
  85. quit();
  86. return;
  87. }
  88. rescanJUCEPathModules();
  89. rescanUserPathModules();
  90. openDocumentManager.registerType (new ProjucerAppClasses::LiveBuildCodeEditorDocument::Type(), 2);
  91. childProcessCache.reset (new ChildProcessCache());
  92. initCommandManager();
  93. menuModel.reset (new MainMenuModel());
  94. settings->appearance.refreshPresetSchemeList();
  95. setColourScheme (settings->getGlobalProperties().getIntValue ("COLOUR SCHEME"), false);
  96. setEditorColourScheme (settings->getGlobalProperties().getIntValue ("EDITOR COLOUR SCHEME"), false);
  97. updateEditorColourSchemeIfNeeded();
  98. // do further initialisation in a moment when the message loop has started
  99. triggerAsyncUpdate();
  100. }
  101. }
  102. void ProjucerApplication::initialiseBasics()
  103. {
  104. LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  105. settings.reset (new StoredSettings());
  106. ImageCache::setCacheTimeout (30 * 1000);
  107. icons.reset (new Icons());
  108. tooltipWindow.setMillisecondsBeforeTipAppears (1200);
  109. }
  110. bool ProjucerApplication::initialiseLogger (const char* filePrefix)
  111. {
  112. if (logger == nullptr)
  113. {
  114. #if JUCE_LINUX
  115. String folder = "~/.config/Projucer/Logs";
  116. #else
  117. String folder = "com.juce.projucer";
  118. #endif
  119. logger.reset (FileLogger::createDateStampedLogger (folder, filePrefix, ".txt",
  120. getApplicationName() + " " + getApplicationVersion()
  121. + " --- Build date: " __DATE__));
  122. Logger::setCurrentLogger (logger.get());
  123. }
  124. return logger != nullptr;
  125. }
  126. void ProjucerApplication::handleAsyncUpdate()
  127. {
  128. if (licenseController != nullptr)
  129. licenseController->startWebviewIfNeeded();
  130. #if JUCE_MAC
  131. PopupMenu extraAppleMenuItems;
  132. createExtraAppleMenuItems (extraAppleMenuItems);
  133. // workaround broken "Open Recent" submenu: not passing the
  134. // submenu's title here avoids the defect in JuceMainMenuHandler::addMenuItem
  135. MenuBarModel::setMacMainMenu (menuModel.get(), &extraAppleMenuItems); //, "Open Recent");
  136. #endif
  137. versionChecker.reset (new LatestVersionChecker());
  138. if (licenseController != nullptr)
  139. {
  140. setAnalyticsEnabled (licenseController->getState().applicationUsageDataState == LicenseState::ApplicationUsageData::enabled);
  141. Analytics::getInstance()->logEvent ("Startup", {}, ProjucerAnalyticsEvent::appEvent);
  142. }
  143. if (! isRunningCommandLine && settings->shouldAskUserToSetJUCEPath())
  144. showSetJUCEPathAlert();
  145. }
  146. void ProjucerApplication::initialiseWindows (const String& commandLine)
  147. {
  148. const String commandLineWithoutNSDebug (commandLine.replace ("-NSDocumentRevisionsDebugMode YES", StringRef()));
  149. if (commandLineWithoutNSDebug.trim().isNotEmpty() && ! commandLineWithoutNSDebug.trim().startsWithChar ('-'))
  150. anotherInstanceStarted (commandLine);
  151. else
  152. mainWindowList.reopenLastProjects();
  153. mainWindowList.createWindowIfNoneAreOpen();
  154. if (licenseController->getState().applicationUsageDataState == LicenseState::ApplicationUsageData::notChosenYet)
  155. showApplicationUsageDataAgreementPopup();
  156. }
  157. static void deleteTemporaryFiles()
  158. {
  159. auto tempDirectory = File::getSpecialLocation (File::SpecialLocationType::tempDirectory).getChildFile ("PIPs");
  160. if (tempDirectory.exists())
  161. tempDirectory.deleteRecursively();
  162. }
  163. void ProjucerApplication::shutdown()
  164. {
  165. if (server != nullptr)
  166. {
  167. destroyClangServer (server);
  168. Logger::writeToLog ("Server shutdown cleanly");
  169. }
  170. versionChecker.reset();
  171. utf8Window.reset();
  172. svgPathWindow.reset();
  173. aboutWindow.reset();
  174. pathsWindow.reset();
  175. editorColourSchemeWindow.reset();
  176. pipCreatorWindow.reset();
  177. if (licenseController != nullptr)
  178. {
  179. licenseController->removeLicenseStatusChangedCallback (this);
  180. licenseController.reset();
  181. }
  182. mainWindowList.forceCloseAllWindows();
  183. openDocumentManager.clear();
  184. childProcessCache.reset();
  185. #if JUCE_MAC
  186. MenuBarModel::setMacMainMenu (nullptr);
  187. #endif
  188. menuModel.reset();
  189. commandManager.reset();
  190. settings.reset();
  191. LookAndFeel::setDefaultLookAndFeel (nullptr);
  192. // clean up after ourselves and delete any temp project files that may have
  193. // been created from PIPs
  194. deleteTemporaryFiles();
  195. if (! isRunningCommandLine)
  196. Logger::writeToLog ("Shutdown");
  197. deleteLogger();
  198. Analytics::getInstance()->logEvent ("Shutdown", {}, ProjucerAnalyticsEvent::appEvent);
  199. }
  200. struct AsyncQuitRetrier : private Timer
  201. {
  202. AsyncQuitRetrier() { startTimer (500); }
  203. void timerCallback() override
  204. {
  205. stopTimer();
  206. delete this;
  207. if (auto* app = JUCEApplicationBase::getInstance())
  208. app->systemRequestedQuit();
  209. }
  210. JUCE_DECLARE_NON_COPYABLE (AsyncQuitRetrier)
  211. };
  212. void ProjucerApplication::systemRequestedQuit()
  213. {
  214. if (server != nullptr)
  215. {
  216. sendQuitMessageToIDE (server);
  217. }
  218. else if (ModalComponentManager::getInstance()->cancelAllModalComponents())
  219. {
  220. new AsyncQuitRetrier();
  221. }
  222. else
  223. {
  224. if (closeAllMainWindows())
  225. quit();
  226. }
  227. }
  228. //==============================================================================
  229. void ProjucerApplication::licenseStateChanged (const LicenseState& state)
  230. {
  231. #if ! JUCER_ENABLE_GPL_MODE
  232. if (state.type != LicenseState::Type::notLoggedIn
  233. && state.type != LicenseState::Type::noLicenseChosenYet)
  234. #else
  235. ignoreUnused (state);
  236. #endif
  237. {
  238. initialiseWindows (getCommandLineParameters());
  239. }
  240. }
  241. void ProjucerApplication::doLogout()
  242. {
  243. if (licenseController != nullptr)
  244. {
  245. const LicenseState& state = licenseController->getState();
  246. if (state.type != LicenseState::Type::notLoggedIn && closeAllMainWindows())
  247. licenseController->logout();
  248. }
  249. }
  250. //==============================================================================
  251. String ProjucerApplication::getVersionDescription() const
  252. {
  253. String s;
  254. const Time buildDate (Time::getCompilationDate());
  255. s << "Projucer " << ProjectInfo::versionString
  256. << newLine
  257. << "Build date: " << buildDate.getDayOfMonth()
  258. << " " << Time::getMonthName (buildDate.getMonth(), true)
  259. << " " << buildDate.getYear();
  260. return s;
  261. }
  262. void ProjucerApplication::anotherInstanceStarted (const String& commandLine)
  263. {
  264. if (server == nullptr && ! commandLine.trim().startsWithChar ('-'))
  265. openFile (File (commandLine.unquoted()));
  266. }
  267. ProjucerApplication& ProjucerApplication::getApp()
  268. {
  269. ProjucerApplication* const app = dynamic_cast<ProjucerApplication*> (JUCEApplication::getInstance());
  270. jassert (app != nullptr);
  271. return *app;
  272. }
  273. ApplicationCommandManager& ProjucerApplication::getCommandManager()
  274. {
  275. auto* cm = ProjucerApplication::getApp().commandManager.get();
  276. jassert (cm != nullptr);
  277. return *cm;
  278. }
  279. //==============================================================================
  280. enum
  281. {
  282. recentProjectsBaseID = 100,
  283. openWindowsBaseID = 300,
  284. activeDocumentsBaseID = 400,
  285. colourSchemeBaseID = 1000,
  286. codeEditorColourSchemeBaseID = 1500,
  287. showPathsID = 1999,
  288. examplesBaseID = 2000
  289. };
  290. MenuBarModel* ProjucerApplication::getMenuModel()
  291. {
  292. return menuModel.get();
  293. }
  294. StringArray ProjucerApplication::getMenuNames()
  295. {
  296. return { "File", "Edit", "View", "Build", "Window", "Document", "GUI Editor", "Tools", "Help" };
  297. }
  298. void ProjucerApplication::createMenu (PopupMenu& menu, const String& menuName)
  299. {
  300. if (menuName == "File") createFileMenu (menu);
  301. else if (menuName == "Edit") createEditMenu (menu);
  302. else if (menuName == "View") createViewMenu (menu);
  303. else if (menuName == "Build") createBuildMenu (menu);
  304. else if (menuName == "Window") createWindowMenu (menu);
  305. else if (menuName == "Document") createDocumentMenu (menu);
  306. else if (menuName == "Tools") createToolsMenu (menu);
  307. else if (menuName == "Help") createHelpMenu (menu);
  308. else if (menuName == "GUI Editor") createGUIEditorMenu (menu);
  309. else jassertfalse; // names have changed?
  310. }
  311. void ProjucerApplication::createFileMenu (PopupMenu& menu)
  312. {
  313. menu.addCommandItem (commandManager.get(), CommandIDs::newProject);
  314. menu.addCommandItem (commandManager.get(), CommandIDs::newProjectFromClipboard);
  315. menu.addCommandItem (commandManager.get(), CommandIDs::newPIP);
  316. menu.addSeparator();
  317. menu.addCommandItem (commandManager.get(), CommandIDs::open);
  318. {
  319. PopupMenu recentFiles;
  320. settings->recentFiles.createPopupMenuItems (recentFiles, recentProjectsBaseID, true, true);
  321. if (recentFiles.getNumItems() > 0)
  322. {
  323. recentFiles.addSeparator();
  324. recentFiles.addCommandItem (commandManager.get(), CommandIDs::clearRecentFiles);
  325. }
  326. menu.addSubMenu ("Open Recent", recentFiles);
  327. }
  328. {
  329. PopupMenu examples;
  330. createExamplesPopupMenu (examples);
  331. menu.addSubMenu ("Open Example", examples);
  332. }
  333. menu.addSeparator();
  334. menu.addCommandItem (commandManager.get(), CommandIDs::closeDocument);
  335. menu.addCommandItem (commandManager.get(), CommandIDs::saveDocument);
  336. menu.addCommandItem (commandManager.get(), CommandIDs::saveDocumentAs);
  337. menu.addCommandItem (commandManager.get(), CommandIDs::saveAll);
  338. menu.addSeparator();
  339. menu.addCommandItem (commandManager.get(), CommandIDs::closeProject);
  340. menu.addCommandItem (commandManager.get(), CommandIDs::saveProject);
  341. menu.addSeparator();
  342. menu.addCommandItem (commandManager.get(), CommandIDs::openInIDE);
  343. menu.addCommandItem (commandManager.get(), CommandIDs::saveAndOpenInIDE);
  344. menu.addSeparator();
  345. #if ! JUCER_ENABLE_GPL_MODE
  346. menu.addCommandItem (commandManager.get(), CommandIDs::loginLogout);
  347. #endif
  348. #if ! JUCE_MAC
  349. menu.addCommandItem (commandManager.get(), CommandIDs::showAboutWindow);
  350. menu.addCommandItem (commandManager.get(), CommandIDs::showAppUsageWindow);
  351. menu.addCommandItem (commandManager.get(), CommandIDs::showGlobalPathsWindow);
  352. menu.addSeparator();
  353. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::quit);
  354. #endif
  355. }
  356. void ProjucerApplication::createEditMenu (PopupMenu& menu)
  357. {
  358. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::undo);
  359. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::redo);
  360. menu.addSeparator();
  361. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::cut);
  362. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::copy);
  363. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::paste);
  364. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::del);
  365. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::selectAll);
  366. menu.addCommandItem (commandManager.get(), StandardApplicationCommandIDs::deselectAll);
  367. menu.addSeparator();
  368. menu.addCommandItem (commandManager.get(), CommandIDs::showFindPanel);
  369. menu.addCommandItem (commandManager.get(), CommandIDs::findSelection);
  370. menu.addCommandItem (commandManager.get(), CommandIDs::findNext);
  371. menu.addCommandItem (commandManager.get(), CommandIDs::findPrevious);
  372. }
  373. void ProjucerApplication::createViewMenu (PopupMenu& menu)
  374. {
  375. menu.addCommandItem (commandManager.get(), CommandIDs::showProjectSettings);
  376. menu.addCommandItem (commandManager.get(), CommandIDs::showProjectTab);
  377. menu.addCommandItem (commandManager.get(), CommandIDs::showBuildTab);
  378. menu.addCommandItem (commandManager.get(), CommandIDs::showFileExplorerPanel);
  379. menu.addCommandItem (commandManager.get(), CommandIDs::showModulesPanel);
  380. menu.addCommandItem (commandManager.get(), CommandIDs::showExportersPanel);
  381. menu.addCommandItem (commandManager.get(), CommandIDs::showExporterSettings);
  382. menu.addSeparator();
  383. createColourSchemeItems (menu);
  384. }
  385. void ProjucerApplication::createBuildMenu (PopupMenu& menu)
  386. {
  387. menu.addCommandItem (commandManager.get(), CommandIDs::toggleBuildEnabled);
  388. menu.addCommandItem (commandManager.get(), CommandIDs::buildNow);
  389. menu.addCommandItem (commandManager.get(), CommandIDs::toggleContinuousBuild);
  390. menu.addSeparator();
  391. menu.addCommandItem (commandManager.get(), CommandIDs::launchApp);
  392. menu.addCommandItem (commandManager.get(), CommandIDs::killApp);
  393. menu.addCommandItem (commandManager.get(), CommandIDs::cleanAll);
  394. menu.addSeparator();
  395. menu.addCommandItem (commandManager.get(), CommandIDs::reinstantiateComp);
  396. menu.addCommandItem (commandManager.get(), CommandIDs::showWarnings);
  397. menu.addSeparator();
  398. menu.addCommandItem (commandManager.get(), CommandIDs::nextError);
  399. menu.addCommandItem (commandManager.get(), CommandIDs::prevError);
  400. }
  401. void ProjucerApplication::createColourSchemeItems (PopupMenu& menu)
  402. {
  403. PopupMenu colourSchemes;
  404. colourSchemes.addItem (colourSchemeBaseID + 0, "Dark", true, selectedColourSchemeIndex == 0);
  405. colourSchemes.addItem (colourSchemeBaseID + 1, "Grey", true, selectedColourSchemeIndex == 1);
  406. colourSchemes.addItem (colourSchemeBaseID + 2, "Light", true, selectedColourSchemeIndex == 2);
  407. menu.addSubMenu ("Colour Scheme", colourSchemes);
  408. //==========================================================================
  409. PopupMenu editorColourSchemes;
  410. auto& appearanceSettings = getAppSettings().appearance;
  411. appearanceSettings.refreshPresetSchemeList();
  412. auto schemes = appearanceSettings.getPresetSchemes();
  413. auto i = 0;
  414. for (auto s : schemes)
  415. {
  416. editorColourSchemes.addItem (codeEditorColourSchemeBaseID + i, s,
  417. editorColourSchemeWindow == nullptr,
  418. selectedEditorColourSchemeIndex == i);
  419. ++i;
  420. }
  421. numEditorColourSchemes = i;
  422. editorColourSchemes.addSeparator();
  423. editorColourSchemes.addItem (codeEditorColourSchemeBaseID + numEditorColourSchemes,
  424. "Create...", editorColourSchemeWindow == nullptr);
  425. menu.addSubMenu ("Editor Colour Scheme", editorColourSchemes);
  426. }
  427. void ProjucerApplication::createWindowMenu (PopupMenu& menu)
  428. {
  429. menu.addCommandItem (commandManager.get(), CommandIDs::goToPreviousWindow);
  430. menu.addCommandItem (commandManager.get(), CommandIDs::goToNextWindow);
  431. menu.addCommandItem (commandManager.get(), CommandIDs::closeWindow);
  432. menu.addSeparator();
  433. int counter = 0;
  434. for (auto* window : mainWindowList.windows)
  435. {
  436. if (window != nullptr)
  437. {
  438. if (auto* project = window->getProject())
  439. menu.addItem (openWindowsBaseID + counter++, project->getProjectNameString());
  440. }
  441. }
  442. menu.addSeparator();
  443. menu.addCommandItem (commandManager.get(), CommandIDs::closeAllWindows);
  444. }
  445. void ProjucerApplication::createDocumentMenu (PopupMenu& menu)
  446. {
  447. menu.addCommandItem (commandManager.get(), CommandIDs::goToPreviousDoc);
  448. menu.addCommandItem (commandManager.get(), CommandIDs::goToNextDoc);
  449. menu.addCommandItem (commandManager.get(), CommandIDs::goToCounterpart);
  450. menu.addSeparator();
  451. auto numDocs = jmin (50, openDocumentManager.getNumOpenDocuments());
  452. for (int i = 0; i < numDocs; ++i)
  453. {
  454. OpenDocumentManager::Document* doc = openDocumentManager.getOpenDocument(i);
  455. menu.addItem (activeDocumentsBaseID + i, doc->getName());
  456. }
  457. menu.addSeparator();
  458. menu.addCommandItem (commandManager.get(), CommandIDs::closeAllDocuments);
  459. }
  460. void ProjucerApplication::createToolsMenu (PopupMenu& menu)
  461. {
  462. menu.addCommandItem (commandManager.get(), CommandIDs::showUTF8Tool);
  463. menu.addCommandItem (commandManager.get(), CommandIDs::showSVGPathTool);
  464. menu.addCommandItem (commandManager.get(), CommandIDs::showTranslationTool);
  465. }
  466. void ProjucerApplication::createHelpMenu (PopupMenu& menu)
  467. {
  468. menu.addCommandItem (commandManager.get(), CommandIDs::showForum);
  469. menu.addSeparator();
  470. menu.addCommandItem (commandManager.get(), CommandIDs::showAPIModules);
  471. menu.addCommandItem (commandManager.get(), CommandIDs::showAPIClasses);
  472. menu.addCommandItem (commandManager.get(), CommandIDs::showTutorials);
  473. }
  474. void ProjucerApplication::createExtraAppleMenuItems (PopupMenu& menu)
  475. {
  476. menu.addCommandItem (commandManager.get(), CommandIDs::showAboutWindow);
  477. menu.addCommandItem (commandManager.get(), CommandIDs::showAppUsageWindow);
  478. menu.addSeparator();
  479. menu.addCommandItem (commandManager.get(), CommandIDs::showGlobalPathsWindow);
  480. }
  481. void ProjucerApplication::createExamplesPopupMenu (PopupMenu& menu) noexcept
  482. {
  483. numExamples = 0;
  484. for (auto& dir : getSortedExampleDirectories())
  485. {
  486. PopupMenu m;
  487. for (auto& f : getSortedExampleFilesInDirectory (dir))
  488. {
  489. m.addItem (examplesBaseID + numExamples, f.getFileNameWithoutExtension());
  490. ++numExamples;
  491. }
  492. menu.addSubMenu (dir.getFileName(), m);
  493. }
  494. if (numExamples == 0)
  495. {
  496. menu.addItem (showPathsID, "Set path to JUCE...");
  497. }
  498. else
  499. {
  500. menu.addSeparator();
  501. menu.addCommandItem (commandManager.get(), CommandIDs::launchDemoRunner);
  502. }
  503. }
  504. //==========================================================================
  505. static File getJUCEExamplesDirectoryPathFromGlobal()
  506. {
  507. auto globalPath = File::createFileWithoutCheckingPath (getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get().toString()
  508. .replace ("~", File::getSpecialLocation (File::userHomeDirectory).getFullPathName()));
  509. if (globalPath.exists())
  510. return File (globalPath).getChildFile ("examples");
  511. return {};
  512. }
  513. Array<File> ProjucerApplication::getSortedExampleDirectories() noexcept
  514. {
  515. Array<File> exampleDirectories;
  516. auto examplesPath = getJUCEExamplesDirectoryPathFromGlobal();
  517. if (! isValidJUCEExamplesDirectory (examplesPath))
  518. return {};
  519. DirectoryIterator iter (examplesPath, false, "*", File::findDirectories);
  520. while (iter.next())
  521. {
  522. auto exampleDirectory = iter.getFile();
  523. if (exampleDirectory.getNumberOfChildFiles (File::findFiles | File::ignoreHiddenFiles) > 0
  524. && exampleDirectory.getFileName() != "DemoRunner" && exampleDirectory.getFileName() != "Assets")
  525. exampleDirectories.add (exampleDirectory);
  526. }
  527. exampleDirectories.sort();
  528. return exampleDirectories;
  529. }
  530. Array<File> ProjucerApplication::getSortedExampleFilesInDirectory (const File& directory) const noexcept
  531. {
  532. Array<File> exampleFiles;
  533. DirectoryIterator iter (directory, false, "*.h", File::findFiles);
  534. while (iter.next())
  535. exampleFiles.add (iter.getFile());
  536. exampleFiles.sort();
  537. return exampleFiles;
  538. }
  539. bool ProjucerApplication::findWindowAndOpenPIP (const File& pip)
  540. {
  541. auto* window = mainWindowList.getFrontmostWindow();
  542. bool shouldCloseWindow = false;
  543. if (window == nullptr)
  544. {
  545. window = mainWindowList.getOrCreateEmptyWindow();
  546. shouldCloseWindow = true;
  547. }
  548. if (window->tryToOpenPIP (pip))
  549. return true;
  550. if (shouldCloseWindow)
  551. mainWindowList.closeWindow (window);
  552. return false;
  553. }
  554. void ProjucerApplication::findAndLaunchExample (int selectedIndex)
  555. {
  556. File example;
  557. for (auto& dir : getSortedExampleDirectories())
  558. {
  559. auto exampleFiles = getSortedExampleFilesInDirectory (dir);
  560. if (selectedIndex < exampleFiles.size())
  561. {
  562. example = exampleFiles.getUnchecked (selectedIndex);
  563. break;
  564. }
  565. selectedIndex -= exampleFiles.size();
  566. }
  567. // example doesn't exist?
  568. jassert (example != File());
  569. findWindowAndOpenPIP (example);
  570. StringPairArray data;
  571. data.set ("label", example.getFileNameWithoutExtension());
  572. Analytics::getInstance()->logEvent ("Example Opened", data, ProjucerAnalyticsEvent::exampleEvent);
  573. }
  574. //==========================================================================
  575. static String getPlatformSpecificFileExtension()
  576. {
  577. #if JUCE_MAC
  578. return ".app";
  579. #elif JUCE_WINDOWS
  580. return ".exe";
  581. #elif JUCE_LINUX
  582. return {};
  583. #endif
  584. jassertfalse;
  585. return {};
  586. }
  587. static File getPlatformSpecificProjectFolder()
  588. {
  589. auto buildsFolder = getJUCEExamplesDirectoryPathFromGlobal().getChildFile ("DemoRunner").getChildFile ("Builds");
  590. if (! buildsFolder.exists())
  591. return {};
  592. #if JUCE_MAC
  593. return buildsFolder.getChildFile ("MacOSX");
  594. #elif JUCE_WINDOWS
  595. return buildsFolder.getChildFile ("VisualStudio2017");
  596. #elif JUCE_LINUX
  597. return buildsFolder.getChildFile ("LinuxMakefile");
  598. #endif
  599. jassertfalse;
  600. return {};
  601. }
  602. static File tryToFindDemoRunnerExecutableInBuilds()
  603. {
  604. auto projectFolder = getPlatformSpecificProjectFolder();
  605. #if JUCE_MAC
  606. projectFolder = projectFolder.getChildFile ("build");
  607. auto demoRunnerExecutable = projectFolder.getChildFile ("Release").getChildFile ("DemoRunner.app");
  608. if (demoRunnerExecutable.exists())
  609. return demoRunnerExecutable;
  610. demoRunnerExecutable = projectFolder.getChildFile ("Debug").getChildFile ("DemoRunner.app");
  611. if (demoRunnerExecutable.exists())
  612. return demoRunnerExecutable;
  613. #elif JUCE_WINDOWS
  614. projectFolder = projectFolder.getChildFile ("x64");
  615. auto demoRunnerExecutable = projectFolder.getChildFile ("Release").getChildFile ("App").getChildFile ("DemoRunner.exe");
  616. if (demoRunnerExecutable.existsAsFile())
  617. return demoRunnerExecutable;
  618. demoRunnerExecutable = projectFolder.getChildFile ("Debug").getChildFile ("App").getChildFile ("DemoRunner.exe");
  619. if (demoRunnerExecutable.existsAsFile())
  620. return demoRunnerExecutable;
  621. #elif JUCE_LINUX
  622. projectFolder = projectFolder.getChildFile ("LinuxMakefile").getChildFile ("build");
  623. auto demoRunnerExecutable = projectFolder.getChildFile ("DemoRunner");
  624. if (demoRunnerExecutable.existsAsFile())
  625. return demoRunnerExecutable;
  626. #endif
  627. return {};
  628. }
  629. static File tryToFindPrebuiltDemoRunnerExecutable()
  630. {
  631. auto prebuiltFile = File (getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get().toString())
  632. .getChildFile ("DemoRunner" + getPlatformSpecificFileExtension());
  633. #if JUCE_MAC
  634. if (prebuiltFile.exists())
  635. #else
  636. if (prebuiltFile.existsAsFile())
  637. #endif
  638. return prebuiltFile;
  639. return {};
  640. }
  641. void ProjucerApplication::checkIfGlobalJUCEPathHasChanged()
  642. {
  643. auto globalJUCEPath = File (getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get());
  644. if (lastJUCEPath != globalJUCEPath)
  645. {
  646. hasScannedForDemoRunnerProject = false;
  647. hasScannedForDemoRunnerExecutable = false;
  648. lastJUCEPath = globalJUCEPath;
  649. }
  650. }
  651. File ProjucerApplication::tryToFindDemoRunnerExecutable()
  652. {
  653. checkIfGlobalJUCEPathHasChanged();
  654. if (hasScannedForDemoRunnerExecutable)
  655. return lastDemoRunnerExectuableFile;
  656. auto demoRunnerExecutable = tryToFindDemoRunnerExecutableInBuilds();
  657. if (demoRunnerExecutable == File())
  658. demoRunnerExecutable = tryToFindPrebuiltDemoRunnerExecutable();
  659. hasScannedForDemoRunnerExecutable = true;
  660. lastDemoRunnerExectuableFile = demoRunnerExecutable;
  661. return demoRunnerExecutable;
  662. }
  663. File ProjucerApplication::tryToFindDemoRunnerProject()
  664. {
  665. checkIfGlobalJUCEPathHasChanged();
  666. if (hasScannedForDemoRunnerProject)
  667. return lastDemoRunnerProjectFile;
  668. auto projectFolder = getPlatformSpecificProjectFolder();
  669. #if JUCE_MAC
  670. auto demoRunnerProjectFile = projectFolder.getChildFile ("DemoRunner.xcodeproj");
  671. #elif JUCE_WINDOWS
  672. auto demoRunnerProjectFile = projectFolder.getChildFile ("DemoRunner.sln");
  673. #elif JUCE_LINUX
  674. auto demoRunnerProjectFile = projectFolder.getChildFile ("Makefile");
  675. #endif
  676. #if JUCE_MAC
  677. if (! demoRunnerProjectFile.exists())
  678. #else
  679. if (! demoRunnerProjectFile.existsAsFile())
  680. #endif
  681. demoRunnerProjectFile = File();
  682. hasScannedForDemoRunnerProject = true;
  683. lastDemoRunnerProjectFile = demoRunnerProjectFile;
  684. return demoRunnerProjectFile;
  685. }
  686. void ProjucerApplication::launchDemoRunner()
  687. {
  688. auto demoRunnerFile = tryToFindDemoRunnerExecutable();
  689. if (demoRunnerFile != File())
  690. {
  691. auto succeeded = demoRunnerFile.startAsProcess();
  692. StringPairArray data;
  693. data.set ("label", succeeded ? "Success" : "Failure");
  694. Analytics::getInstance()->logEvent ("Launch DemoRunner", data, ProjucerAnalyticsEvent::exampleEvent);
  695. if (succeeded)
  696. return;
  697. }
  698. demoRunnerFile = tryToFindDemoRunnerProject();
  699. if (demoRunnerFile != File())
  700. {
  701. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  702. demoRunnerAlert.reset (lf.createAlertWindow ("Open Project",
  703. "Couldn't find a compiled version of the Demo Runner."
  704. #if JUCE_LINUX
  705. " Do you want to build it now?", "Build project", "Cancel",
  706. #else
  707. " Do you want to open the project?", "Open project", "Cancel",
  708. #endif
  709. {},
  710. AlertWindow::QuestionIcon, 2,
  711. mainWindowList.getFrontmostWindow (false)));
  712. demoRunnerAlert->enterModalState (true, ModalCallbackFunction::create ([this, demoRunnerFile] (int retVal)
  713. {
  714. demoRunnerAlert.reset (nullptr);
  715. StringPairArray data;
  716. data.set ("label", retVal == 1 ? "Opened" : "Cancelled");
  717. Analytics::getInstance()->logEvent ("Open DemoRunner Project", data, ProjucerAnalyticsEvent::exampleEvent);
  718. if (retVal == 1)
  719. {
  720. #if JUCE_LINUX
  721. String command ("make -C " + demoRunnerFile.getParentDirectory().getFullPathName() + " CONFIG=Release -j3");
  722. if (! makeProcess.start (command))
  723. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Error", "Error building Demo Runner.");
  724. #else
  725. demoRunnerFile.startAsProcess();
  726. #endif
  727. }
  728. }), false);
  729. }
  730. }
  731. //==========================================================================
  732. void ProjucerApplication::handleMainMenuCommand (int menuItemID)
  733. {
  734. if (menuItemID >= recentProjectsBaseID && menuItemID < (recentProjectsBaseID + 100))
  735. {
  736. // open a file from the "recent files" menu
  737. openFile (settings->recentFiles.getFile (menuItemID - recentProjectsBaseID));
  738. }
  739. else if (menuItemID >= openWindowsBaseID && menuItemID < (openWindowsBaseID + 100))
  740. {
  741. if (auto* window = mainWindowList.windows.getUnchecked (menuItemID - openWindowsBaseID))
  742. window->toFront (true);
  743. }
  744. else if (menuItemID >= activeDocumentsBaseID && menuItemID < (activeDocumentsBaseID + 200))
  745. {
  746. if (auto* doc = openDocumentManager.getOpenDocument (menuItemID - activeDocumentsBaseID))
  747. mainWindowList.openDocument (doc, true);
  748. else
  749. jassertfalse;
  750. }
  751. else if (menuItemID >= colourSchemeBaseID && menuItemID < (colourSchemeBaseID + 3))
  752. {
  753. setColourScheme (menuItemID - colourSchemeBaseID, true);
  754. updateEditorColourSchemeIfNeeded();
  755. }
  756. else if (menuItemID >= codeEditorColourSchemeBaseID && menuItemID < (codeEditorColourSchemeBaseID + numEditorColourSchemes))
  757. {
  758. setEditorColourScheme (menuItemID - codeEditorColourSchemeBaseID, true);
  759. }
  760. else if (menuItemID == (codeEditorColourSchemeBaseID + numEditorColourSchemes))
  761. {
  762. showEditorColourSchemeWindow();
  763. }
  764. else if (menuItemID == showPathsID)
  765. {
  766. showPathsWindow (true);
  767. }
  768. else if (menuItemID >= examplesBaseID && menuItemID < (examplesBaseID + numExamples))
  769. {
  770. findAndLaunchExample (menuItemID - examplesBaseID);
  771. }
  772. else
  773. {
  774. handleGUIEditorMenuCommand (menuItemID);
  775. }
  776. }
  777. //==============================================================================
  778. void ProjucerApplication::getAllCommands (Array <CommandID>& commands)
  779. {
  780. JUCEApplication::getAllCommands (commands);
  781. const CommandID ids[] = { CommandIDs::newProject,
  782. CommandIDs::newProjectFromClipboard,
  783. CommandIDs::newPIP,
  784. CommandIDs::open,
  785. CommandIDs::launchDemoRunner,
  786. CommandIDs::closeAllWindows,
  787. CommandIDs::closeAllDocuments,
  788. CommandIDs::clearRecentFiles,
  789. CommandIDs::saveAll,
  790. CommandIDs::showGlobalPathsWindow,
  791. CommandIDs::showUTF8Tool,
  792. CommandIDs::showSVGPathTool,
  793. CommandIDs::showAboutWindow,
  794. CommandIDs::showAppUsageWindow,
  795. CommandIDs::showForum,
  796. CommandIDs::showAPIModules,
  797. CommandIDs::showAPIClasses,
  798. CommandIDs::showTutorials,
  799. CommandIDs::loginLogout };
  800. commands.addArray (ids, numElementsInArray (ids));
  801. }
  802. void ProjucerApplication::getCommandInfo (CommandID commandID, ApplicationCommandInfo& result)
  803. {
  804. switch (commandID)
  805. {
  806. case CommandIDs::newProject:
  807. result.setInfo ("New Project...", "Creates a new JUCE project", CommandCategories::general, 0);
  808. result.defaultKeypresses.add (KeyPress ('n', ModifierKeys::commandModifier, 0));
  809. break;
  810. case CommandIDs::newProjectFromClipboard:
  811. result.setInfo ("New Project From Clipboard...", "Creates a new JUCE project from the clipboard contents", CommandCategories::general, 0);
  812. result.defaultKeypresses.add (KeyPress ('n', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0));
  813. break;
  814. case CommandIDs::newPIP:
  815. result.setInfo ("New PIP...", "Opens the PIP Creator utility for creating a new PIP", CommandCategories::general, 0);
  816. result.defaultKeypresses.add (KeyPress ('p', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0));
  817. break;
  818. case CommandIDs::launchDemoRunner:
  819. #if JUCE_LINUX
  820. if (makeProcess.isRunning())
  821. {
  822. result.setInfo ("Building Demo Runner...", "The Demo Runner project is currently building", CommandCategories::general, 0);
  823. result.setActive (false);
  824. }
  825. else
  826. #endif
  827. {
  828. result.setInfo ("Launch Demo Runner", "Launches the JUCE demo runner application, or the project if it can't be found", CommandCategories::general, 0);
  829. result.setActive (tryToFindDemoRunnerExecutable() != File() || tryToFindDemoRunnerProject() != File());
  830. }
  831. break;
  832. case CommandIDs::open:
  833. result.setInfo ("Open...", "Opens a JUCE project", CommandCategories::general, 0);
  834. result.defaultKeypresses.add (KeyPress ('o', ModifierKeys::commandModifier, 0));
  835. break;
  836. case CommandIDs::showGlobalPathsWindow:
  837. result.setInfo ("Global Paths...",
  838. "Shows the window to change the stored global paths.",
  839. CommandCategories::general, 0);
  840. break;
  841. case CommandIDs::closeAllWindows:
  842. result.setInfo ("Close All Windows", "Closes all open windows", CommandCategories::general, 0);
  843. result.setActive (mainWindowList.windows.size() > 0);
  844. break;
  845. case CommandIDs::closeAllDocuments:
  846. result.setInfo ("Close All Documents", "Closes all open documents", CommandCategories::general, 0);
  847. result.setActive (openDocumentManager.getNumOpenDocuments() > 0);
  848. break;
  849. case CommandIDs::clearRecentFiles:
  850. result.setInfo ("Clear Recent Files", "Clears all recent files from the menu", CommandCategories::general, 0);
  851. result.setActive (settings->recentFiles.getNumFiles() > 0);
  852. break;
  853. case CommandIDs::saveAll:
  854. result.setInfo ("Save All", "Saves all open documents", CommandCategories::general, 0);
  855. result.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier | ModifierKeys::altModifier, 0));
  856. break;
  857. case CommandIDs::showUTF8Tool:
  858. result.setInfo ("UTF-8 String-Literal Helper", "Shows the UTF-8 string literal utility", CommandCategories::general, 0);
  859. break;
  860. case CommandIDs::showSVGPathTool:
  861. result.setInfo ("SVG Path Converter", "Shows the SVG->Path data conversion utility", CommandCategories::general, 0);
  862. break;
  863. case CommandIDs::showAboutWindow:
  864. result.setInfo ("About Projucer", "Shows the Projucer's 'About' page.", CommandCategories::general, 0);
  865. break;
  866. case CommandIDs::showAppUsageWindow:
  867. result.setInfo ("Application Usage Data", "Shows the application usage data agreement window", CommandCategories::general, 0);
  868. break;
  869. case CommandIDs::showForum:
  870. result.setInfo ("JUCE Community Forum", "Shows the JUCE community forum in a browser", CommandCategories::general, 0);
  871. break;
  872. case CommandIDs::showAPIModules:
  873. result.setInfo ("API Modules", "Shows the API modules documentation in a browser", CommandCategories::general, 0);
  874. break;
  875. case CommandIDs::showAPIClasses:
  876. result.setInfo ("API Classes", "Shows the API classes documentation in a browser", CommandCategories::general, 0);
  877. break;
  878. case CommandIDs::showTutorials:
  879. result.setInfo ("JUCE Tutorials", "Shows the JUCE tutorials in a browser", CommandCategories::general, 0);
  880. break;
  881. case CommandIDs::loginLogout:
  882. {
  883. bool isLoggedIn = false;
  884. String username;
  885. if (licenseController != nullptr)
  886. {
  887. const LicenseState state = licenseController->getState();
  888. isLoggedIn = (state.type != LicenseState::Type::notLoggedIn && state.type != LicenseState::Type::GPL);
  889. username = state.username;
  890. }
  891. result.setInfo (isLoggedIn
  892. ? String ("Sign out ") + username + "..."
  893. : String ("Sign in..."),
  894. "Log out of your JUCE account", CommandCategories::general, 0);
  895. }
  896. break;
  897. default:
  898. JUCEApplication::getCommandInfo (commandID, result);
  899. break;
  900. }
  901. }
  902. bool ProjucerApplication::perform (const InvocationInfo& info)
  903. {
  904. switch (info.commandID)
  905. {
  906. case CommandIDs::newProject: createNewProject(); break;
  907. case CommandIDs::newProjectFromClipboard: createNewProjectFromClipboard(); break;
  908. case CommandIDs::newPIP: createNewPIP(); break;
  909. case CommandIDs::open: askUserToOpenFile(); break;
  910. case CommandIDs::launchDemoRunner: launchDemoRunner(); break;
  911. case CommandIDs::saveAll: saveAllDocuments(); break;
  912. case CommandIDs::closeAllWindows: closeAllMainWindowsAndQuitIfNeeded(); break;
  913. case CommandIDs::closeAllDocuments: closeAllDocuments (true); break;
  914. case CommandIDs::clearRecentFiles: clearRecentFiles(); break;
  915. case CommandIDs::showUTF8Tool: showUTF8ToolWindow(); break;
  916. case CommandIDs::showSVGPathTool: showSVGPathDataToolWindow(); break;
  917. case CommandIDs::showGlobalPathsWindow: showPathsWindow (false); break;
  918. case CommandIDs::showAboutWindow: showAboutWindow(); break;
  919. case CommandIDs::showAppUsageWindow: showApplicationUsageDataAgreementPopup(); break;
  920. case CommandIDs::showForum: launchForumBrowser(); break;
  921. case CommandIDs::showAPIModules: launchModulesBrowser(); break;
  922. case CommandIDs::showAPIClasses: launchClassesBrowser(); break;
  923. case CommandIDs::showTutorials: launchTutorialsBrowser(); break;
  924. case CommandIDs::loginLogout: doLogout(); break;
  925. default: return JUCEApplication::perform (info);
  926. }
  927. return true;
  928. }
  929. //==============================================================================
  930. void ProjucerApplication::createNewProject()
  931. {
  932. auto* mw = mainWindowList.getOrCreateEmptyWindow();
  933. mw->showStartPage();
  934. mainWindowList.avoidSuperimposedWindows (mw);
  935. }
  936. void ProjucerApplication::createNewProjectFromClipboard()
  937. {
  938. auto tempFile = File::getSpecialLocation (File::SpecialLocationType::tempDirectory).getChildFile ("PIPs").getChildFile ("Clipboard")
  939. .getChildFile ("PIPFile_" + String (std::abs (Random::getSystemRandom().nextInt())) + ".h");
  940. if (tempFile.existsAsFile())
  941. tempFile.deleteFile();
  942. tempFile.create();
  943. tempFile.appendText (SystemClipboard::getTextFromClipboard());
  944. if (! findWindowAndOpenPIP (tempFile))
  945. {
  946. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Error", "Couldn't create project from clipboard contents.");
  947. tempFile.deleteFile();
  948. }
  949. }
  950. void ProjucerApplication::createNewPIP()
  951. {
  952. showPIPCreatorWindow();
  953. }
  954. void ProjucerApplication::askUserToOpenFile()
  955. {
  956. FileChooser fc ("Open File");
  957. if (fc.browseForFileToOpen())
  958. openFile (fc.getResult());
  959. }
  960. bool ProjucerApplication::openFile (const File& file)
  961. {
  962. return mainWindowList.openFile (file);
  963. }
  964. void ProjucerApplication::saveAllDocuments()
  965. {
  966. openDocumentManager.saveAll();
  967. for (int i = 0; i < mainWindowList.windows.size(); ++i)
  968. if (auto* pcc = mainWindowList.windows.getUnchecked(i)->getProjectContentComponent())
  969. pcc->refreshProjectTreeFileStatuses();
  970. }
  971. bool ProjucerApplication::closeAllDocuments (bool askUserToSave)
  972. {
  973. return openDocumentManager.closeAll (askUserToSave);
  974. }
  975. bool ProjucerApplication::closeAllMainWindows()
  976. {
  977. return server != nullptr || mainWindowList.askAllWindowsToClose();
  978. }
  979. void ProjucerApplication::closeAllMainWindowsAndQuitIfNeeded()
  980. {
  981. if (closeAllMainWindows())
  982. {
  983. #if ! JUCE_MAC
  984. if (mainWindowList.windows.size() == 0)
  985. systemRequestedQuit();
  986. #endif
  987. }
  988. }
  989. void ProjucerApplication::clearRecentFiles()
  990. {
  991. settings->recentFiles.clear();
  992. settings->recentFiles.clearRecentFilesNatively();
  993. settings->flush();
  994. menuModel->menuItemsChanged();
  995. }
  996. //==============================================================================
  997. void ProjucerApplication::showUTF8ToolWindow()
  998. {
  999. if (utf8Window != nullptr)
  1000. utf8Window->toFront (true);
  1001. else
  1002. new FloatingToolWindow ("UTF-8 String Literal Converter", "utf8WindowPos",
  1003. new UTF8Component(), utf8Window, true,
  1004. 500, 500, 300, 300, 1000, 1000);
  1005. }
  1006. void ProjucerApplication::showSVGPathDataToolWindow()
  1007. {
  1008. if (svgPathWindow != nullptr)
  1009. svgPathWindow->toFront (true);
  1010. else
  1011. new FloatingToolWindow ("SVG Path Converter", "svgPathWindowPos",
  1012. new SVGPathDataComponent(), svgPathWindow, true,
  1013. 500, 500, 300, 300, 1000, 1000);
  1014. }
  1015. void ProjucerApplication::showAboutWindow()
  1016. {
  1017. if (aboutWindow != nullptr)
  1018. aboutWindow->toFront (true);
  1019. else
  1020. new FloatingToolWindow ({}, {}, new AboutWindowComponent(),
  1021. aboutWindow, false,
  1022. 500, 300, 500, 300, 500, 300);
  1023. }
  1024. void ProjucerApplication::showApplicationUsageDataAgreementPopup()
  1025. {
  1026. if (applicationUsageDataWindow != nullptr)
  1027. applicationUsageDataWindow->toFront (true);
  1028. else
  1029. new FloatingToolWindow ("Application Usage Analytics", {},
  1030. new ApplicationUsageDataWindowComponent (isPaidOrGPL()), applicationUsageDataWindow, false,
  1031. 400, 300, 400, 300, 400, 300);
  1032. }
  1033. void ProjucerApplication::dismissApplicationUsageDataAgreementPopup()
  1034. {
  1035. if (applicationUsageDataWindow != nullptr)
  1036. applicationUsageDataWindow.reset();
  1037. }
  1038. void ProjucerApplication::showPathsWindow (bool highlightJUCEPath)
  1039. {
  1040. if (pathsWindow != nullptr)
  1041. pathsWindow->toFront (true);
  1042. else
  1043. new FloatingToolWindow ("Global Paths", "pathsWindowPos",
  1044. new GlobalPathsWindowComponent(), pathsWindow, false,
  1045. 600, 650, 600, 650, 600, 650);
  1046. if (highlightJUCEPath)
  1047. if (auto* pathsComp = dynamic_cast<GlobalPathsWindowComponent*> (pathsWindow->getChildComponent (0)))
  1048. pathsComp->highlightJUCEPath();
  1049. }
  1050. void ProjucerApplication::showEditorColourSchemeWindow()
  1051. {
  1052. if (editorColourSchemeWindow != nullptr)
  1053. editorColourSchemeWindow->toFront (true);
  1054. else
  1055. new FloatingToolWindow ("Editor Colour Scheme", "editorColourSchemeWindowPos",
  1056. new EditorColourSchemeWindowComponent(), editorColourSchemeWindow, false,
  1057. 500, 500, 500, 500, 500, 500);
  1058. }
  1059. void ProjucerApplication::showPIPCreatorWindow()
  1060. {
  1061. if (pipCreatorWindow != nullptr)
  1062. pipCreatorWindow->toFront (true);
  1063. else
  1064. new FloatingToolWindow ("PIP Creator", "pipCreatorWindowPos",
  1065. new PIPCreatorWindowComponent(), pipCreatorWindow, false,
  1066. 600, 750, 600, 750, 600, 750);
  1067. }
  1068. void ProjucerApplication::launchForumBrowser()
  1069. {
  1070. URL forumLink ("https://forum.juce.com/");
  1071. if (forumLink.isWellFormed())
  1072. forumLink.launchInDefaultBrowser();
  1073. }
  1074. void ProjucerApplication::launchModulesBrowser()
  1075. {
  1076. URL modulesLink ("https://docs.juce.com/master/modules.html");
  1077. if (modulesLink.isWellFormed())
  1078. modulesLink.launchInDefaultBrowser();
  1079. }
  1080. void ProjucerApplication::launchClassesBrowser()
  1081. {
  1082. URL classesLink ("https://docs.juce.com/master/classes.html");
  1083. if (classesLink.isWellFormed())
  1084. classesLink.launchInDefaultBrowser();
  1085. }
  1086. void ProjucerApplication::launchTutorialsBrowser()
  1087. {
  1088. URL tutorialsLink ("https://juce.com/learn/tutorials");
  1089. if (tutorialsLink.isWellFormed())
  1090. tutorialsLink.launchInDefaultBrowser();
  1091. }
  1092. //==============================================================================
  1093. struct FileWithTime
  1094. {
  1095. FileWithTime (const File& f) : file (f), time (f.getLastModificationTime()) {}
  1096. FileWithTime() {}
  1097. bool operator< (const FileWithTime& other) const { return time < other.time; }
  1098. bool operator== (const FileWithTime& other) const { return time == other.time; }
  1099. File file;
  1100. Time time;
  1101. };
  1102. void ProjucerApplication::deleteLogger()
  1103. {
  1104. const int maxNumLogFilesToKeep = 50;
  1105. Logger::setCurrentLogger (nullptr);
  1106. if (logger != nullptr)
  1107. {
  1108. auto logFiles = logger->getLogFile().getParentDirectory().findChildFiles (File::findFiles, false);
  1109. if (logFiles.size() > maxNumLogFilesToKeep)
  1110. {
  1111. Array<FileWithTime> files;
  1112. for (auto& f : logFiles)
  1113. files.addUsingDefaultSort (f);
  1114. for (int i = 0; i < files.size() - maxNumLogFilesToKeep; ++i)
  1115. files.getReference(i).file.deleteFile();
  1116. }
  1117. }
  1118. logger.reset();
  1119. }
  1120. PropertiesFile::Options ProjucerApplication::getPropertyFileOptionsFor (const String& filename, bool isProjectSettings)
  1121. {
  1122. PropertiesFile::Options options;
  1123. options.applicationName = filename;
  1124. options.filenameSuffix = "settings";
  1125. options.osxLibrarySubFolder = "Application Support";
  1126. #if JUCE_LINUX
  1127. options.folderName = "~/.config/Projucer";
  1128. #else
  1129. options.folderName = "Projucer";
  1130. #endif
  1131. if (isProjectSettings)
  1132. options.folderName += "/ProjectSettings";
  1133. return options;
  1134. }
  1135. void ProjucerApplication::updateAllBuildTabs()
  1136. {
  1137. for (int i = 0; i < mainWindowList.windows.size(); ++i)
  1138. if (ProjectContentComponent* p = mainWindowList.windows.getUnchecked(i)->getProjectContentComponent())
  1139. p->rebuildProjectTabs();
  1140. }
  1141. void ProjucerApplication::initCommandManager()
  1142. {
  1143. commandManager.reset (new ApplicationCommandManager());
  1144. commandManager->registerAllCommandsForTarget (this);
  1145. {
  1146. CodeDocument doc;
  1147. CppCodeEditorComponent ed (File(), doc);
  1148. commandManager->registerAllCommandsForTarget (&ed);
  1149. }
  1150. registerGUIEditorCommands();
  1151. }
  1152. void ProjucerApplication::setAnalyticsEnabled (bool enabled)
  1153. {
  1154. resetAnalytics();
  1155. if (enabled)
  1156. setupAnalytics();
  1157. }
  1158. void ProjucerApplication::resetAnalytics() noexcept
  1159. {
  1160. auto analyticsInstance = Analytics::getInstance();
  1161. analyticsInstance->setUserId ({});
  1162. analyticsInstance->setUserProperties ({});
  1163. analyticsInstance->getDestinations().clear();
  1164. }
  1165. void ProjucerApplication::setupAnalytics()
  1166. {
  1167. Analytics::getInstance()->addDestination (new ProjucerAnalyticsDestination());
  1168. auto deviceString = SystemStats::getDeviceIdentifiers().joinIntoString (":");
  1169. auto deviceIdentifier = String::toHexString (deviceString.hashCode64());
  1170. Analytics::getInstance()->setUserId (deviceIdentifier);
  1171. StringPairArray userData;
  1172. userData.set ("cd1", getApplicationName());
  1173. userData.set ("cd2", getApplicationVersion());
  1174. userData.set ("cd3", SystemStats::getDeviceDescription());
  1175. userData.set ("cd4", deviceString);
  1176. userData.set ("cd5", SystemStats::getOperatingSystemName());
  1177. Analytics::getInstance()->setUserProperties (userData);
  1178. }
  1179. void ProjucerApplication::showSetJUCEPathAlert()
  1180. {
  1181. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  1182. pathAlert.reset (lf.createAlertWindow ("Set JUCE Path", "Your global JUCE path is invalid. This path is used to access the JUCE examples and demo project - "
  1183. "would you like to set it now?",
  1184. "Set path", "Cancel", "Don't ask again",
  1185. AlertWindow::WarningIcon, 3,
  1186. mainWindowList.getFrontmostWindow (false)));
  1187. pathAlert->enterModalState (true, ModalCallbackFunction::create ([this] (int retVal)
  1188. {
  1189. pathAlert.reset (nullptr);
  1190. if (retVal == 1)
  1191. showPathsWindow (true);
  1192. else if (retVal == 0)
  1193. settings->setDontAskAboutJUCEPathAgain();
  1194. }));
  1195. }
  1196. void ProjucerApplication::rescanJUCEPathModules()
  1197. {
  1198. File jucePath (getAppSettings().getStoredPath (Ids::defaultJuceModulePath, TargetOS::getThisOS()).get().toString());
  1199. if (! jucePath.exists())
  1200. return;
  1201. if (isRunningCommandLine)
  1202. jucePathModuleList.scanPaths ({ jucePath });
  1203. else
  1204. jucePathModuleList.scanPathsAsync ({ jucePath });
  1205. }
  1206. static Array<File> getSanitisedUserModulePaths()
  1207. {
  1208. Array<File> paths;
  1209. for (auto p : StringArray::fromTokens (getAppSettings().getStoredPath (Ids::defaultUserModulePath, TargetOS::getThisOS()).get().toString(), ";", {}))
  1210. {
  1211. p = p.replace ("~", File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  1212. paths.add (File::createFileWithoutCheckingPath (p.trim()));
  1213. }
  1214. return paths;
  1215. }
  1216. void ProjucerApplication::rescanUserPathModules()
  1217. {
  1218. if (isRunningCommandLine)
  1219. userPathsModuleList.scanPaths (getSanitisedUserModulePaths());
  1220. else
  1221. userPathsModuleList.scanPathsAsync (getSanitisedUserModulePaths());
  1222. }
  1223. void ProjucerApplication::selectEditorColourSchemeWithName (const String& schemeName)
  1224. {
  1225. auto& appearanceSettings = getAppSettings().appearance;
  1226. auto schemes = appearanceSettings.getPresetSchemes();
  1227. auto schemeIndex = schemes.indexOf (schemeName);
  1228. if (schemeIndex >= 0)
  1229. setEditorColourScheme (schemeIndex, true);
  1230. }
  1231. void ProjucerApplication::setColourScheme (int index, bool saveSetting)
  1232. {
  1233. switch (index)
  1234. {
  1235. case 0: lookAndFeel.setColourScheme (LookAndFeel_V4::getDarkColourScheme()); break;
  1236. case 1: lookAndFeel.setColourScheme (LookAndFeel_V4::getGreyColourScheme()); break;
  1237. case 2: lookAndFeel.setColourScheme (LookAndFeel_V4::getLightColourScheme()); break;
  1238. default: break;
  1239. }
  1240. lookAndFeel.setupColours();
  1241. mainWindowList.sendLookAndFeelChange();
  1242. if (utf8Window != nullptr) utf8Window->sendLookAndFeelChange();
  1243. if (svgPathWindow != nullptr) svgPathWindow->sendLookAndFeelChange();
  1244. if (aboutWindow != nullptr) aboutWindow->sendLookAndFeelChange();
  1245. if (applicationUsageDataWindow != nullptr) applicationUsageDataWindow->sendLookAndFeelChange();
  1246. if (pathsWindow != nullptr) pathsWindow->sendLookAndFeelChange();
  1247. if (editorColourSchemeWindow != nullptr) editorColourSchemeWindow->sendLookAndFeelChange();
  1248. if (pipCreatorWindow != nullptr) pipCreatorWindow->sendLookAndFeelChange();
  1249. auto* mcm = ModalComponentManager::getInstance();
  1250. for (auto i = 0; i < mcm->getNumModalComponents(); ++i)
  1251. mcm->getModalComponent (i)->sendLookAndFeelChange();
  1252. if (saveSetting)
  1253. {
  1254. auto& properties = settings->getGlobalProperties();
  1255. properties.setValue ("COLOUR SCHEME", index);
  1256. }
  1257. selectedColourSchemeIndex = index;
  1258. getCommandManager().commandStatusChanged();
  1259. }
  1260. void ProjucerApplication::setEditorColourScheme (int index, bool saveSetting)
  1261. {
  1262. auto& appearanceSettings = getAppSettings().appearance;
  1263. auto schemes = appearanceSettings.getPresetSchemes();
  1264. index = jmin (index, schemes.size() - 1);
  1265. appearanceSettings.selectPresetScheme (index);
  1266. if (saveSetting)
  1267. {
  1268. auto& properties = settings->getGlobalProperties();
  1269. properties.setValue ("EDITOR COLOUR SCHEME", index);
  1270. }
  1271. selectedEditorColourSchemeIndex = index;
  1272. getCommandManager().commandStatusChanged();
  1273. }
  1274. bool ProjucerApplication::isEditorColourSchemeADefaultScheme (const StringArray& schemes, int editorColourSchemeIndex)
  1275. {
  1276. auto& schemeName = schemes[editorColourSchemeIndex];
  1277. return (schemeName == "Default (Dark)" || schemeName == "Default (Light)");
  1278. }
  1279. int ProjucerApplication::getEditorColourSchemeForGUIColourScheme (const StringArray& schemes, int guiColourSchemeIndex)
  1280. {
  1281. auto defaultDarkEditorIndex = schemes.indexOf ("Default (Dark)");
  1282. auto defaultLightEditorIndex = schemes.indexOf ("Default (Light)");
  1283. // Can't find default code editor colour schemes!
  1284. jassert (defaultDarkEditorIndex != -1 && defaultLightEditorIndex != -1);
  1285. return (guiColourSchemeIndex == 2 ? defaultLightEditorIndex : defaultDarkEditorIndex);
  1286. }
  1287. void ProjucerApplication::updateEditorColourSchemeIfNeeded()
  1288. {
  1289. auto& appearanceSettings = getAppSettings().appearance;
  1290. auto schemes = appearanceSettings.getPresetSchemes();
  1291. if (isEditorColourSchemeADefaultScheme (schemes, selectedEditorColourSchemeIndex))
  1292. setEditorColourScheme (getEditorColourSchemeForGUIColourScheme (schemes, selectedColourSchemeIndex), true);
  1293. }