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.

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