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.

920 lines
27KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #include "../Application/jucer_Headers.h"
  14. #include "jucer_Application.h"
  15. #include "jucer_MainWindow.h"
  16. #include "../Wizards/jucer_NewProjectWizardClasses.h"
  17. #include "../Utility/UI/jucer_JucerTreeViewBase.h"
  18. #include "../ProjectSaving/jucer_ProjectSaver.h"
  19. #include "UserAccount/jucer_LoginFormComponent.h"
  20. #include "../Project/UI/jucer_ProjectContentComponent.h"
  21. //==============================================================================
  22. class BlurOverlayWithComponent : public Component,
  23. private ComponentMovementWatcher,
  24. private AsyncUpdater
  25. {
  26. public:
  27. BlurOverlayWithComponent (MainWindow& window, std::unique_ptr<Component> comp)
  28. : ComponentMovementWatcher (&window),
  29. mainWindow (window),
  30. componentToShow (std::move (comp))
  31. {
  32. kernel.createGaussianBlur (1.25f);
  33. addAndMakeVisible (*componentToShow);
  34. setAlwaysOnTop (true);
  35. setOpaque (true);
  36. setVisible (true);
  37. static_cast<Component&> (mainWindow).addChildComponent (this);
  38. componentMovedOrResized (true, true);
  39. }
  40. void resized() override
  41. {
  42. setBounds (mainWindow.getLocalBounds());
  43. componentToShow->centreWithSize (componentToShow->getWidth(), componentToShow->getHeight());
  44. refreshBackgroundImage();
  45. }
  46. void paint (Graphics& g) override
  47. {
  48. g.drawImage (componentImage, getLocalBounds().toFloat());
  49. }
  50. private:
  51. void componentPeerChanged() override {}
  52. void componentVisibilityChanged() override {}
  53. using ComponentMovementWatcher::componentVisibilityChanged;
  54. void componentMovedOrResized (bool, bool) override { triggerAsyncUpdate(); }
  55. using ComponentMovementWatcher::componentMovedOrResized;
  56. void handleAsyncUpdate() override { resized(); }
  57. void mouseUp (const MouseEvent& event) override
  58. {
  59. if (event.eventComponent == this)
  60. mainWindow.hideLoginFormOverlay();
  61. }
  62. void lookAndFeelChanged() override
  63. {
  64. refreshBackgroundImage();
  65. repaint();
  66. }
  67. void refreshBackgroundImage()
  68. {
  69. setVisible (false);
  70. auto parentBounds = mainWindow.getBounds();
  71. componentImage = mainWindow.createComponentSnapshot (mainWindow.getLocalBounds())
  72. .rescaled (roundToInt (parentBounds.getWidth() / 1.75f), roundToInt (parentBounds.getHeight() / 1.75f));
  73. kernel.applyToImage (componentImage, componentImage, getLocalBounds());
  74. setVisible (true);
  75. }
  76. //==============================================================================
  77. MainWindow& mainWindow;
  78. std::unique_ptr<Component> componentToShow;
  79. ImageConvolutionKernel kernel { 3 };
  80. Image componentImage;
  81. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlurOverlayWithComponent)
  82. };
  83. //==============================================================================
  84. MainWindow::MainWindow()
  85. : DocumentWindow (ProjucerApplication::getApp().getApplicationName(),
  86. ProjucerApplication::getApp().lookAndFeel.getCurrentColourScheme()
  87. .getUIColour (LookAndFeel_V4::ColourScheme::UIColour::windowBackground),
  88. DocumentWindow::allButtons,
  89. false)
  90. {
  91. setUsingNativeTitleBar (true);
  92. setResizable (true, false);
  93. setResizeLimits (600, 500, 32000, 32000);
  94. #if ! JUCE_MAC
  95. setMenuBar (ProjucerApplication::getApp().getMenuModel());
  96. #endif
  97. createProjectContentCompIfNeeded();
  98. auto& commandManager = ProjucerApplication::getCommandManager();
  99. auto registerAllAppCommands = [&]
  100. {
  101. commandManager.registerAllCommandsForTarget (this);
  102. commandManager.registerAllCommandsForTarget (getProjectContentComponent());
  103. };
  104. auto updateAppKeyMappings = [&]
  105. {
  106. commandManager.getKeyMappings()->resetToDefaultMappings();
  107. if (auto keys = getGlobalProperties().getXmlValue ("keyMappings"))
  108. commandManager.getKeyMappings()->restoreFromXml (*keys);
  109. addKeyListener (commandManager.getKeyMappings());
  110. };
  111. registerAllAppCommands();
  112. updateAppKeyMappings();
  113. setWantsKeyboardFocus (false);
  114. getLookAndFeel().setColour (ColourSelector::backgroundColourId, Colours::transparentBlack);
  115. projectNameValue.addListener (this);
  116. centreWithSize (800, 600);
  117. }
  118. MainWindow::~MainWindow()
  119. {
  120. #if ! JUCE_MAC
  121. setMenuBar (nullptr);
  122. #endif
  123. removeKeyListener (ProjucerApplication::getCommandManager().getKeyMappings());
  124. // save the current size and position to our settings file..
  125. getGlobalProperties().setValue ("lastMainWindowPos", getWindowStateAsString());
  126. clearContentComponent();
  127. }
  128. void MainWindow::createProjectContentCompIfNeeded()
  129. {
  130. if (getProjectContentComponent() == nullptr)
  131. {
  132. clearContentComponent();
  133. setContentOwned (new ProjectContentComponent(), false);
  134. }
  135. }
  136. void MainWindow::setTitleBarIcon()
  137. {
  138. if (auto* peer = getPeer())
  139. {
  140. if (currentProject != nullptr)
  141. {
  142. peer->setRepresentedFile (currentProject->getFile());
  143. peer->setIcon (ImageCache::getFromMemory (BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize));
  144. }
  145. else
  146. {
  147. peer->setRepresentedFile ({});
  148. }
  149. }
  150. }
  151. void MainWindow::makeVisible()
  152. {
  153. setVisible (true);
  154. addToDesktop();
  155. restoreWindowPosition();
  156. setTitleBarIcon();
  157. getContentComponent()->grabKeyboardFocus();
  158. }
  159. ProjectContentComponent* MainWindow::getProjectContentComponent() const
  160. {
  161. return dynamic_cast<ProjectContentComponent*> (getContentComponent());
  162. }
  163. void MainWindow::closeButtonPressed()
  164. {
  165. ProjucerApplication::getApp().mainWindowList.closeWindow (this);
  166. }
  167. bool MainWindow::closeCurrentProject (OpenDocumentManager::SaveIfNeeded askUserToSave)
  168. {
  169. if (currentProject == nullptr)
  170. return true;
  171. currentProject->getStoredProperties().setValue (getProjectWindowPosName(), getWindowStateAsString());
  172. if (auto* pcc = getProjectContentComponent())
  173. {
  174. pcc->saveTreeViewState();
  175. pcc->saveOpenDocumentList();
  176. pcc->hideEditor();
  177. }
  178. if (ProjucerApplication::getApp().openDocumentManager
  179. .closeAllDocumentsUsingProject (*currentProject, askUserToSave))
  180. {
  181. if (askUserToSave == OpenDocumentManager::SaveIfNeeded::no
  182. || (currentProject->saveIfNeededAndUserAgrees() == FileBasedDocument::savedOk))
  183. {
  184. setProject (nullptr);
  185. return true;
  186. }
  187. }
  188. return false;
  189. }
  190. void MainWindow::moveProject (File newProjectFileToOpen, OpenInIDE openInIDE)
  191. {
  192. closeCurrentProject (OpenDocumentManager::SaveIfNeeded::no);
  193. openFile (newProjectFileToOpen);
  194. if (currentProject != nullptr)
  195. ProjucerApplication::getApp().getCommandManager()
  196. .invokeDirectly (openInIDE == OpenInIDE::yes ? CommandIDs::saveAndOpenInIDE
  197. : CommandIDs::saveProject,
  198. false);
  199. }
  200. void MainWindow::setProject (std::unique_ptr<Project> newProject)
  201. {
  202. if (newProject == nullptr)
  203. {
  204. if (auto* content = getProjectContentComponent())
  205. content->setProject (nullptr);
  206. currentProject.reset();
  207. }
  208. else
  209. {
  210. currentProject = std::move (newProject);
  211. createProjectContentCompIfNeeded();
  212. getProjectContentComponent()->setProject (currentProject.get());
  213. }
  214. projectNameValue.referTo (currentProject != nullptr ? currentProject->getProjectValue (Ids::name) : Value());
  215. if (auto* peer = getPeer())
  216. peer->setRepresentedFile (currentProject != nullptr ? currentProject->getFile() : File());
  217. ProjucerApplication::getCommandManager().commandStatusChanged();
  218. }
  219. void MainWindow::restoreWindowPosition()
  220. {
  221. String windowState;
  222. if (currentProject != nullptr)
  223. windowState = currentProject->getStoredProperties().getValue (getProjectWindowPosName());
  224. if (windowState.isEmpty())
  225. windowState = getGlobalProperties().getValue ("lastMainWindowPos");
  226. restoreWindowStateFromString (windowState);
  227. }
  228. bool MainWindow::canOpenFile (const File& file) const
  229. {
  230. return (! file.isDirectory())
  231. && (file.hasFileExtension (Project::projectFileExtension)
  232. || ProjucerApplication::getApp().openDocumentManager.canOpenFile (file));
  233. }
  234. bool MainWindow::openFile (const File& file)
  235. {
  236. createProjectContentCompIfNeeded();
  237. if (file.hasFileExtension (Project::projectFileExtension))
  238. {
  239. auto newDoc = std::make_unique<Project> (file);
  240. auto result = newDoc->loadFrom (file, true);
  241. if (result.wasOk() && closeCurrentProject (OpenDocumentManager::SaveIfNeeded::yes))
  242. {
  243. setProject (std::move (newDoc));
  244. currentProject->setChangedFlag (false);
  245. getProjectContentComponent()->reloadLastOpenDocuments();
  246. currentProject->updateDeprecatedProjectSettingsInteractively();
  247. return true;
  248. }
  249. }
  250. else if (file.exists())
  251. {
  252. return getProjectContentComponent()->showEditorForFile (file, true);
  253. }
  254. return false;
  255. }
  256. bool MainWindow::tryToOpenPIP (const File& pipFile)
  257. {
  258. PIPGenerator generator (pipFile);
  259. if (! generator.hasValidPIP())
  260. return false;
  261. auto generatorResult = generator.createJucerFile();
  262. if (generatorResult != Result::ok())
  263. {
  264. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  265. "PIP Error.",
  266. generatorResult.getErrorMessage());
  267. return false;
  268. }
  269. if (! generator.createMainCpp())
  270. {
  271. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  272. "PIP Error.",
  273. "Failed to create Main.cpp.");
  274. return false;
  275. }
  276. if (! ProjucerApplication::getApp().mainWindowList.openFile (generator.getJucerFile()))
  277. return false;
  278. openPIP (generator);
  279. return true;
  280. }
  281. static bool isDivider (const String& line)
  282. {
  283. auto afterIndent = line.trim();
  284. if (afterIndent.startsWith ("//") && afterIndent.length() > 20)
  285. {
  286. afterIndent = afterIndent.substring (2);
  287. if (afterIndent.containsOnly ("=")
  288. || afterIndent.containsOnly ("/")
  289. || afterIndent.containsOnly ("-"))
  290. {
  291. return true;
  292. }
  293. }
  294. return false;
  295. }
  296. static bool isEndOfCommentBlock (const String& line)
  297. {
  298. if (line.contains ("*/"))
  299. return true;
  300. return false;
  301. }
  302. static int getIndexOfCommentBlockStart (const StringArray& lines, int blockEndIndex)
  303. {
  304. for (int i = blockEndIndex; i >= 0; --i)
  305. {
  306. if (lines[i].contains ("/*"))
  307. return i;
  308. }
  309. return 0;
  310. }
  311. static int findBestLineToScrollTo (StringArray lines, StringRef className)
  312. {
  313. for (auto line : lines)
  314. {
  315. if (line.contains ("struct " + className) || line.contains ("class " + className))
  316. {
  317. auto index = lines.indexOf (line);
  318. if (isDivider (lines[index - 1]))
  319. return index - 1;
  320. if (isEndOfCommentBlock (lines[index - 1]))
  321. {
  322. auto blockStartIndex = getIndexOfCommentBlockStart (lines, index - 1);
  323. if (blockStartIndex > 0 && isDivider (lines [blockStartIndex - 1]))
  324. return blockStartIndex - 1;
  325. return blockStartIndex;
  326. }
  327. return lines.indexOf (line);
  328. }
  329. }
  330. return 0;
  331. }
  332. void MainWindow::openPIP (PIPGenerator& generator)
  333. {
  334. if (auto* window = ProjucerApplication::getApp().mainWindowList.getMainWindowForFile (generator.getJucerFile()))
  335. {
  336. if (auto* project = window->getProject())
  337. {
  338. project->setTemporaryDirectory (generator.getOutputDirectory());
  339. ProjectSaver liveBuildSaver (*project);
  340. liveBuildSaver.saveContentNeededForLiveBuild();
  341. if (auto* pcc = window->getProjectContentComponent())
  342. {
  343. pcc->invokeDirectly (CommandIDs::toggleBuildEnabled, true);
  344. pcc->invokeDirectly (CommandIDs::buildNow, true);
  345. pcc->invokeDirectly (CommandIDs::toggleContinuousBuild, true);
  346. auto fileToDisplay = generator.getPIPFile();
  347. if (fileToDisplay != File())
  348. {
  349. pcc->showEditorForFile (fileToDisplay, true);
  350. if (auto* sourceCodeEditor = dynamic_cast <SourceCodeEditor*> (pcc->getEditorComponent()))
  351. {
  352. sourceCodeEditor->editor->scrollToLine (findBestLineToScrollTo (StringArray::fromLines (fileToDisplay.loadFileAsString()),
  353. generator.getMainClassName()));
  354. }
  355. }
  356. }
  357. }
  358. }
  359. }
  360. bool MainWindow::isInterestedInFileDrag (const StringArray& filenames)
  361. {
  362. for (auto& filename : filenames)
  363. if (canOpenFile (File (filename)))
  364. return true;
  365. return false;
  366. }
  367. void MainWindow::filesDropped (const StringArray& filenames, int /*mouseX*/, int /*mouseY*/)
  368. {
  369. for (auto& filename : filenames)
  370. {
  371. const File f (filename);
  372. if (tryToOpenPIP (f))
  373. continue;
  374. if (! isPIPFile (f) && (canOpenFile (f) && openFile (f)))
  375. break;
  376. }
  377. }
  378. bool MainWindow::shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails& sourceDetails,
  379. StringArray& files, bool& canMoveFiles)
  380. {
  381. if (auto* tv = dynamic_cast<TreeView*> (sourceDetails.sourceComponent.get()))
  382. {
  383. Array<JucerTreeViewBase*> selected;
  384. for (int i = tv->getNumSelectedItems(); --i >= 0;)
  385. if (auto* b = dynamic_cast<JucerTreeViewBase*> (tv->getSelectedItem(i)))
  386. selected.add (b);
  387. if (! selected.isEmpty())
  388. {
  389. for (int i = selected.size(); --i >= 0;)
  390. {
  391. if (auto* jtvb = selected.getUnchecked(i))
  392. {
  393. auto f = jtvb->getDraggableFile();
  394. if (f.existsAsFile())
  395. files.add (f.getFullPathName());
  396. }
  397. }
  398. canMoveFiles = false;
  399. return ! files.isEmpty();
  400. }
  401. }
  402. return false;
  403. }
  404. void MainWindow::activeWindowStatusChanged()
  405. {
  406. DocumentWindow::activeWindowStatusChanged();
  407. if (auto* pcc = getProjectContentComponent())
  408. pcc->updateMissingFileStatuses();
  409. ProjucerApplication::getApp().openDocumentManager.reloadModifiedFiles();
  410. }
  411. void MainWindow::showStartPage()
  412. {
  413. jassert (currentProject == nullptr);
  414. setContentOwned (createNewProjectWizardComponent(), true);
  415. centreWithSize (900, 630);
  416. setVisible (true);
  417. addToDesktop();
  418. getContentComponent()->grabKeyboardFocus();
  419. }
  420. void MainWindow::showLoginFormOverlay()
  421. {
  422. blurOverlayComponent = std::make_unique<BlurOverlayWithComponent> (*this, std::make_unique<LoginFormComponent> (*this));
  423. loginFormOpen = true;
  424. }
  425. void MainWindow::hideLoginFormOverlay()
  426. {
  427. blurOverlayComponent.reset();
  428. loginFormOpen = false;
  429. }
  430. //==============================================================================
  431. ApplicationCommandTarget* MainWindow::getNextCommandTarget()
  432. {
  433. return nullptr;
  434. }
  435. void MainWindow::getAllCommands (Array <CommandID>& commands)
  436. {
  437. const CommandID ids[] =
  438. {
  439. CommandIDs::closeWindow,
  440. CommandIDs::goToPreviousWindow,
  441. CommandIDs::goToNextWindow
  442. };
  443. commands.addArray (ids, numElementsInArray (ids));
  444. }
  445. void MainWindow::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  446. {
  447. switch (commandID)
  448. {
  449. case CommandIDs::closeWindow:
  450. result.setInfo ("Close Window", "Closes the current window", CommandCategories::general, 0);
  451. result.defaultKeypresses.add (KeyPress ('w', ModifierKeys::commandModifier, 0));
  452. break;
  453. case CommandIDs::goToPreviousWindow:
  454. result.setInfo ("Previous Window", "Activates the previous window", CommandCategories::general, 0);
  455. result.setActive (ProjucerApplication::getApp().mainWindowList.windows.size() > 1);
  456. result.defaultKeypresses.add (KeyPress (KeyPress::tabKey, ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier, 0));
  457. break;
  458. case CommandIDs::goToNextWindow:
  459. result.setInfo ("Next Window", "Activates the next window", CommandCategories::general, 0);
  460. result.setActive (ProjucerApplication::getApp().mainWindowList.windows.size() > 1);
  461. result.defaultKeypresses.add (KeyPress (KeyPress::tabKey, ModifierKeys::ctrlModifier, 0));
  462. break;
  463. default:
  464. break;
  465. }
  466. }
  467. bool MainWindow::perform (const InvocationInfo& info)
  468. {
  469. switch (info.commandID)
  470. {
  471. case CommandIDs::closeWindow:
  472. closeButtonPressed();
  473. break;
  474. case CommandIDs::goToPreviousWindow:
  475. ProjucerApplication::getApp().mainWindowList.goToSiblingWindow (this, -1);
  476. break;
  477. case CommandIDs::goToNextWindow:
  478. ProjucerApplication::getApp().mainWindowList.goToSiblingWindow (this, 1);
  479. break;
  480. default:
  481. return false;
  482. }
  483. return true;
  484. }
  485. void MainWindow::valueChanged (Value& value)
  486. {
  487. if (value == projectNameValue)
  488. setName (currentProject != nullptr ? currentProject->getProjectNameString() + " - Projucer"
  489. : "Projucer");
  490. }
  491. //==============================================================================
  492. MainWindowList::MainWindowList()
  493. {
  494. }
  495. void MainWindowList::forceCloseAllWindows()
  496. {
  497. windows.clear();
  498. }
  499. bool MainWindowList::askAllWindowsToClose()
  500. {
  501. saveCurrentlyOpenProjectList();
  502. while (windows.size() > 0)
  503. {
  504. if (! windows[0]->closeCurrentProject (OpenDocumentManager::SaveIfNeeded::yes))
  505. return false;
  506. windows.remove (0);
  507. }
  508. return true;
  509. }
  510. void MainWindowList::createWindowIfNoneAreOpen()
  511. {
  512. if (windows.isEmpty())
  513. createNewMainWindow()->showStartPage();
  514. }
  515. void MainWindowList::closeWindow (MainWindow* w)
  516. {
  517. jassert (windows.contains (w));
  518. #if ! JUCE_MAC
  519. if (windows.size() == 1 && ! isInReopenLastProjects)
  520. {
  521. JUCEApplicationBase::getInstance()->systemRequestedQuit();
  522. }
  523. else
  524. #endif
  525. {
  526. if (w->closeCurrentProject (OpenDocumentManager::SaveIfNeeded::yes))
  527. {
  528. windows.removeObject (w);
  529. saveCurrentlyOpenProjectList();
  530. }
  531. }
  532. }
  533. void MainWindowList::goToSiblingWindow (MainWindow* w, int delta)
  534. {
  535. auto index = windows.indexOf (w);
  536. if (index >= 0)
  537. if (auto* next = windows[(index + delta + windows.size()) % windows.size()])
  538. next->toFront (true);
  539. }
  540. void MainWindowList::openDocument (OpenDocumentManager::Document* doc, bool grabFocus)
  541. {
  542. auto& desktop = Desktop::getInstance();
  543. for (int i = desktop.getNumComponents(); --i >= 0;)
  544. {
  545. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  546. {
  547. if (auto* pcc = mw->getProjectContentComponent())
  548. {
  549. if (pcc->hasFileInRecentList (doc->getFile()))
  550. {
  551. mw->toFront (true);
  552. mw->getProjectContentComponent()->showDocument (doc, grabFocus);
  553. return;
  554. }
  555. }
  556. }
  557. }
  558. getFrontmostWindow()->getProjectContentComponent()->showDocument (doc, grabFocus);
  559. }
  560. bool MainWindowList::openFile (const File& file, bool openInBackground)
  561. {
  562. for (auto* w : windows)
  563. {
  564. if (w->getProject() != nullptr && w->getProject()->getFile() == file)
  565. {
  566. w->toFront (true);
  567. return true;
  568. }
  569. }
  570. if (file.hasFileExtension (Project::projectFileExtension))
  571. {
  572. WeakReference<Component> previousFrontWindow (getFrontmostWindow());
  573. auto* w = getOrCreateEmptyWindow();
  574. jassert (w != nullptr);
  575. if (w->openFile (file))
  576. {
  577. w->makeVisible();
  578. checkWindowBounds (*w);
  579. if (openInBackground && previousFrontWindow != nullptr)
  580. previousFrontWindow->toFront (true);
  581. return true;
  582. }
  583. closeWindow (w);
  584. return false;
  585. }
  586. if (getFrontmostWindow()->tryToOpenPIP (file))
  587. return true;
  588. if (! isPIPFile (file) && file.exists())
  589. return getFrontmostWindow()->openFile (file);
  590. return false;
  591. }
  592. MainWindow* MainWindowList::createNewMainWindow()
  593. {
  594. windows.add (new MainWindow());
  595. return windows.getLast();
  596. }
  597. MainWindow* MainWindowList::getFrontmostWindow (bool createIfNotFound)
  598. {
  599. if (windows.isEmpty())
  600. {
  601. if (createIfNotFound)
  602. {
  603. auto* w = createNewMainWindow();
  604. jassert (w != nullptr);
  605. w->makeVisible();
  606. checkWindowBounds (*w);
  607. return w;
  608. }
  609. return nullptr;
  610. }
  611. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  612. {
  613. auto* mw = dynamic_cast<MainWindow*> (Desktop::getInstance().getComponent (i));
  614. if (windows.contains (mw))
  615. return mw;
  616. }
  617. return windows.getLast();
  618. }
  619. MainWindow* MainWindowList::getOrCreateEmptyWindow()
  620. {
  621. if (windows.size() == 0)
  622. return createNewMainWindow();
  623. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  624. {
  625. auto* mw = dynamic_cast<MainWindow*> (Desktop::getInstance().getComponent (i));
  626. if (windows.contains (mw) && mw->getProject() == nullptr)
  627. return mw;
  628. }
  629. return createNewMainWindow();
  630. }
  631. MainWindow* MainWindowList::getMainWindowForFile (const File& file)
  632. {
  633. if (windows.size() > 0)
  634. {
  635. for (auto* window : windows)
  636. {
  637. if (auto* project = window->getProject())
  638. {
  639. if (project->getFile() == file)
  640. return window;
  641. }
  642. }
  643. }
  644. return nullptr;
  645. }
  646. MainWindow* MainWindowList::getMainWindowWithLoginFormOpen()
  647. {
  648. for (auto* window : windows)
  649. if (window->isShowingLoginForm())
  650. return window;
  651. return nullptr;
  652. }
  653. void MainWindowList::checkWindowBounds (MainWindow& windowToCheck)
  654. {
  655. auto avoidSuperimposedWindows = [&]
  656. {
  657. for (auto* otherWindow : windows)
  658. {
  659. if (otherWindow == nullptr || otherWindow == &windowToCheck)
  660. continue;
  661. auto boundsToCheck = windowToCheck.getScreenBounds();
  662. auto otherBounds = otherWindow->getScreenBounds();
  663. if (std::abs (boundsToCheck.getX() - otherBounds.getX()) < 3
  664. && std::abs (boundsToCheck.getY() - otherBounds.getY()) < 3
  665. && std::abs (boundsToCheck.getRight() - otherBounds.getRight()) < 3
  666. && std::abs (boundsToCheck.getBottom() - otherBounds.getBottom()) < 3)
  667. {
  668. int dx = 40, dy = 30;
  669. if (otherBounds.getCentreX() >= boundsToCheck.getCentreX()) dx = -dx;
  670. if (otherBounds.getCentreY() >= boundsToCheck.getCentreY()) dy = -dy;
  671. windowToCheck.setBounds (boundsToCheck.translated (dx, dy));
  672. }
  673. }
  674. };
  675. auto ensureWindowIsFullyOnscreen = [&]
  676. {
  677. auto windowBounds = windowToCheck.getScreenBounds();
  678. auto screenLimits = Desktop::getInstance().getDisplays().findDisplayForRect (windowBounds).userArea;
  679. if (auto* peer = windowToCheck.getPeer())
  680. peer->getFrameSize().subtractFrom (screenLimits);
  681. auto constrainedX = jlimit (screenLimits.getX(), jmax (screenLimits.getX(), screenLimits.getRight() - windowBounds.getWidth()), windowBounds.getX());
  682. auto constrainedY = jlimit (screenLimits.getY(), jmax (screenLimits.getY(), screenLimits.getBottom() - windowBounds.getHeight()), windowBounds.getY());
  683. Point<int> constrainedTopLeft (constrainedX, constrainedY);
  684. if (windowBounds.getPosition() != constrainedTopLeft)
  685. windowToCheck.setTopLeftPosition (constrainedTopLeft);
  686. };
  687. avoidSuperimposedWindows();
  688. ensureWindowIsFullyOnscreen();
  689. }
  690. void MainWindowList::saveCurrentlyOpenProjectList()
  691. {
  692. Array<File> projects;
  693. auto& desktop = Desktop::getInstance();
  694. for (int i = 0; i < desktop.getNumComponents(); ++i)
  695. {
  696. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  697. if (auto* p = mw->getProject())
  698. if (! p->isTemporaryProject())
  699. projects.add (p->getFile());
  700. }
  701. getAppSettings().setLastProjects (projects);
  702. }
  703. void MainWindowList::reopenLastProjects()
  704. {
  705. const ScopedValueSetter<bool> setter (isInReopenLastProjects, true);
  706. for (auto& p : getAppSettings().getLastProjects())
  707. if (p.existsAsFile())
  708. openFile (p, true);
  709. }
  710. void MainWindowList::sendLookAndFeelChange()
  711. {
  712. for (auto* w : windows)
  713. w->sendLookAndFeelChange();
  714. }
  715. Project* MainWindowList::getFrontmostProject()
  716. {
  717. auto& desktop = Desktop::getInstance();
  718. for (int i = desktop.getNumComponents(); --i >= 0;)
  719. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  720. if (auto* p = mw->getProject())
  721. return p;
  722. return nullptr;
  723. }