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.

637 lines
22KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #ifndef __JUCER_APPLICATION_JUCEHEADER__
  18. #define __JUCER_APPLICATION_JUCEHEADER__
  19. #include "../jucer_Headers.h"
  20. #include "jucer_MainWindow.h"
  21. #include "jucer_JuceUpdater.h"
  22. #include "jucer_CommandLine.h"
  23. #include "../Code Editor/jucer_SourceCodeEditor.h"
  24. void createGUIEditorMenu (PopupMenu&);
  25. void handleGUIEditorMenuCommand (int);
  26. void registerGUIEditorCommands();
  27. //==============================================================================
  28. class IntrojucerApp : public JUCEApplication
  29. {
  30. public:
  31. //==============================================================================
  32. IntrojucerApp() : isRunningCommandLine (false) {}
  33. //==============================================================================
  34. void initialise (const String& commandLine) override
  35. {
  36. LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37. settings = new StoredSettings();
  38. if (commandLine.isNotEmpty())
  39. {
  40. const int appReturnCode = performCommandLine (commandLine);
  41. if (appReturnCode != commandLineNotPerformed)
  42. {
  43. isRunningCommandLine = true;
  44. setApplicationReturnValue (appReturnCode);
  45. quit();
  46. return;
  47. }
  48. }
  49. initialiseLogger ("log_");
  50. if (sendCommandLineToPreexistingInstance())
  51. {
  52. DBG ("Another instance is running - quitting...");
  53. quit();
  54. return;
  55. }
  56. icons = new Icons();
  57. initCommandManager();
  58. menuModel = new MainMenuModel();
  59. doExtraInitialisation();
  60. settings->appearance.refreshPresetSchemeList();
  61. ImageCache::setCacheTimeout (30 * 1000);
  62. if (commandLine.trim().isNotEmpty() && ! commandLine.trim().startsWithChar ('-'))
  63. anotherInstanceStarted (commandLine);
  64. else
  65. mainWindowList.reopenLastProjects();
  66. mainWindowList.createWindowIfNoneAreOpen();
  67. #if JUCE_MAC
  68. MenuBarModel::setMacMainMenu (menuModel, nullptr, "Open Recent");
  69. #endif
  70. struct ModuleFolderChecker : public CallbackMessage
  71. {
  72. ModuleFolderChecker() {}
  73. void messageCallback() override
  74. {
  75. if (IntrojucerApp* const app = dynamic_cast<IntrojucerApp*> (JUCEApplication::getInstance()))
  76. app->makeSureUserHasSelectedModuleFolder();
  77. }
  78. };
  79. (new ModuleFolderChecker())->post();
  80. }
  81. void shutdown() override
  82. {
  83. appearanceEditorWindow = nullptr;
  84. utf8Window = nullptr;
  85. #if JUCE_MAC
  86. MenuBarModel::setMacMainMenu (nullptr);
  87. #endif
  88. menuModel = nullptr;
  89. mainWindowList.forceCloseAllWindows();
  90. openDocumentManager.clear();
  91. commandManager = nullptr;
  92. settings = nullptr;
  93. LookAndFeel::setDefaultLookAndFeel (nullptr);
  94. if (! isRunningCommandLine)
  95. Logger::writeToLog ("Shutdown");
  96. deleteLogger();
  97. }
  98. //==============================================================================
  99. void systemRequestedQuit() override
  100. {
  101. closeModalCompsAndQuit();
  102. }
  103. void closeModalCompsAndQuit()
  104. {
  105. if (cancelAnyModalComponents())
  106. {
  107. new AsyncQuitRetrier();
  108. }
  109. else
  110. {
  111. if (closeAllMainWindows())
  112. quit();
  113. }
  114. }
  115. //==============================================================================
  116. const String getApplicationName() override { return "Introjucer"; }
  117. const String getApplicationVersion() override { return ProjectInfo::versionString; }
  118. bool moreThanOneInstanceAllowed() override
  119. {
  120. return true; // this is handled manually in initialise()
  121. }
  122. void anotherInstanceStarted (const String& commandLine) override
  123. {
  124. openFile (File (commandLine.unquoted()));
  125. }
  126. static IntrojucerApp& getApp()
  127. {
  128. IntrojucerApp* const app = dynamic_cast<IntrojucerApp*> (JUCEApplication::getInstance());
  129. jassert (app != nullptr);
  130. return *app;
  131. }
  132. static ApplicationCommandManager& getCommandManager()
  133. {
  134. ApplicationCommandManager* cm = IntrojucerApp::getApp().commandManager;
  135. jassert (cm != nullptr);
  136. return *cm;
  137. }
  138. //==============================================================================
  139. class MainMenuModel : public MenuBarModel
  140. {
  141. public:
  142. MainMenuModel()
  143. {
  144. setApplicationCommandManagerToWatch (&getCommandManager());
  145. }
  146. StringArray getMenuBarNames()
  147. {
  148. return getApp().getMenuNames();
  149. }
  150. PopupMenu getMenuForIndex (int /*topLevelMenuIndex*/, const String& menuName)
  151. {
  152. PopupMenu menu;
  153. getApp().createMenu (menu, menuName);
  154. return menu;
  155. }
  156. void menuItemSelected (int menuItemID, int /*topLevelMenuIndex*/)
  157. {
  158. getApp().handleMainMenuCommand (menuItemID);
  159. }
  160. };
  161. enum
  162. {
  163. recentProjectsBaseID = 100,
  164. activeDocumentsBaseID = 300,
  165. colourSchemeBaseID = 1000
  166. };
  167. virtual StringArray getMenuNames()
  168. {
  169. const char* const names[] = { "File", "Edit", "View", "Window", "GUI Editor", "Tools", nullptr };
  170. return StringArray (names);
  171. }
  172. virtual void createMenu (PopupMenu& menu, const String& menuName)
  173. {
  174. if (menuName == "File") createFileMenu (menu);
  175. else if (menuName == "Edit") createEditMenu (menu);
  176. else if (menuName == "View") createViewMenu (menu);
  177. else if (menuName == "Window") createWindowMenu (menu);
  178. else if (menuName == "Tools") createToolsMenu (menu);
  179. else if (menuName == "GUI Editor") createGUIEditorMenu (menu);
  180. else jassertfalse; // names have changed?
  181. }
  182. virtual void createFileMenu (PopupMenu& menu)
  183. {
  184. menu.addCommandItem (commandManager, CommandIDs::newProject);
  185. menu.addSeparator();
  186. menu.addCommandItem (commandManager, CommandIDs::open);
  187. PopupMenu recentFiles;
  188. settings->recentFiles.createPopupMenuItems (recentFiles, recentProjectsBaseID, true, true);
  189. menu.addSubMenu ("Open Recent", recentFiles);
  190. menu.addSeparator();
  191. menu.addCommandItem (commandManager, CommandIDs::closeDocument);
  192. menu.addCommandItem (commandManager, CommandIDs::saveDocument);
  193. menu.addCommandItem (commandManager, CommandIDs::saveDocumentAs);
  194. menu.addSeparator();
  195. menu.addCommandItem (commandManager, CommandIDs::closeProject);
  196. menu.addCommandItem (commandManager, CommandIDs::saveProject);
  197. menu.addSeparator();
  198. menu.addCommandItem (commandManager, CommandIDs::openInIDE);
  199. menu.addCommandItem (commandManager, CommandIDs::saveAndOpenInIDE);
  200. #if ! JUCE_MAC
  201. menu.addSeparator();
  202. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::quit);
  203. #endif
  204. }
  205. virtual void createEditMenu (PopupMenu& menu)
  206. {
  207. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::undo);
  208. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::redo);
  209. menu.addSeparator();
  210. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::cut);
  211. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::copy);
  212. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::paste);
  213. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::del);
  214. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::selectAll);
  215. menu.addCommandItem (commandManager, StandardApplicationCommandIDs::deselectAll);
  216. menu.addSeparator();
  217. menu.addCommandItem (commandManager, CommandIDs::showFindPanel);
  218. menu.addCommandItem (commandManager, CommandIDs::findSelection);
  219. menu.addCommandItem (commandManager, CommandIDs::findNext);
  220. menu.addCommandItem (commandManager, CommandIDs::findPrevious);
  221. }
  222. virtual void createViewMenu (PopupMenu& menu)
  223. {
  224. menu.addCommandItem (commandManager, CommandIDs::showFilePanel);
  225. menu.addCommandItem (commandManager, CommandIDs::showConfigPanel);
  226. menu.addCommandItem (commandManager, CommandIDs::showProjectSettings);
  227. menu.addCommandItem (commandManager, CommandIDs::showProjectModules);
  228. menu.addSeparator();
  229. createColourSchemeItems (menu);
  230. }
  231. void createColourSchemeItems (PopupMenu& menu)
  232. {
  233. menu.addCommandItem (commandManager, CommandIDs::showAppearanceSettings);
  234. const StringArray presetSchemes (settings->appearance.getPresetSchemes());
  235. if (presetSchemes.size() > 0)
  236. {
  237. PopupMenu schemes;
  238. for (int i = 0; i < presetSchemes.size(); ++i)
  239. schemes.addItem (colourSchemeBaseID + i, presetSchemes[i]);
  240. menu.addSubMenu ("Colour Scheme", schemes);
  241. }
  242. }
  243. virtual void createWindowMenu (PopupMenu& menu)
  244. {
  245. menu.addCommandItem (commandManager, CommandIDs::closeWindow);
  246. menu.addSeparator();
  247. menu.addCommandItem (commandManager, CommandIDs::goToPreviousDoc);
  248. menu.addCommandItem (commandManager, CommandIDs::goToNextDoc);
  249. menu.addCommandItem (commandManager, CommandIDs::goToCounterpart);
  250. menu.addSeparator();
  251. const int numDocs = jmin (50, openDocumentManager.getNumOpenDocuments());
  252. for (int i = 0; i < numDocs; ++i)
  253. {
  254. OpenDocumentManager::Document* doc = openDocumentManager.getOpenDocument(i);
  255. menu.addItem (activeDocumentsBaseID + i, doc->getName());
  256. }
  257. menu.addSeparator();
  258. menu.addCommandItem (commandManager, CommandIDs::closeAllDocuments);
  259. }
  260. virtual void createToolsMenu (PopupMenu& menu)
  261. {
  262. menu.addCommandItem (commandManager, CommandIDs::updateModules);
  263. menu.addCommandItem (commandManager, CommandIDs::showUTF8Tool);
  264. menu.addCommandItem (commandManager, CommandIDs::showTranslationTool);
  265. }
  266. virtual void handleMainMenuCommand (int menuItemID)
  267. {
  268. if (menuItemID >= recentProjectsBaseID && menuItemID < recentProjectsBaseID + 100)
  269. {
  270. // open a file from the "recent files" menu
  271. openFile (settings->recentFiles.getFile (menuItemID - recentProjectsBaseID));
  272. }
  273. else if (menuItemID >= activeDocumentsBaseID && menuItemID < activeDocumentsBaseID + 200)
  274. {
  275. if (OpenDocumentManager::Document* doc = openDocumentManager.getOpenDocument (menuItemID - activeDocumentsBaseID))
  276. mainWindowList.openDocument (doc, true);
  277. else
  278. jassertfalse;
  279. }
  280. else if (menuItemID >= colourSchemeBaseID && menuItemID < colourSchemeBaseID + 200)
  281. {
  282. settings->appearance.selectPresetScheme (menuItemID - colourSchemeBaseID);
  283. }
  284. else
  285. {
  286. handleGUIEditorMenuCommand (menuItemID);
  287. }
  288. }
  289. //==============================================================================
  290. void getAllCommands (Array <CommandID>& commands) override
  291. {
  292. JUCEApplication::getAllCommands (commands);
  293. const CommandID ids[] = { CommandIDs::newProject,
  294. CommandIDs::open,
  295. CommandIDs::closeAllDocuments,
  296. CommandIDs::saveAll,
  297. CommandIDs::updateModules,
  298. CommandIDs::showAppearanceSettings,
  299. CommandIDs::showUTF8Tool };
  300. commands.addArray (ids, numElementsInArray (ids));
  301. }
  302. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) override
  303. {
  304. switch (commandID)
  305. {
  306. case CommandIDs::newProject:
  307. result.setInfo ("New Project...", "Creates a new Jucer project", CommandCategories::general, 0);
  308. result.defaultKeypresses.add (KeyPress ('n', ModifierKeys::commandModifier, 0));
  309. break;
  310. case CommandIDs::open:
  311. result.setInfo ("Open...", "Opens a Jucer project", CommandCategories::general, 0);
  312. result.defaultKeypresses.add (KeyPress ('o', ModifierKeys::commandModifier, 0));
  313. break;
  314. case CommandIDs::showAppearanceSettings:
  315. result.setInfo ("Fonts and Colours...", "Shows the appearance settings window.", CommandCategories::general, 0);
  316. break;
  317. case CommandIDs::closeAllDocuments:
  318. result.setInfo ("Close All Documents", "Closes all open documents", CommandCategories::general, 0);
  319. result.setActive (openDocumentManager.getNumOpenDocuments() > 0);
  320. break;
  321. case CommandIDs::saveAll:
  322. result.setInfo ("Save All", "Saves all open documents", CommandCategories::general, 0);
  323. result.setActive (openDocumentManager.anyFilesNeedSaving());
  324. break;
  325. case CommandIDs::updateModules:
  326. result.setInfo ("Download the latest JUCE modules", "Checks online for any JUCE modules updates and installs them", CommandCategories::general, 0);
  327. break;
  328. case CommandIDs::showUTF8Tool:
  329. result.setInfo ("UTF-8 String-Literal Helper", "Shows the UTF-8 string literal utility", CommandCategories::general, 0);
  330. break;
  331. default:
  332. JUCEApplication::getCommandInfo (commandID, result);
  333. break;
  334. }
  335. }
  336. bool perform (const InvocationInfo& info) override
  337. {
  338. switch (info.commandID)
  339. {
  340. case CommandIDs::newProject: createNewProject(); break;
  341. case CommandIDs::open: askUserToOpenFile(); break;
  342. case CommandIDs::saveAll: openDocumentManager.saveAll(); break;
  343. case CommandIDs::closeAllDocuments: closeAllDocuments (true); break;
  344. case CommandIDs::showUTF8Tool: showUTF8ToolWindow (utf8Window); break;
  345. case CommandIDs::showAppearanceSettings: AppearanceSettings::showEditorWindow (appearanceEditorWindow); break;
  346. case CommandIDs::updateModules: runModuleUpdate (String::empty); break;
  347. default: return JUCEApplication::perform (info);
  348. }
  349. return true;
  350. }
  351. //==============================================================================
  352. void createNewProject()
  353. {
  354. if (makeSureUserHasSelectedModuleFolder())
  355. {
  356. MainWindow* mw = mainWindowList.getOrCreateEmptyWindow();
  357. mw->showNewProjectWizard();
  358. mainWindowList.avoidSuperimposedWindows (mw);
  359. }
  360. }
  361. virtual void updateNewlyOpenedProject (Project&) {}
  362. void askUserToOpenFile()
  363. {
  364. FileChooser fc ("Open File");
  365. if (fc.browseForFileToOpen())
  366. openFile (fc.getResult());
  367. }
  368. bool openFile (const File& file)
  369. {
  370. return mainWindowList.openFile (file);
  371. }
  372. bool closeAllDocuments (bool askUserToSave)
  373. {
  374. return openDocumentManager.closeAll (askUserToSave);
  375. }
  376. virtual bool closeAllMainWindows()
  377. {
  378. return mainWindowList.askAllWindowsToClose();
  379. }
  380. bool makeSureUserHasSelectedModuleFolder()
  381. {
  382. if (! AvailableModuleList::isLocalModulesFolderValid())
  383. {
  384. if (! runModuleUpdate ("Please select a location to store your local set of JUCE modules,\n"
  385. "and download the ones that you'd like to use!"))
  386. {
  387. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  388. "Introjucer",
  389. "Unless you create a local JUCE folder containing some modules, you'll be unable to save any projects correctly!\n\n"
  390. "Use the option on the 'Tools' menu to set this up!");
  391. return false;
  392. }
  393. }
  394. if (AvailableModuleList().isLibraryNewerThanIntrojucer())
  395. {
  396. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  397. "Introjucer",
  398. "This version of the introjucer is out-of-date!"
  399. "\n\n"
  400. "Always make sure that you're running the very latest version, preferably compiled directly from the juce tree that you're working with!");
  401. }
  402. return true;
  403. }
  404. bool runModuleUpdate (const String& message)
  405. {
  406. AvailableModuleList list;
  407. list.rescan (AvailableModuleList::getDefaultModulesFolder (mainWindowList.getFrontmostProject()));
  408. JuceUpdater::show (list, mainWindowList.windows[0], message);
  409. AvailableModuleList::setLocalModulesFolder (list.getModulesFolder());
  410. return AvailableModuleList::isJuceOrModulesFolder (list.getModulesFolder());
  411. }
  412. //==============================================================================
  413. void initialiseLogger (const char* filePrefix)
  414. {
  415. if (logger == nullptr)
  416. {
  417. logger = FileLogger::createDateStampedLogger (getLogFolderName(), filePrefix, ".txt",
  418. getApplicationName() + " " + getApplicationVersion()
  419. + " --- Build date: " __DATE__);
  420. Logger::setCurrentLogger (logger);
  421. }
  422. }
  423. struct FileWithTime
  424. {
  425. FileWithTime (const File& f) : file (f), time (f.getLastModificationTime()) {}
  426. FileWithTime() {}
  427. bool operator< (const FileWithTime& other) const { return time < other.time; }
  428. bool operator== (const FileWithTime& other) const { return time == other.time; }
  429. File file;
  430. Time time;
  431. };
  432. void deleteLogger()
  433. {
  434. const int maxNumLogFilesToKeep = 50;
  435. Logger::setCurrentLogger (nullptr);
  436. if (logger != nullptr)
  437. {
  438. Array<File> logFiles;
  439. logger->getLogFile().getParentDirectory().findChildFiles (logFiles, File::findFiles, false);
  440. if (logFiles.size() > maxNumLogFilesToKeep)
  441. {
  442. Array <FileWithTime> files;
  443. for (int i = 0; i < logFiles.size(); ++i)
  444. files.addUsingDefaultSort (logFiles.getReference(i));
  445. for (int i = 0; i < files.size() - maxNumLogFilesToKeep; ++i)
  446. files.getReference(i).file.deleteFile();
  447. }
  448. }
  449. logger = nullptr;
  450. }
  451. virtual void doExtraInitialisation() {}
  452. virtual void addExtraConfigItems (Project&, TreeViewItem&) {}
  453. #if JUCE_LINUX
  454. virtual String getLogFolderName() const { return "~/.config/Introjucer/Logs"; }
  455. #else
  456. virtual String getLogFolderName() const { return "com.juce.introjucer"; }
  457. #endif
  458. virtual PropertiesFile::Options getPropertyFileOptionsFor (const String& filename)
  459. {
  460. PropertiesFile::Options options;
  461. options.applicationName = filename;
  462. options.filenameSuffix = "settings";
  463. options.osxLibrarySubFolder = "Application Support";
  464. #if JUCE_LINUX
  465. options.folderName = "~/.config/Introjucer";
  466. #else
  467. options.folderName = "Introjucer";
  468. #endif
  469. return options;
  470. }
  471. virtual Component* createProjectContentComponent() const
  472. {
  473. return new ProjectContentComponent();
  474. }
  475. //==============================================================================
  476. IntrojucerLookAndFeel lookAndFeel;
  477. ScopedPointer<StoredSettings> settings;
  478. ScopedPointer<Icons> icons;
  479. ScopedPointer<MainMenuModel> menuModel;
  480. MainWindowList mainWindowList;
  481. OpenDocumentManager openDocumentManager;
  482. ScopedPointer<ApplicationCommandManager> commandManager;
  483. ScopedPointer<Component> appearanceEditorWindow, utf8Window;
  484. ScopedPointer<FileLogger> logger;
  485. bool isRunningCommandLine;
  486. private:
  487. class AsyncQuitRetrier : private Timer
  488. {
  489. public:
  490. AsyncQuitRetrier() { startTimer (500); }
  491. void timerCallback() override
  492. {
  493. stopTimer();
  494. delete this;
  495. if (JUCEApplicationBase::getInstance() != nullptr)
  496. getApp().closeModalCompsAndQuit();
  497. }
  498. JUCE_DECLARE_NON_COPYABLE (AsyncQuitRetrier)
  499. };
  500. void initCommandManager()
  501. {
  502. commandManager = new ApplicationCommandManager();
  503. commandManager->registerAllCommandsForTarget (this);
  504. {
  505. CodeDocument doc;
  506. CppCodeEditorComponent ed (File::nonexistent, doc);
  507. commandManager->registerAllCommandsForTarget (&ed);
  508. }
  509. registerGUIEditorCommands();
  510. }
  511. };
  512. #endif // __JUCER_APPLICATION_JUCEHEADER__