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.

635 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 (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.addSeparator();
  227. createColourSchemeItems (menu);
  228. }
  229. void createColourSchemeItems (PopupMenu& menu)
  230. {
  231. menu.addCommandItem (commandManager, CommandIDs::showAppearanceSettings);
  232. const StringArray presetSchemes (settings->appearance.getPresetSchemes());
  233. if (presetSchemes.size() > 0)
  234. {
  235. PopupMenu schemes;
  236. for (int i = 0; i < presetSchemes.size(); ++i)
  237. schemes.addItem (colourSchemeBaseID + i, presetSchemes[i]);
  238. menu.addSubMenu ("Colour Scheme", schemes);
  239. }
  240. }
  241. virtual void createWindowMenu (PopupMenu& menu)
  242. {
  243. menu.addCommandItem (commandManager, CommandIDs::closeWindow);
  244. menu.addSeparator();
  245. menu.addCommandItem (commandManager, CommandIDs::goToPreviousDoc);
  246. menu.addCommandItem (commandManager, CommandIDs::goToNextDoc);
  247. menu.addCommandItem (commandManager, CommandIDs::goToCounterpart);
  248. menu.addSeparator();
  249. const int numDocs = jmin (50, openDocumentManager.getNumOpenDocuments());
  250. for (int i = 0; i < numDocs; ++i)
  251. {
  252. OpenDocumentManager::Document* doc = openDocumentManager.getOpenDocument(i);
  253. menu.addItem (activeDocumentsBaseID + i, doc->getName());
  254. }
  255. menu.addSeparator();
  256. menu.addCommandItem (commandManager, CommandIDs::closeAllDocuments);
  257. }
  258. virtual void createToolsMenu (PopupMenu& menu)
  259. {
  260. menu.addCommandItem (commandManager, CommandIDs::updateModules);
  261. menu.addCommandItem (commandManager, CommandIDs::showUTF8Tool);
  262. menu.addCommandItem (commandManager, CommandIDs::showTranslationTool);
  263. }
  264. virtual void handleMainMenuCommand (int menuItemID)
  265. {
  266. if (menuItemID >= recentProjectsBaseID && menuItemID < recentProjectsBaseID + 100)
  267. {
  268. // open a file from the "recent files" menu
  269. openFile (settings->recentFiles.getFile (menuItemID - recentProjectsBaseID));
  270. }
  271. else if (menuItemID >= activeDocumentsBaseID && menuItemID < activeDocumentsBaseID + 200)
  272. {
  273. if (OpenDocumentManager::Document* doc = openDocumentManager.getOpenDocument (menuItemID - activeDocumentsBaseID))
  274. mainWindowList.openDocument (doc, true);
  275. else
  276. jassertfalse;
  277. }
  278. else if (menuItemID >= colourSchemeBaseID && menuItemID < colourSchemeBaseID + 200)
  279. {
  280. settings->appearance.selectPresetScheme (menuItemID - colourSchemeBaseID);
  281. }
  282. else
  283. {
  284. handleGUIEditorMenuCommand (menuItemID);
  285. }
  286. }
  287. //==============================================================================
  288. void getAllCommands (Array <CommandID>& commands) override
  289. {
  290. JUCEApplication::getAllCommands (commands);
  291. const CommandID ids[] = { CommandIDs::newProject,
  292. CommandIDs::open,
  293. CommandIDs::closeAllDocuments,
  294. CommandIDs::saveAll,
  295. CommandIDs::updateModules,
  296. CommandIDs::showAppearanceSettings,
  297. CommandIDs::showUTF8Tool };
  298. commands.addArray (ids, numElementsInArray (ids));
  299. }
  300. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) override
  301. {
  302. switch (commandID)
  303. {
  304. case CommandIDs::newProject:
  305. result.setInfo ("New Project...", "Creates a new Jucer project", CommandCategories::general, 0);
  306. result.defaultKeypresses.add (KeyPress ('n', ModifierKeys::commandModifier, 0));
  307. break;
  308. case CommandIDs::open:
  309. result.setInfo ("Open...", "Opens a Jucer project", CommandCategories::general, 0);
  310. result.defaultKeypresses.add (KeyPress ('o', ModifierKeys::commandModifier, 0));
  311. break;
  312. case CommandIDs::showAppearanceSettings:
  313. result.setInfo ("Fonts and Colours...", "Shows the appearance settings window.", CommandCategories::general, 0);
  314. break;
  315. case CommandIDs::closeAllDocuments:
  316. result.setInfo ("Close All Documents", "Closes all open documents", CommandCategories::general, 0);
  317. result.setActive (openDocumentManager.getNumOpenDocuments() > 0);
  318. break;
  319. case CommandIDs::saveAll:
  320. result.setInfo ("Save All", "Saves all open documents", CommandCategories::general, 0);
  321. result.setActive (openDocumentManager.anyFilesNeedSaving());
  322. break;
  323. case CommandIDs::updateModules:
  324. result.setInfo ("Download the latest JUCE modules", "Checks online for any JUCE modules updates and installs them", CommandCategories::general, 0);
  325. break;
  326. case CommandIDs::showUTF8Tool:
  327. result.setInfo ("UTF-8 String-Literal Helper", "Shows the UTF-8 string literal utility", CommandCategories::general, 0);
  328. break;
  329. default:
  330. JUCEApplication::getCommandInfo (commandID, result);
  331. break;
  332. }
  333. }
  334. bool perform (const InvocationInfo& info) override
  335. {
  336. switch (info.commandID)
  337. {
  338. case CommandIDs::newProject: createNewProject(); break;
  339. case CommandIDs::open: askUserToOpenFile(); break;
  340. case CommandIDs::saveAll: openDocumentManager.saveAll(); break;
  341. case CommandIDs::closeAllDocuments: closeAllDocuments (true); break;
  342. case CommandIDs::showUTF8Tool: showUTF8ToolWindow (utf8Window); break;
  343. case CommandIDs::showAppearanceSettings: AppearanceSettings::showEditorWindow (appearanceEditorWindow); break;
  344. case CommandIDs::updateModules: runModuleUpdate (String::empty); break;
  345. default: return JUCEApplication::perform (info);
  346. }
  347. return true;
  348. }
  349. //==============================================================================
  350. void createNewProject()
  351. {
  352. if (makeSureUserHasSelectedModuleFolder())
  353. {
  354. MainWindow* mw = mainWindowList.getOrCreateEmptyWindow();
  355. mw->showNewProjectWizard();
  356. mainWindowList.avoidSuperimposedWindows (mw);
  357. }
  358. }
  359. virtual void updateNewlyOpenedProject (Project&) {}
  360. void askUserToOpenFile()
  361. {
  362. FileChooser fc ("Open File");
  363. if (fc.browseForFileToOpen())
  364. openFile (fc.getResult());
  365. }
  366. bool openFile (const File& file)
  367. {
  368. return mainWindowList.openFile (file);
  369. }
  370. bool closeAllDocuments (bool askUserToSave)
  371. {
  372. return openDocumentManager.closeAll (askUserToSave);
  373. }
  374. virtual bool closeAllMainWindows()
  375. {
  376. return mainWindowList.askAllWindowsToClose();
  377. }
  378. bool makeSureUserHasSelectedModuleFolder()
  379. {
  380. if (! ModuleList::isLocalModulesFolderValid())
  381. {
  382. if (! runModuleUpdate ("Please select a location to store your local set of JUCE modules,\n"
  383. "and download the ones that you'd like to use!"))
  384. {
  385. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  386. "Introjucer",
  387. "Unless you create a local JUCE folder containing some modules, you'll be unable to save any projects correctly!\n\n"
  388. "Use the option on the 'Tools' menu to set this up!");
  389. return false;
  390. }
  391. }
  392. if (ModuleList().isLibraryNewerThanIntrojucer())
  393. {
  394. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  395. "Introjucer",
  396. "This version of the introjucer is out-of-date!"
  397. "\n\n"
  398. "Always make sure that you're running the very latest version, preferably compiled directly from the juce tree that you're working with!");
  399. }
  400. return true;
  401. }
  402. bool runModuleUpdate (const String& message)
  403. {
  404. ModuleList list;
  405. list.rescan (ModuleList::getDefaultModulesFolder (mainWindowList.getFrontmostProject()));
  406. JuceUpdater::show (list, mainWindowList.windows[0], message);
  407. ModuleList::setLocalModulesFolder (list.getModulesFolder());
  408. return ModuleList::isJuceOrModulesFolder (list.getModulesFolder());
  409. }
  410. //==============================================================================
  411. void initialiseLogger (const char* filePrefix)
  412. {
  413. if (logger == nullptr)
  414. {
  415. logger = FileLogger::createDateStampedLogger (getLogFolderName(), filePrefix, ".txt",
  416. getApplicationName() + " " + getApplicationVersion()
  417. + " --- Build date: " __DATE__);
  418. Logger::setCurrentLogger (logger);
  419. }
  420. }
  421. struct FileWithTime
  422. {
  423. FileWithTime (const File& f) : file (f), time (f.getLastModificationTime()) {}
  424. FileWithTime() {}
  425. bool operator< (const FileWithTime& other) const { return time < other.time; }
  426. bool operator== (const FileWithTime& other) const { return time == other.time; }
  427. File file;
  428. Time time;
  429. };
  430. void deleteLogger()
  431. {
  432. const int maxNumLogFilesToKeep = 50;
  433. Logger::setCurrentLogger (nullptr);
  434. if (logger != nullptr)
  435. {
  436. Array<File> logFiles;
  437. logger->getLogFile().getParentDirectory().findChildFiles (logFiles, File::findFiles, false);
  438. if (logFiles.size() > maxNumLogFilesToKeep)
  439. {
  440. Array <FileWithTime> files;
  441. for (int i = 0; i < logFiles.size(); ++i)
  442. files.addUsingDefaultSort (logFiles.getReference(i));
  443. for (int i = 0; i < files.size() - maxNumLogFilesToKeep; ++i)
  444. files.getReference(i).file.deleteFile();
  445. }
  446. }
  447. logger = nullptr;
  448. }
  449. virtual void doExtraInitialisation() {}
  450. virtual void addExtraConfigItems (Project&, TreeViewItem&) {}
  451. #if JUCE_LINUX
  452. virtual String getLogFolderName() const { return "~/.config/Introjucer/Logs"; }
  453. #else
  454. virtual String getLogFolderName() const { return "com.juce.introjucer"; }
  455. #endif
  456. virtual PropertiesFile::Options getPropertyFileOptionsFor (const String& filename)
  457. {
  458. PropertiesFile::Options options;
  459. options.applicationName = filename;
  460. options.filenameSuffix = "settings";
  461. options.osxLibrarySubFolder = "Application Support";
  462. #if JUCE_LINUX
  463. options.folderName = "~/.config/Introjucer";
  464. #else
  465. options.folderName = "Introjucer";
  466. #endif
  467. return options;
  468. }
  469. virtual Component* createProjectContentComponent() const
  470. {
  471. return new ProjectContentComponent();
  472. }
  473. //==============================================================================
  474. IntrojucerLookAndFeel lookAndFeel;
  475. ScopedPointer<StoredSettings> settings;
  476. ScopedPointer<Icons> icons;
  477. ScopedPointer<MainMenuModel> menuModel;
  478. MainWindowList mainWindowList;
  479. OpenDocumentManager openDocumentManager;
  480. ScopedPointer<ApplicationCommandManager> commandManager;
  481. ScopedPointer<Component> appearanceEditorWindow, utf8Window;
  482. ScopedPointer<FileLogger> logger;
  483. bool isRunningCommandLine;
  484. private:
  485. class AsyncQuitRetrier : private Timer
  486. {
  487. public:
  488. AsyncQuitRetrier() { startTimer (500); }
  489. void timerCallback() override
  490. {
  491. stopTimer();
  492. delete this;
  493. if (JUCEApplicationBase::getInstance() != nullptr)
  494. getApp().closeModalCompsAndQuit();
  495. }
  496. JUCE_DECLARE_NON_COPYABLE (AsyncQuitRetrier)
  497. };
  498. void initCommandManager()
  499. {
  500. commandManager = new ApplicationCommandManager();
  501. commandManager->registerAllCommandsForTarget (this);
  502. {
  503. CodeDocument doc;
  504. CppCodeEditorComponent ed (File::nonexistent, doc);
  505. commandManager->registerAllCommandsForTarget (&ed);
  506. }
  507. registerGUIEditorCommands();
  508. }
  509. };
  510. #endif // __JUCER_APPLICATION_JUCEHEADER__