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.

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