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.

1609 lines
57KB

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