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.

1603 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. #else
  584. jassertfalse;
  585. return {};
  586. #endif
  587. }
  588. static File getPlatformSpecificProjectFolder()
  589. {
  590. auto examplesDir = getJUCEExamplesDirectoryPathFromGlobal();
  591. if (examplesDir == File())
  592. return {};
  593. auto buildsFolder = examplesDir.getChildFile ("DemoRunner").getChildFile ("Builds");
  594. #if JUCE_MAC
  595. return buildsFolder.getChildFile ("MacOSX");
  596. #elif JUCE_WINDOWS
  597. return buildsFolder.getChildFile ("VisualStudio2017");
  598. #elif JUCE_LINUX
  599. return buildsFolder.getChildFile ("LinuxMakefile");
  600. #else
  601. jassertfalse;
  602. return {};
  603. #endif
  604. }
  605. static File tryToFindDemoRunnerExecutableInBuilds()
  606. {
  607. auto projectFolder = getPlatformSpecificProjectFolder();
  608. if (projectFolder == File())
  609. return {};
  610. #if JUCE_MAC
  611. projectFolder = projectFolder.getChildFile ("build");
  612. auto demoRunnerExecutable = projectFolder.getChildFile ("Release").getChildFile ("DemoRunner.app");
  613. if (demoRunnerExecutable.exists())
  614. return demoRunnerExecutable;
  615. demoRunnerExecutable = projectFolder.getChildFile ("Debug").getChildFile ("DemoRunner.app");
  616. if (demoRunnerExecutable.exists())
  617. return demoRunnerExecutable;
  618. #elif JUCE_WINDOWS
  619. projectFolder = projectFolder.getChildFile ("x64");
  620. auto demoRunnerExecutable = projectFolder.getChildFile ("Release").getChildFile ("App").getChildFile ("DemoRunner.exe");
  621. if (demoRunnerExecutable.existsAsFile())
  622. return demoRunnerExecutable;
  623. demoRunnerExecutable = projectFolder.getChildFile ("Debug").getChildFile ("App").getChildFile ("DemoRunner.exe");
  624. if (demoRunnerExecutable.existsAsFile())
  625. return demoRunnerExecutable;
  626. #elif JUCE_LINUX
  627. projectFolder = projectFolder.getChildFile ("LinuxMakefile").getChildFile ("build");
  628. auto demoRunnerExecutable = projectFolder.getChildFile ("DemoRunner");
  629. if (demoRunnerExecutable.existsAsFile())
  630. return demoRunnerExecutable;
  631. #endif
  632. return {};
  633. }
  634. static File tryToFindPrebuiltDemoRunnerExecutable()
  635. {
  636. auto prebuiltFile = File (getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get().toString())
  637. .getChildFile ("DemoRunner" + getPlatformSpecificFileExtension());
  638. #if JUCE_MAC
  639. if (prebuiltFile.exists())
  640. #else
  641. if (prebuiltFile.existsAsFile())
  642. #endif
  643. return prebuiltFile;
  644. return {};
  645. }
  646. void ProjucerApplication::checkIfGlobalJUCEPathHasChanged()
  647. {
  648. auto globalJUCEPath = File (getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get());
  649. if (lastJUCEPath != globalJUCEPath)
  650. {
  651. hasScannedForDemoRunnerProject = false;
  652. hasScannedForDemoRunnerExecutable = false;
  653. lastJUCEPath = globalJUCEPath;
  654. }
  655. }
  656. File ProjucerApplication::tryToFindDemoRunnerExecutable()
  657. {
  658. checkIfGlobalJUCEPathHasChanged();
  659. if (hasScannedForDemoRunnerExecutable)
  660. return lastDemoRunnerExectuableFile;
  661. hasScannedForDemoRunnerExecutable = true;
  662. auto demoRunnerExecutable = tryToFindDemoRunnerExecutableInBuilds();
  663. if (demoRunnerExecutable == File())
  664. demoRunnerExecutable = tryToFindPrebuiltDemoRunnerExecutable();
  665. lastDemoRunnerExectuableFile = demoRunnerExecutable;
  666. return demoRunnerExecutable;
  667. }
  668. File ProjucerApplication::tryToFindDemoRunnerProject()
  669. {
  670. checkIfGlobalJUCEPathHasChanged();
  671. if (hasScannedForDemoRunnerProject)
  672. return lastDemoRunnerProjectFile;
  673. hasScannedForDemoRunnerProject = true;
  674. auto projectFolder = getPlatformSpecificProjectFolder();
  675. if (projectFolder == File())
  676. {
  677. lastDemoRunnerProjectFile = File();
  678. return {};
  679. }
  680. #if JUCE_MAC
  681. auto demoRunnerProjectFile = projectFolder.getChildFile ("DemoRunner.xcodeproj");
  682. #elif JUCE_WINDOWS
  683. auto demoRunnerProjectFile = projectFolder.getChildFile ("DemoRunner.sln");
  684. #elif JUCE_LINUX
  685. auto demoRunnerProjectFile = projectFolder.getChildFile ("Makefile");
  686. #endif
  687. #if JUCE_MAC
  688. if (! demoRunnerProjectFile.exists())
  689. #else
  690. if (! demoRunnerProjectFile.existsAsFile())
  691. #endif
  692. demoRunnerProjectFile = File();
  693. lastDemoRunnerProjectFile = demoRunnerProjectFile;
  694. return demoRunnerProjectFile;
  695. }
  696. void ProjucerApplication::launchDemoRunner()
  697. {
  698. auto demoRunnerFile = tryToFindDemoRunnerExecutable();
  699. if (demoRunnerFile != File())
  700. {
  701. auto succeeded = demoRunnerFile.startAsProcess();
  702. StringPairArray data;
  703. data.set ("label", succeeded ? "Success" : "Failure");
  704. Analytics::getInstance()->logEvent ("Launch DemoRunner", data, ProjucerAnalyticsEvent::exampleEvent);
  705. if (succeeded)
  706. return;
  707. }
  708. demoRunnerFile = tryToFindDemoRunnerProject();
  709. if (demoRunnerFile != File())
  710. {
  711. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  712. demoRunnerAlert.reset (lf.createAlertWindow ("Open Project",
  713. "Couldn't find a compiled version of the Demo Runner."
  714. #if JUCE_LINUX
  715. " Do you want to build it now?", "Build project", "Cancel",
  716. #else
  717. " Do you want to open the project?", "Open project", "Cancel",
  718. #endif
  719. {},
  720. AlertWindow::QuestionIcon, 2,
  721. mainWindowList.getFrontmostWindow (false)));
  722. demoRunnerAlert->enterModalState (true, ModalCallbackFunction::create ([this, demoRunnerFile] (int retVal)
  723. {
  724. demoRunnerAlert.reset (nullptr);
  725. StringPairArray data;
  726. data.set ("label", retVal == 1 ? "Opened" : "Cancelled");
  727. Analytics::getInstance()->logEvent ("Open DemoRunner Project", data, ProjucerAnalyticsEvent::exampleEvent);
  728. if (retVal == 1)
  729. {
  730. #if JUCE_LINUX
  731. String command ("make -C " + demoRunnerFile.getParentDirectory().getFullPathName() + " CONFIG=Release -j3");
  732. if (! makeProcess.start (command))
  733. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Error", "Error building Demo Runner.");
  734. #else
  735. demoRunnerFile.startAsProcess();
  736. #endif
  737. }
  738. }), false);
  739. }
  740. }
  741. //==========================================================================
  742. void ProjucerApplication::handleMainMenuCommand (int menuItemID)
  743. {
  744. if (menuItemID >= recentProjectsBaseID && menuItemID < (recentProjectsBaseID + 100))
  745. {
  746. // open a file from the "recent files" menu
  747. openFile (settings->recentFiles.getFile (menuItemID - recentProjectsBaseID));
  748. }
  749. else if (menuItemID >= openWindowsBaseID && menuItemID < (openWindowsBaseID + 100))
  750. {
  751. if (auto* window = mainWindowList.windows.getUnchecked (menuItemID - openWindowsBaseID))
  752. window->toFront (true);
  753. }
  754. else if (menuItemID >= activeDocumentsBaseID && menuItemID < (activeDocumentsBaseID + 200))
  755. {
  756. if (auto* doc = openDocumentManager.getOpenDocument (menuItemID - activeDocumentsBaseID))
  757. mainWindowList.openDocument (doc, true);
  758. else
  759. jassertfalse;
  760. }
  761. else if (menuItemID >= colourSchemeBaseID && menuItemID < (colourSchemeBaseID + 3))
  762. {
  763. setColourScheme (menuItemID - colourSchemeBaseID, true);
  764. updateEditorColourSchemeIfNeeded();
  765. }
  766. else if (menuItemID >= codeEditorColourSchemeBaseID && menuItemID < (codeEditorColourSchemeBaseID + numEditorColourSchemes))
  767. {
  768. setEditorColourScheme (menuItemID - codeEditorColourSchemeBaseID, true);
  769. }
  770. else if (menuItemID == (codeEditorColourSchemeBaseID + numEditorColourSchemes))
  771. {
  772. showEditorColourSchemeWindow();
  773. }
  774. else if (menuItemID == showPathsID)
  775. {
  776. showPathsWindow (true);
  777. }
  778. else if (menuItemID >= examplesBaseID && menuItemID < (examplesBaseID + numExamples))
  779. {
  780. findAndLaunchExample (menuItemID - examplesBaseID);
  781. }
  782. else
  783. {
  784. handleGUIEditorMenuCommand (menuItemID);
  785. }
  786. }
  787. //==============================================================================
  788. void ProjucerApplication::getAllCommands (Array <CommandID>& commands)
  789. {
  790. JUCEApplication::getAllCommands (commands);
  791. const CommandID ids[] = { CommandIDs::newProject,
  792. CommandIDs::newProjectFromClipboard,
  793. CommandIDs::newPIP,
  794. CommandIDs::open,
  795. CommandIDs::launchDemoRunner,
  796. CommandIDs::closeAllWindows,
  797. CommandIDs::closeAllDocuments,
  798. CommandIDs::clearRecentFiles,
  799. CommandIDs::saveAll,
  800. CommandIDs::showGlobalPathsWindow,
  801. CommandIDs::showUTF8Tool,
  802. CommandIDs::showSVGPathTool,
  803. CommandIDs::showAboutWindow,
  804. CommandIDs::showAppUsageWindow,
  805. CommandIDs::showForum,
  806. CommandIDs::showAPIModules,
  807. CommandIDs::showAPIClasses,
  808. CommandIDs::showTutorials,
  809. CommandIDs::loginLogout };
  810. commands.addArray (ids, numElementsInArray (ids));
  811. }
  812. void ProjucerApplication::getCommandInfo (CommandID commandID, ApplicationCommandInfo& result)
  813. {
  814. switch (commandID)
  815. {
  816. case CommandIDs::newProject:
  817. result.setInfo ("New Project...", "Creates a new JUCE project", CommandCategories::general, 0);
  818. result.defaultKeypresses.add (KeyPress ('n', ModifierKeys::commandModifier, 0));
  819. break;
  820. case CommandIDs::newProjectFromClipboard:
  821. result.setInfo ("New Project From Clipboard...", "Creates a new JUCE project from the clipboard contents", CommandCategories::general, 0);
  822. result.defaultKeypresses.add (KeyPress ('n', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0));
  823. break;
  824. case CommandIDs::newPIP:
  825. result.setInfo ("New PIP...", "Opens the PIP Creator utility for creating a new PIP", CommandCategories::general, 0);
  826. result.defaultKeypresses.add (KeyPress ('p', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0));
  827. break;
  828. case CommandIDs::launchDemoRunner:
  829. #if JUCE_LINUX
  830. if (makeProcess.isRunning())
  831. {
  832. result.setInfo ("Building Demo Runner...", "The Demo Runner project is currently building", CommandCategories::general, 0);
  833. result.setActive (false);
  834. }
  835. else
  836. #endif
  837. {
  838. result.setInfo ("Launch Demo Runner", "Launches the JUCE demo runner application, or the project if it can't be found", CommandCategories::general, 0);
  839. result.setActive (tryToFindDemoRunnerExecutable() != File() || tryToFindDemoRunnerProject() != File());
  840. }
  841. break;
  842. case CommandIDs::open:
  843. result.setInfo ("Open...", "Opens a JUCE project", CommandCategories::general, 0);
  844. result.defaultKeypresses.add (KeyPress ('o', ModifierKeys::commandModifier, 0));
  845. break;
  846. case CommandIDs::showGlobalPathsWindow:
  847. result.setInfo ("Global Paths...",
  848. "Shows the window to change the stored global paths.",
  849. CommandCategories::general, 0);
  850. break;
  851. case CommandIDs::closeAllWindows:
  852. result.setInfo ("Close All Windows", "Closes all open windows", CommandCategories::general, 0);
  853. result.setActive (mainWindowList.windows.size() > 0);
  854. break;
  855. case CommandIDs::closeAllDocuments:
  856. result.setInfo ("Close All Documents", "Closes all open documents", CommandCategories::general, 0);
  857. result.setActive (openDocumentManager.getNumOpenDocuments() > 0);
  858. break;
  859. case CommandIDs::clearRecentFiles:
  860. result.setInfo ("Clear Recent Files", "Clears all recent files from the menu", CommandCategories::general, 0);
  861. result.setActive (settings->recentFiles.getNumFiles() > 0);
  862. break;
  863. case CommandIDs::saveAll:
  864. result.setInfo ("Save All", "Saves all open documents", CommandCategories::general, 0);
  865. result.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier | ModifierKeys::altModifier, 0));
  866. break;
  867. case CommandIDs::showUTF8Tool:
  868. result.setInfo ("UTF-8 String-Literal Helper", "Shows the UTF-8 string literal utility", CommandCategories::general, 0);
  869. break;
  870. case CommandIDs::showSVGPathTool:
  871. result.setInfo ("SVG Path Converter", "Shows the SVG->Path data conversion utility", CommandCategories::general, 0);
  872. break;
  873. case CommandIDs::showAboutWindow:
  874. result.setInfo ("About Projucer", "Shows the Projucer's 'About' page.", CommandCategories::general, 0);
  875. break;
  876. case CommandIDs::showAppUsageWindow:
  877. result.setInfo ("Application Usage Data", "Shows the application usage data agreement window", CommandCategories::general, 0);
  878. break;
  879. case CommandIDs::showForum:
  880. result.setInfo ("JUCE Community Forum", "Shows the JUCE community forum in a browser", CommandCategories::general, 0);
  881. break;
  882. case CommandIDs::showAPIModules:
  883. result.setInfo ("API Modules", "Shows the API modules documentation in a browser", CommandCategories::general, 0);
  884. break;
  885. case CommandIDs::showAPIClasses:
  886. result.setInfo ("API Classes", "Shows the API classes documentation in a browser", CommandCategories::general, 0);
  887. break;
  888. case CommandIDs::showTutorials:
  889. result.setInfo ("JUCE Tutorials", "Shows the JUCE tutorials in a browser", CommandCategories::general, 0);
  890. break;
  891. case CommandIDs::loginLogout:
  892. {
  893. bool isLoggedIn = false;
  894. String username;
  895. if (licenseController != nullptr)
  896. {
  897. const LicenseState state = licenseController->getState();
  898. isLoggedIn = (state.type != LicenseState::Type::notLoggedIn && state.type != LicenseState::Type::GPL);
  899. username = state.username;
  900. }
  901. result.setInfo (isLoggedIn
  902. ? String ("Sign out ") + username + "..."
  903. : String ("Sign in..."),
  904. "Log out of your JUCE account", CommandCategories::general, 0);
  905. }
  906. break;
  907. default:
  908. JUCEApplication::getCommandInfo (commandID, result);
  909. break;
  910. }
  911. }
  912. bool ProjucerApplication::perform (const InvocationInfo& info)
  913. {
  914. switch (info.commandID)
  915. {
  916. case CommandIDs::newProject: createNewProject(); break;
  917. case CommandIDs::newProjectFromClipboard: createNewProjectFromClipboard(); break;
  918. case CommandIDs::newPIP: createNewPIP(); break;
  919. case CommandIDs::open: askUserToOpenFile(); break;
  920. case CommandIDs::launchDemoRunner: launchDemoRunner(); break;
  921. case CommandIDs::saveAll: saveAllDocuments(); break;
  922. case CommandIDs::closeAllWindows: closeAllMainWindowsAndQuitIfNeeded(); break;
  923. case CommandIDs::closeAllDocuments: closeAllDocuments (true); break;
  924. case CommandIDs::clearRecentFiles: clearRecentFiles(); break;
  925. case CommandIDs::showUTF8Tool: showUTF8ToolWindow(); break;
  926. case CommandIDs::showSVGPathTool: showSVGPathDataToolWindow(); break;
  927. case CommandIDs::showGlobalPathsWindow: showPathsWindow (false); break;
  928. case CommandIDs::showAboutWindow: showAboutWindow(); break;
  929. case CommandIDs::showAppUsageWindow: showApplicationUsageDataAgreementPopup(); break;
  930. case CommandIDs::showForum: launchForumBrowser(); break;
  931. case CommandIDs::showAPIModules: launchModulesBrowser(); break;
  932. case CommandIDs::showAPIClasses: launchClassesBrowser(); break;
  933. case CommandIDs::showTutorials: launchTutorialsBrowser(); break;
  934. case CommandIDs::loginLogout: doLogout(); break;
  935. default: return JUCEApplication::perform (info);
  936. }
  937. return true;
  938. }
  939. //==============================================================================
  940. void ProjucerApplication::createNewProject()
  941. {
  942. auto* mw = mainWindowList.getOrCreateEmptyWindow();
  943. mw->showStartPage();
  944. mainWindowList.avoidSuperimposedWindows (mw);
  945. }
  946. void ProjucerApplication::createNewProjectFromClipboard()
  947. {
  948. auto tempFile = File::getSpecialLocation (File::SpecialLocationType::tempDirectory).getChildFile ("PIPs").getChildFile ("Clipboard")
  949. .getChildFile ("PIPFile_" + String (std::abs (Random::getSystemRandom().nextInt())) + ".h");
  950. if (tempFile.existsAsFile())
  951. tempFile.deleteFile();
  952. tempFile.create();
  953. tempFile.appendText (SystemClipboard::getTextFromClipboard());
  954. if (! findWindowAndOpenPIP (tempFile))
  955. {
  956. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Error", "Couldn't create project from clipboard contents.");
  957. tempFile.deleteFile();
  958. }
  959. }
  960. void ProjucerApplication::createNewPIP()
  961. {
  962. showPIPCreatorWindow();
  963. }
  964. void ProjucerApplication::askUserToOpenFile()
  965. {
  966. FileChooser fc ("Open File");
  967. if (fc.browseForFileToOpen())
  968. openFile (fc.getResult());
  969. }
  970. bool ProjucerApplication::openFile (const File& file)
  971. {
  972. return mainWindowList.openFile (file);
  973. }
  974. void ProjucerApplication::saveAllDocuments()
  975. {
  976. openDocumentManager.saveAll();
  977. for (int i = 0; i < mainWindowList.windows.size(); ++i)
  978. if (auto* pcc = mainWindowList.windows.getUnchecked(i)->getProjectContentComponent())
  979. pcc->refreshProjectTreeFileStatuses();
  980. }
  981. bool ProjucerApplication::closeAllDocuments (bool askUserToSave)
  982. {
  983. return openDocumentManager.closeAll (askUserToSave);
  984. }
  985. bool ProjucerApplication::closeAllMainWindows()
  986. {
  987. return server != nullptr || mainWindowList.askAllWindowsToClose();
  988. }
  989. void ProjucerApplication::closeAllMainWindowsAndQuitIfNeeded()
  990. {
  991. if (closeAllMainWindows())
  992. {
  993. #if ! JUCE_MAC
  994. if (mainWindowList.windows.size() == 0)
  995. systemRequestedQuit();
  996. #endif
  997. }
  998. }
  999. void ProjucerApplication::clearRecentFiles()
  1000. {
  1001. settings->recentFiles.clear();
  1002. settings->recentFiles.clearRecentFilesNatively();
  1003. settings->flush();
  1004. menuModel->menuItemsChanged();
  1005. }
  1006. //==============================================================================
  1007. void ProjucerApplication::showUTF8ToolWindow()
  1008. {
  1009. if (utf8Window != nullptr)
  1010. utf8Window->toFront (true);
  1011. else
  1012. new FloatingToolWindow ("UTF-8 String Literal Converter", "utf8WindowPos",
  1013. new UTF8Component(), utf8Window, true,
  1014. 500, 500, 300, 300, 1000, 1000);
  1015. }
  1016. void ProjucerApplication::showSVGPathDataToolWindow()
  1017. {
  1018. if (svgPathWindow != nullptr)
  1019. svgPathWindow->toFront (true);
  1020. else
  1021. new FloatingToolWindow ("SVG Path Converter", "svgPathWindowPos",
  1022. new SVGPathDataComponent(), svgPathWindow, true,
  1023. 500, 500, 300, 300, 1000, 1000);
  1024. }
  1025. void ProjucerApplication::showAboutWindow()
  1026. {
  1027. if (aboutWindow != nullptr)
  1028. aboutWindow->toFront (true);
  1029. else
  1030. new FloatingToolWindow ({}, {}, new AboutWindowComponent(),
  1031. aboutWindow, false,
  1032. 500, 300, 500, 300, 500, 300);
  1033. }
  1034. void ProjucerApplication::showApplicationUsageDataAgreementPopup()
  1035. {
  1036. if (applicationUsageDataWindow != nullptr)
  1037. applicationUsageDataWindow->toFront (true);
  1038. else
  1039. new FloatingToolWindow ("Application Usage Analytics", {},
  1040. new ApplicationUsageDataWindowComponent (isPaidOrGPL()), applicationUsageDataWindow, false,
  1041. 400, 300, 400, 300, 400, 300);
  1042. }
  1043. void ProjucerApplication::dismissApplicationUsageDataAgreementPopup()
  1044. {
  1045. if (applicationUsageDataWindow != nullptr)
  1046. applicationUsageDataWindow.reset();
  1047. }
  1048. void ProjucerApplication::showPathsWindow (bool highlightJUCEPath)
  1049. {
  1050. if (pathsWindow != nullptr)
  1051. pathsWindow->toFront (true);
  1052. else
  1053. new FloatingToolWindow ("Global Paths", "pathsWindowPos",
  1054. new GlobalPathsWindowComponent(), pathsWindow, false,
  1055. 600, 700, 600, 700, 600, 700);
  1056. if (highlightJUCEPath)
  1057. if (auto* pathsComp = dynamic_cast<GlobalPathsWindowComponent*> (pathsWindow->getChildComponent (0)))
  1058. pathsComp->highlightJUCEPath();
  1059. }
  1060. void ProjucerApplication::showEditorColourSchemeWindow()
  1061. {
  1062. if (editorColourSchemeWindow != nullptr)
  1063. editorColourSchemeWindow->toFront (true);
  1064. else
  1065. new FloatingToolWindow ("Editor Colour Scheme", "editorColourSchemeWindowPos",
  1066. new EditorColourSchemeWindowComponent(), editorColourSchemeWindow, false,
  1067. 500, 500, 500, 500, 500, 500);
  1068. }
  1069. void ProjucerApplication::showPIPCreatorWindow()
  1070. {
  1071. if (pipCreatorWindow != nullptr)
  1072. pipCreatorWindow->toFront (true);
  1073. else
  1074. new FloatingToolWindow ("PIP Creator", "pipCreatorWindowPos",
  1075. new PIPCreatorWindowComponent(), pipCreatorWindow, false,
  1076. 600, 750, 600, 750, 600, 750);
  1077. }
  1078. void ProjucerApplication::launchForumBrowser()
  1079. {
  1080. URL forumLink ("https://forum.juce.com/");
  1081. if (forumLink.isWellFormed())
  1082. forumLink.launchInDefaultBrowser();
  1083. }
  1084. void ProjucerApplication::launchModulesBrowser()
  1085. {
  1086. URL modulesLink ("https://docs.juce.com/master/modules.html");
  1087. if (modulesLink.isWellFormed())
  1088. modulesLink.launchInDefaultBrowser();
  1089. }
  1090. void ProjucerApplication::launchClassesBrowser()
  1091. {
  1092. URL classesLink ("https://docs.juce.com/master/classes.html");
  1093. if (classesLink.isWellFormed())
  1094. classesLink.launchInDefaultBrowser();
  1095. }
  1096. void ProjucerApplication::launchTutorialsBrowser()
  1097. {
  1098. URL tutorialsLink ("https://juce.com/learn/tutorials");
  1099. if (tutorialsLink.isWellFormed())
  1100. tutorialsLink.launchInDefaultBrowser();
  1101. }
  1102. //==============================================================================
  1103. struct FileWithTime
  1104. {
  1105. FileWithTime (const File& f) : file (f), time (f.getLastModificationTime()) {}
  1106. FileWithTime() {}
  1107. bool operator< (const FileWithTime& other) const { return time < other.time; }
  1108. bool operator== (const FileWithTime& other) const { return time == other.time; }
  1109. File file;
  1110. Time time;
  1111. };
  1112. void ProjucerApplication::deleteLogger()
  1113. {
  1114. const int maxNumLogFilesToKeep = 50;
  1115. Logger::setCurrentLogger (nullptr);
  1116. if (logger != nullptr)
  1117. {
  1118. auto logFiles = logger->getLogFile().getParentDirectory().findChildFiles (File::findFiles, false);
  1119. if (logFiles.size() > maxNumLogFilesToKeep)
  1120. {
  1121. Array<FileWithTime> files;
  1122. for (auto& f : logFiles)
  1123. files.addUsingDefaultSort (f);
  1124. for (int i = 0; i < files.size() - maxNumLogFilesToKeep; ++i)
  1125. files.getReference(i).file.deleteFile();
  1126. }
  1127. }
  1128. logger.reset();
  1129. }
  1130. PropertiesFile::Options ProjucerApplication::getPropertyFileOptionsFor (const String& filename, bool isProjectSettings)
  1131. {
  1132. PropertiesFile::Options options;
  1133. options.applicationName = filename;
  1134. options.filenameSuffix = "settings";
  1135. options.osxLibrarySubFolder = "Application Support";
  1136. #if JUCE_LINUX
  1137. options.folderName = "~/.config/Projucer";
  1138. #else
  1139. options.folderName = "Projucer";
  1140. #endif
  1141. if (isProjectSettings)
  1142. options.folderName += "/ProjectSettings";
  1143. return options;
  1144. }
  1145. void ProjucerApplication::updateAllBuildTabs()
  1146. {
  1147. for (int i = 0; i < mainWindowList.windows.size(); ++i)
  1148. if (ProjectContentComponent* p = mainWindowList.windows.getUnchecked(i)->getProjectContentComponent())
  1149. p->rebuildProjectTabs();
  1150. }
  1151. void ProjucerApplication::initCommandManager()
  1152. {
  1153. commandManager.reset (new ApplicationCommandManager());
  1154. commandManager->registerAllCommandsForTarget (this);
  1155. {
  1156. CodeDocument doc;
  1157. CppCodeEditorComponent ed (File(), doc);
  1158. commandManager->registerAllCommandsForTarget (&ed);
  1159. }
  1160. registerGUIEditorCommands();
  1161. }
  1162. void ProjucerApplication::setAnalyticsEnabled (bool enabled)
  1163. {
  1164. resetAnalytics();
  1165. if (enabled)
  1166. setupAnalytics();
  1167. }
  1168. void ProjucerApplication::resetAnalytics() noexcept
  1169. {
  1170. auto analyticsInstance = Analytics::getInstance();
  1171. analyticsInstance->setUserId ({});
  1172. analyticsInstance->setUserProperties ({});
  1173. analyticsInstance->getDestinations().clear();
  1174. }
  1175. void ProjucerApplication::setupAnalytics()
  1176. {
  1177. Analytics::getInstance()->addDestination (new ProjucerAnalyticsDestination());
  1178. auto deviceString = SystemStats::getDeviceIdentifiers().joinIntoString (":");
  1179. auto deviceIdentifier = String::toHexString (deviceString.hashCode64());
  1180. Analytics::getInstance()->setUserId (deviceIdentifier);
  1181. StringPairArray userData;
  1182. userData.set ("cd1", getApplicationName());
  1183. userData.set ("cd2", getApplicationVersion());
  1184. userData.set ("cd3", SystemStats::getDeviceDescription());
  1185. userData.set ("cd4", deviceString);
  1186. userData.set ("cd5", SystemStats::getOperatingSystemName());
  1187. Analytics::getInstance()->setUserProperties (userData);
  1188. }
  1189. void ProjucerApplication::showSetJUCEPathAlert()
  1190. {
  1191. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  1192. 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 - "
  1193. "would you like to set it now?",
  1194. "Set path", "Cancel", "Don't ask again",
  1195. AlertWindow::WarningIcon, 3,
  1196. mainWindowList.getFrontmostWindow (false)));
  1197. pathAlert->enterModalState (true, ModalCallbackFunction::create ([this] (int retVal)
  1198. {
  1199. pathAlert.reset (nullptr);
  1200. if (retVal == 1)
  1201. showPathsWindow (true);
  1202. else if (retVal == 0)
  1203. settings->setDontAskAboutJUCEPathAgain();
  1204. }));
  1205. }
  1206. void rescanModules (AvailableModuleList& list, const Array<File>& paths, bool async)
  1207. {
  1208. if (async)
  1209. list.scanPathsAsync (paths);
  1210. else
  1211. list.scanPaths (paths);
  1212. }
  1213. void ProjucerApplication::rescanJUCEPathModules()
  1214. {
  1215. rescanModules (jucePathModuleList, { getAppSettings().getStoredPath (Ids::defaultJuceModulePath, TargetOS::getThisOS()).get().toString() }, ! isRunningCommandLine);
  1216. }
  1217. void ProjucerApplication::rescanUserPathModules()
  1218. {
  1219. rescanModules (userPathsModuleList, { getAppSettings().getStoredPath (Ids::defaultUserModulePath, TargetOS::getThisOS()).get().toString() }, ! isRunningCommandLine);
  1220. }
  1221. void ProjucerApplication::selectEditorColourSchemeWithName (const String& schemeName)
  1222. {
  1223. auto& appearanceSettings = getAppSettings().appearance;
  1224. auto schemes = appearanceSettings.getPresetSchemes();
  1225. auto schemeIndex = schemes.indexOf (schemeName);
  1226. if (schemeIndex >= 0)
  1227. setEditorColourScheme (schemeIndex, true);
  1228. }
  1229. void ProjucerApplication::setColourScheme (int index, bool saveSetting)
  1230. {
  1231. switch (index)
  1232. {
  1233. case 0: lookAndFeel.setColourScheme (LookAndFeel_V4::getDarkColourScheme()); break;
  1234. case 1: lookAndFeel.setColourScheme (LookAndFeel_V4::getGreyColourScheme()); break;
  1235. case 2: lookAndFeel.setColourScheme (LookAndFeel_V4::getLightColourScheme()); break;
  1236. default: break;
  1237. }
  1238. lookAndFeel.setupColours();
  1239. mainWindowList.sendLookAndFeelChange();
  1240. if (utf8Window != nullptr) utf8Window->sendLookAndFeelChange();
  1241. if (svgPathWindow != nullptr) svgPathWindow->sendLookAndFeelChange();
  1242. if (aboutWindow != nullptr) aboutWindow->sendLookAndFeelChange();
  1243. if (applicationUsageDataWindow != nullptr) applicationUsageDataWindow->sendLookAndFeelChange();
  1244. if (pathsWindow != nullptr) pathsWindow->sendLookAndFeelChange();
  1245. if (editorColourSchemeWindow != nullptr) editorColourSchemeWindow->sendLookAndFeelChange();
  1246. if (pipCreatorWindow != nullptr) pipCreatorWindow->sendLookAndFeelChange();
  1247. auto* mcm = ModalComponentManager::getInstance();
  1248. for (auto i = 0; i < mcm->getNumModalComponents(); ++i)
  1249. mcm->getModalComponent (i)->sendLookAndFeelChange();
  1250. if (saveSetting)
  1251. {
  1252. auto& properties = settings->getGlobalProperties();
  1253. properties.setValue ("COLOUR SCHEME", index);
  1254. }
  1255. selectedColourSchemeIndex = index;
  1256. getCommandManager().commandStatusChanged();
  1257. }
  1258. void ProjucerApplication::setEditorColourScheme (int index, bool saveSetting)
  1259. {
  1260. auto& appearanceSettings = getAppSettings().appearance;
  1261. auto schemes = appearanceSettings.getPresetSchemes();
  1262. index = jmin (index, schemes.size() - 1);
  1263. appearanceSettings.selectPresetScheme (index);
  1264. if (saveSetting)
  1265. {
  1266. auto& properties = settings->getGlobalProperties();
  1267. properties.setValue ("EDITOR COLOUR SCHEME", index);
  1268. }
  1269. selectedEditorColourSchemeIndex = index;
  1270. getCommandManager().commandStatusChanged();
  1271. }
  1272. bool ProjucerApplication::isEditorColourSchemeADefaultScheme (const StringArray& schemes, int editorColourSchemeIndex)
  1273. {
  1274. auto& schemeName = schemes[editorColourSchemeIndex];
  1275. return (schemeName == "Default (Dark)" || schemeName == "Default (Light)");
  1276. }
  1277. int ProjucerApplication::getEditorColourSchemeForGUIColourScheme (const StringArray& schemes, int guiColourSchemeIndex)
  1278. {
  1279. auto defaultDarkEditorIndex = schemes.indexOf ("Default (Dark)");
  1280. auto defaultLightEditorIndex = schemes.indexOf ("Default (Light)");
  1281. // Can't find default code editor colour schemes!
  1282. jassert (defaultDarkEditorIndex != -1 && defaultLightEditorIndex != -1);
  1283. return (guiColourSchemeIndex == 2 ? defaultLightEditorIndex : defaultDarkEditorIndex);
  1284. }
  1285. void ProjucerApplication::updateEditorColourSchemeIfNeeded()
  1286. {
  1287. auto& appearanceSettings = getAppSettings().appearance;
  1288. auto schemes = appearanceSettings.getPresetSchemes();
  1289. if (isEditorColourSchemeADefaultScheme (schemes, selectedEditorColourSchemeIndex))
  1290. setEditorColourScheme (getEditorColourSchemeForGUIColourScheme (schemes, selectedColourSchemeIndex), true);
  1291. }