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.

1594 lines
57KB

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