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.

1472 lines
52KB

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