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.

1073 lines
32KB

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