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.

1067 lines
32KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - 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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-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 (parent == nullptr)
  239. return;
  240. if (openedSuccessfully && parent->currentProject != nullptr && openInIDE == OpenInIDE::yes)
  241. ProjucerApplication::getApp().getCommandManager().invokeDirectly (CommandIDs::saveAndOpenInIDE, false);
  242. });
  243. });
  244. }
  245. void MainWindow::setProject (std::unique_ptr<Project> newProject)
  246. {
  247. if (newProject == nullptr)
  248. {
  249. if (auto* content = getProjectContentComponent())
  250. content->setProject (nullptr);
  251. currentProject.reset();
  252. }
  253. else
  254. {
  255. currentProject = std::move (newProject);
  256. createProjectContentCompIfNeeded();
  257. getProjectContentComponent()->setProject (currentProject.get());
  258. }
  259. if (currentProject != nullptr)
  260. currentProject->addChangeListener (this);
  261. changeListenerCallback (currentProject.get());
  262. projectNameValue.referTo (currentProject != nullptr ? currentProject->getProjectValue (Ids::name) : Value());
  263. initialiseProjectWindow();
  264. ProjucerApplication::getCommandManager().commandStatusChanged();
  265. }
  266. void MainWindow::restoreWindowPosition()
  267. {
  268. String windowState;
  269. if (currentProject != nullptr)
  270. windowState = currentProject->getStoredProperties().getValue (getProjectWindowPosName());
  271. if (windowState.isEmpty())
  272. windowState = getGlobalProperties().getValue ("lastMainWindowPos");
  273. restoreWindowStateFromString (windowState);
  274. }
  275. bool MainWindow::canOpenFile (const File& file) const
  276. {
  277. return (! file.isDirectory())
  278. && (file.hasFileExtension (Project::projectFileExtension)
  279. || ProjucerApplication::getApp().openDocumentManager.canOpenFile (file));
  280. }
  281. void MainWindow::openFile (const File& file, std::function<void (bool)> callback)
  282. {
  283. if (file.hasFileExtension (Project::projectFileExtension))
  284. {
  285. auto newDoc = std::make_unique<Project> (file);
  286. auto result = newDoc->loadFrom (file, true);
  287. if (result.wasOk())
  288. {
  289. closeCurrentProject (OpenDocumentManager::SaveIfNeeded::yes,
  290. [parent = SafePointer<MainWindow> { this },
  291. sharedDoc = std::make_shared<std::unique_ptr<Project>> (std::move (newDoc)),
  292. callback] (bool saveResult)
  293. {
  294. if (parent == nullptr)
  295. return;
  296. if (saveResult)
  297. {
  298. parent->setProject (std::move (*sharedDoc.get()));
  299. parent->currentProject->setChangedFlag (false);
  300. parent->createProjectContentCompIfNeeded();
  301. parent->getProjectContentComponent()->reloadLastOpenDocuments();
  302. parent->currentProject->updateDeprecatedProjectSettingsInteractively();
  303. }
  304. if (callback != nullptr)
  305. callback (saveResult);
  306. });
  307. return;
  308. }
  309. if (callback != nullptr)
  310. callback (false);
  311. return;
  312. }
  313. if (file.exists())
  314. {
  315. SafePointer<MainWindow> parent { this };
  316. auto createCompAndShowEditor = [parent, file, callback]
  317. {
  318. if (parent != nullptr)
  319. {
  320. parent->createProjectContentCompIfNeeded();
  321. if (callback != nullptr)
  322. callback (parent->getProjectContentComponent()->showEditorForFile (file, true));
  323. }
  324. };
  325. if (isPIPFile (file))
  326. {
  327. openPIP (file, [parent, createCompAndShowEditor, callback] (bool openedSuccessfully)
  328. {
  329. if (parent == nullptr)
  330. return;
  331. if (openedSuccessfully)
  332. {
  333. if (callback != nullptr)
  334. callback (true);
  335. return;
  336. }
  337. createCompAndShowEditor();
  338. });
  339. return;
  340. }
  341. createCompAndShowEditor();
  342. return;
  343. }
  344. if (callback != nullptr)
  345. callback (false);
  346. }
  347. void MainWindow::openPIP (const File& pipFile, std::function<void (bool)> callback)
  348. {
  349. auto generator = std::make_shared<PIPGenerator> (pipFile);
  350. if (! generator->hasValidPIP())
  351. {
  352. if (callback != nullptr)
  353. callback (false);
  354. return;
  355. }
  356. auto generatorResult = generator->createJucerFile();
  357. if (generatorResult != Result::ok())
  358. {
  359. AlertWindow::showMessageBoxAsync (MessageBoxIconType::WarningIcon,
  360. "PIP Error.",
  361. generatorResult.getErrorMessage());
  362. if (callback != nullptr)
  363. callback (false);
  364. return;
  365. }
  366. if (! generator->createMainCpp())
  367. {
  368. AlertWindow::showMessageBoxAsync (MessageBoxIconType::WarningIcon,
  369. "PIP Error.",
  370. "Failed to create Main.cpp.");
  371. if (callback != nullptr)
  372. callback (false);
  373. return;
  374. }
  375. openFile (generator->getJucerFile(), [parent = SafePointer<MainWindow> { this }, generator, callback] (bool openedSuccessfully)
  376. {
  377. if (parent == nullptr)
  378. return;
  379. if (! openedSuccessfully)
  380. {
  381. AlertWindow::showMessageBoxAsync (MessageBoxIconType::WarningIcon,
  382. "PIP Error.",
  383. "Failed to open .jucer file.");
  384. if (callback != nullptr)
  385. callback (false);
  386. return;
  387. }
  388. parent->setupTemporaryPIPProject (*generator);
  389. if (callback != nullptr)
  390. callback (true);
  391. });
  392. }
  393. void MainWindow::setupTemporaryPIPProject (PIPGenerator& generator)
  394. {
  395. jassert (currentProject != nullptr);
  396. currentProject->setTemporaryDirectory (generator.getOutputDirectory());
  397. if (auto* pcc = getProjectContentComponent())
  398. {
  399. auto fileToDisplay = generator.getPIPFile();
  400. if (fileToDisplay != File())
  401. {
  402. pcc->showEditorForFile (fileToDisplay, true);
  403. if (auto* sourceCodeEditor = dynamic_cast <SourceCodeEditor*> (pcc->getEditorComponent()))
  404. sourceCodeEditor->editor->scrollToLine (findBestLineToScrollToForClass (StringArray::fromLines (fileToDisplay.loadFileAsString()),
  405. generator.getMainClassName(), currentProject->getProjectType().isAudioPlugin()));
  406. }
  407. }
  408. }
  409. bool MainWindow::isInterestedInFileDrag (const StringArray& filenames)
  410. {
  411. for (auto& filename : filenames)
  412. if (canOpenFile (File (filename)))
  413. return true;
  414. return false;
  415. }
  416. static void filesDroppedRecursive (Component::SafePointer<MainWindow> parent, StringArray filenames)
  417. {
  418. if (filenames.isEmpty())
  419. return;
  420. auto f = filenames[0];
  421. filenames.remove (0);
  422. if (! parent->canOpenFile (f))
  423. {
  424. filesDroppedRecursive (parent, filenames);
  425. return;
  426. }
  427. parent->openFile (f, [parent, filenames] (bool openedSuccessfully)
  428. {
  429. if (parent == nullptr || ! openedSuccessfully)
  430. return;
  431. filesDroppedRecursive (parent, filenames);
  432. });
  433. }
  434. void MainWindow::filesDropped (const StringArray& filenames, int /*mouseX*/, int /*mouseY*/)
  435. {
  436. filesDroppedRecursive (this, filenames);
  437. }
  438. bool MainWindow::shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails& sourceDetails,
  439. StringArray& files, bool& canMoveFiles)
  440. {
  441. if (auto* tv = dynamic_cast<TreeView*> (sourceDetails.sourceComponent.get()))
  442. {
  443. Array<JucerTreeViewBase*> selected;
  444. for (int i = tv->getNumSelectedItems(); --i >= 0;)
  445. if (auto* b = dynamic_cast<JucerTreeViewBase*> (tv->getSelectedItem(i)))
  446. selected.add (b);
  447. if (! selected.isEmpty())
  448. {
  449. for (int i = selected.size(); --i >= 0;)
  450. {
  451. if (auto* jtvb = selected.getUnchecked(i))
  452. {
  453. auto f = jtvb->getDraggableFile();
  454. if (f.existsAsFile())
  455. files.add (f.getFullPathName());
  456. }
  457. }
  458. canMoveFiles = false;
  459. return ! files.isEmpty();
  460. }
  461. }
  462. return false;
  463. }
  464. void MainWindow::activeWindowStatusChanged()
  465. {
  466. DocumentWindow::activeWindowStatusChanged();
  467. if (auto* pcc = getProjectContentComponent())
  468. pcc->updateMissingFileStatuses();
  469. ProjucerApplication::getApp().openDocumentManager.reloadModifiedFiles();
  470. }
  471. void MainWindow::initialiseProjectWindow()
  472. {
  473. setResizable (true, false);
  474. updateTitleBarIcon();
  475. }
  476. void MainWindow::showStartPage()
  477. {
  478. jassert (currentProject == nullptr);
  479. setContentOwned (new StartPageComponent ([this] (std::unique_ptr<Project>&& newProject) { setProject (std::move (newProject)); },
  480. [this] (const File& exampleFile) { openFile (exampleFile, nullptr); }),
  481. true);
  482. setResizable (false, false);
  483. setName ("New Project");
  484. addToDesktop();
  485. centreWithSize (getContentComponent()->getWidth(), getContentComponent()->getHeight());
  486. setVisible (true);
  487. getContentComponent()->grabKeyboardFocus();
  488. }
  489. void MainWindow::showLoginFormOverlay()
  490. {
  491. blurOverlayComponent = std::make_unique<BlurOverlayWithComponent> (*this, std::make_unique<LoginFormComponent> (*this));
  492. loginFormOpen = true;
  493. }
  494. void MainWindow::hideLoginFormOverlay()
  495. {
  496. blurOverlayComponent.reset();
  497. loginFormOpen = false;
  498. }
  499. //==============================================================================
  500. ApplicationCommandTarget* MainWindow::getNextCommandTarget()
  501. {
  502. return nullptr;
  503. }
  504. void MainWindow::getAllCommands (Array <CommandID>& commands)
  505. {
  506. const CommandID ids[] =
  507. {
  508. CommandIDs::closeWindow,
  509. CommandIDs::goToPreviousWindow,
  510. CommandIDs::goToNextWindow
  511. };
  512. commands.addArray (ids, numElementsInArray (ids));
  513. }
  514. void MainWindow::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  515. {
  516. switch (commandID)
  517. {
  518. case CommandIDs::closeWindow:
  519. result.setInfo ("Close Window", "Closes the current window", CommandCategories::general, 0);
  520. result.defaultKeypresses.add (KeyPress ('w', ModifierKeys::commandModifier, 0));
  521. break;
  522. case CommandIDs::goToPreviousWindow:
  523. result.setInfo ("Previous Window", "Activates the previous window", CommandCategories::general, 0);
  524. result.setActive (ProjucerApplication::getApp().mainWindowList.windows.size() > 1);
  525. result.defaultKeypresses.add (KeyPress (KeyPress::tabKey, ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier, 0));
  526. break;
  527. case CommandIDs::goToNextWindow:
  528. result.setInfo ("Next Window", "Activates the next window", CommandCategories::general, 0);
  529. result.setActive (ProjucerApplication::getApp().mainWindowList.windows.size() > 1);
  530. result.defaultKeypresses.add (KeyPress (KeyPress::tabKey, ModifierKeys::ctrlModifier, 0));
  531. break;
  532. default:
  533. break;
  534. }
  535. }
  536. bool MainWindow::perform (const InvocationInfo& info)
  537. {
  538. switch (info.commandID)
  539. {
  540. case CommandIDs::closeWindow:
  541. closeButtonPressed();
  542. break;
  543. case CommandIDs::goToPreviousWindow:
  544. ProjucerApplication::getApp().mainWindowList.goToSiblingWindow (this, -1);
  545. break;
  546. case CommandIDs::goToNextWindow:
  547. ProjucerApplication::getApp().mainWindowList.goToSiblingWindow (this, 1);
  548. break;
  549. default:
  550. return false;
  551. }
  552. return true;
  553. }
  554. void MainWindow::valueChanged (Value& value)
  555. {
  556. if (value == projectNameValue)
  557. setName (currentProject != nullptr ? currentProject->getProjectNameString() + " - Projucer"
  558. : "Projucer");
  559. }
  560. void MainWindow::changeListenerCallback (ChangeBroadcaster* source)
  561. {
  562. auto* project = getProject();
  563. if (source == project)
  564. if (auto* peer = getPeer())
  565. peer->setHasChangedSinceSaved (project != nullptr ? project->hasChangedSinceSaved()
  566. : false);
  567. }
  568. //==============================================================================
  569. MainWindowList::MainWindowList()
  570. {
  571. }
  572. void MainWindowList::forceCloseAllWindows()
  573. {
  574. windows.clear();
  575. }
  576. static void askAllWindowsToCloseRecursive (WeakReference<MainWindowList> parent, std::function<void (bool)> callback)
  577. {
  578. if (parent->windows.size() == 0)
  579. {
  580. if (callback != nullptr)
  581. callback (true);
  582. return;
  583. }
  584. parent->windows[0]->closeCurrentProject (OpenDocumentManager::SaveIfNeeded::yes, [parent, callback] (bool closedSuccessfully)
  585. {
  586. if (parent == nullptr)
  587. return;
  588. if (! closedSuccessfully)
  589. {
  590. if (callback != nullptr)
  591. callback (false);
  592. return;
  593. }
  594. parent->windows.remove (0);
  595. askAllWindowsToCloseRecursive (parent, std::move (callback));
  596. });
  597. }
  598. void MainWindowList::askAllWindowsToClose (std::function<void (bool)> callback)
  599. {
  600. saveCurrentlyOpenProjectList();
  601. askAllWindowsToCloseRecursive (this, std::move (callback));
  602. }
  603. void MainWindowList::createWindowIfNoneAreOpen()
  604. {
  605. if (windows.isEmpty())
  606. createNewMainWindow()->showStartPage();
  607. }
  608. void MainWindowList::closeWindow (MainWindow* w)
  609. {
  610. jassert (windows.contains (w));
  611. #if ! JUCE_MAC
  612. if (windows.size() == 1 && ! isInReopenLastProjects)
  613. {
  614. JUCEApplicationBase::getInstance()->systemRequestedQuit();
  615. }
  616. else
  617. #endif
  618. {
  619. w->closeCurrentProject (OpenDocumentManager::SaveIfNeeded::yes,
  620. [parent = WeakReference<MainWindowList> { this }, w] (bool closedSuccessfully)
  621. {
  622. if (parent == nullptr)
  623. return;
  624. if (closedSuccessfully)
  625. {
  626. parent->windows.removeObject (w);
  627. parent->saveCurrentlyOpenProjectList();
  628. }
  629. });
  630. }
  631. }
  632. void MainWindowList::goToSiblingWindow (MainWindow* w, int delta)
  633. {
  634. auto index = windows.indexOf (w);
  635. if (index >= 0)
  636. if (auto* next = windows[(index + delta + windows.size()) % windows.size()])
  637. next->toFront (true);
  638. }
  639. void MainWindowList::openDocument (OpenDocumentManager::Document* doc, bool grabFocus)
  640. {
  641. auto& desktop = Desktop::getInstance();
  642. for (int i = desktop.getNumComponents(); --i >= 0;)
  643. {
  644. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  645. {
  646. if (auto* pcc = mw->getProjectContentComponent())
  647. {
  648. if (pcc->hasFileInRecentList (doc->getFile()))
  649. {
  650. mw->toFront (true);
  651. mw->getProjectContentComponent()->showDocument (doc, grabFocus);
  652. return;
  653. }
  654. }
  655. }
  656. }
  657. getFrontmostWindow()->getProjectContentComponent()->showDocument (doc, grabFocus);
  658. }
  659. void MainWindowList::openFile (const File& file, std::function<void (bool)> callback, bool openInBackground)
  660. {
  661. if (! file.exists())
  662. {
  663. if (callback != nullptr)
  664. callback (false);
  665. return;
  666. }
  667. for (auto* w : windows)
  668. {
  669. if (w->getProject() != nullptr && w->getProject()->getFile() == file)
  670. {
  671. w->toFront (true);
  672. if (callback != nullptr)
  673. callback (true);
  674. return;
  675. }
  676. }
  677. WeakReference<MainWindowList> parent { this };
  678. if (file.hasFileExtension (Project::projectFileExtension)
  679. || isPIPFile (file))
  680. {
  681. WeakReference<Component> previousFrontWindow (getFrontmostWindow());
  682. auto* w = getOrCreateEmptyWindow();
  683. jassert (w != nullptr);
  684. w->openFile (file, [parent, previousFrontWindow, w, openInBackground, callback] (bool openedSuccessfully)
  685. {
  686. if (parent == nullptr)
  687. return;
  688. if (openedSuccessfully)
  689. {
  690. w->makeVisible();
  691. w->setResizable (true, false);
  692. parent->checkWindowBounds (*w);
  693. if (openInBackground && previousFrontWindow != nullptr)
  694. previousFrontWindow->toFront (true);
  695. }
  696. else
  697. {
  698. parent->closeWindow (w);
  699. }
  700. if (callback != nullptr)
  701. callback (openedSuccessfully);
  702. });
  703. return;
  704. }
  705. getFrontmostWindow()->openFile (file, [parent, callback] (bool openedSuccessfully)
  706. {
  707. if (parent != nullptr && callback != nullptr)
  708. callback (openedSuccessfully);
  709. });
  710. }
  711. MainWindow* MainWindowList::createNewMainWindow()
  712. {
  713. windows.add (new MainWindow());
  714. return windows.getLast();
  715. }
  716. MainWindow* MainWindowList::getFrontmostWindow (bool createIfNotFound)
  717. {
  718. if (windows.isEmpty())
  719. {
  720. if (createIfNotFound)
  721. {
  722. auto* w = createNewMainWindow();
  723. jassert (w != nullptr);
  724. w->makeVisible();
  725. checkWindowBounds (*w);
  726. return w;
  727. }
  728. return nullptr;
  729. }
  730. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  731. {
  732. auto* mw = dynamic_cast<MainWindow*> (Desktop::getInstance().getComponent (i));
  733. if (windows.contains (mw))
  734. return mw;
  735. }
  736. return windows.getLast();
  737. }
  738. MainWindow* MainWindowList::getOrCreateEmptyWindow()
  739. {
  740. if (windows.size() == 0)
  741. return createNewMainWindow();
  742. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  743. {
  744. auto* mw = dynamic_cast<MainWindow*> (Desktop::getInstance().getComponent (i));
  745. if (windows.contains (mw) && mw->getProject() == nullptr)
  746. return mw;
  747. }
  748. return createNewMainWindow();
  749. }
  750. MainWindow* MainWindowList::getMainWindowForFile (const File& file)
  751. {
  752. if (windows.size() > 0)
  753. {
  754. for (auto* window : windows)
  755. {
  756. if (auto* project = window->getProject())
  757. {
  758. if (project->getFile() == file)
  759. return window;
  760. }
  761. }
  762. }
  763. return nullptr;
  764. }
  765. MainWindow* MainWindowList::getMainWindowWithLoginFormOpen()
  766. {
  767. for (auto* window : windows)
  768. if (window->isShowingLoginForm())
  769. return window;
  770. return nullptr;
  771. }
  772. void MainWindowList::checkWindowBounds (MainWindow& windowToCheck)
  773. {
  774. auto avoidSuperimposedWindows = [&]
  775. {
  776. for (auto* otherWindow : windows)
  777. {
  778. if (otherWindow == nullptr || otherWindow == &windowToCheck)
  779. continue;
  780. auto boundsToCheck = windowToCheck.getScreenBounds();
  781. auto otherBounds = otherWindow->getScreenBounds();
  782. if (std::abs (boundsToCheck.getX() - otherBounds.getX()) < 3
  783. && std::abs (boundsToCheck.getY() - otherBounds.getY()) < 3
  784. && std::abs (boundsToCheck.getRight() - otherBounds.getRight()) < 3
  785. && std::abs (boundsToCheck.getBottom() - otherBounds.getBottom()) < 3)
  786. {
  787. int dx = 40, dy = 30;
  788. if (otherBounds.getCentreX() >= boundsToCheck.getCentreX()) dx = -dx;
  789. if (otherBounds.getCentreY() >= boundsToCheck.getCentreY()) dy = -dy;
  790. windowToCheck.setBounds (boundsToCheck.translated (dx, dy));
  791. }
  792. }
  793. };
  794. auto ensureWindowIsFullyOnscreen = [&]
  795. {
  796. auto windowBounds = windowToCheck.getScreenBounds();
  797. auto screenLimits = Desktop::getInstance().getDisplays().getDisplayForRect (windowBounds)->userArea;
  798. if (auto* peer = windowToCheck.getPeer())
  799. peer->getFrameSize().subtractFrom (screenLimits);
  800. auto constrainedX = jlimit (screenLimits.getX(), jmax (screenLimits.getX(), screenLimits.getRight() - windowBounds.getWidth()), windowBounds.getX());
  801. auto constrainedY = jlimit (screenLimits.getY(), jmax (screenLimits.getY(), screenLimits.getBottom() - windowBounds.getHeight()), windowBounds.getY());
  802. Point<int> constrainedTopLeft (constrainedX, constrainedY);
  803. if (windowBounds.getPosition() != constrainedTopLeft)
  804. windowToCheck.setTopLeftPosition (constrainedTopLeft);
  805. };
  806. avoidSuperimposedWindows();
  807. ensureWindowIsFullyOnscreen();
  808. }
  809. void MainWindowList::saveCurrentlyOpenProjectList()
  810. {
  811. Array<File> projects;
  812. auto& desktop = Desktop::getInstance();
  813. for (int i = 0; i < desktop.getNumComponents(); ++i)
  814. {
  815. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  816. if (auto* p = mw->getProject())
  817. if (! p->isTemporaryProject())
  818. projects.add (p->getFile());
  819. }
  820. getAppSettings().setLastProjects (projects);
  821. }
  822. void MainWindowList::reopenLastProjects()
  823. {
  824. const ScopedValueSetter<bool> setter (isInReopenLastProjects, true);
  825. for (auto& p : getAppSettings().getLastProjects())
  826. if (p.existsAsFile())
  827. openFile (p, nullptr, true);
  828. }
  829. void MainWindowList::sendLookAndFeelChange()
  830. {
  831. for (auto* w : windows)
  832. w->sendLookAndFeelChange();
  833. }
  834. Project* MainWindowList::getFrontmostProject()
  835. {
  836. auto& desktop = Desktop::getInstance();
  837. for (int i = desktop.getNumComponents(); --i >= 0;)
  838. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  839. if (auto* p = mw->getProject())
  840. return p;
  841. return nullptr;
  842. }