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.

1066 lines
32KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - 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 the technical preview this file cannot be licensed commercially.
  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 "StartPage/jucer_StartPageComponent.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. enterModalState();
  40. }
  41. void resized() override
  42. {
  43. setBounds (mainWindow.getLocalBounds());
  44. componentToShow->centreWithSize (componentToShow->getWidth(), componentToShow->getHeight());
  45. refreshBackgroundImage();
  46. }
  47. void paint (Graphics& g) override
  48. {
  49. g.drawImage (componentImage, getLocalBounds().toFloat());
  50. }
  51. void inputAttemptWhenModal() override
  52. {
  53. mainWindow.hideLoginFormOverlay();
  54. }
  55. private:
  56. void componentPeerChanged() override {}
  57. void componentVisibilityChanged() override {}
  58. using ComponentMovementWatcher::componentVisibilityChanged;
  59. void componentMovedOrResized (bool, bool) override { triggerAsyncUpdate(); }
  60. using ComponentMovementWatcher::componentMovedOrResized;
  61. void handleAsyncUpdate() override { resized(); }
  62. void mouseUp (const MouseEvent& event) override
  63. {
  64. if (event.eventComponent == this)
  65. mainWindow.hideLoginFormOverlay();
  66. }
  67. void lookAndFeelChanged() override
  68. {
  69. refreshBackgroundImage();
  70. repaint();
  71. }
  72. void refreshBackgroundImage()
  73. {
  74. setAlwaysOnTop (false);
  75. toBack();
  76. auto parentBounds = mainWindow.getBounds();
  77. componentImage = mainWindow.createComponentSnapshot (mainWindow.getLocalBounds())
  78. .rescaled (roundToInt ((float) parentBounds.getWidth() / 1.75f),
  79. roundToInt ((float) parentBounds.getHeight() / 1.75f));
  80. kernel.applyToImage (componentImage, componentImage, getLocalBounds());
  81. setAlwaysOnTop (true);
  82. toFront (true);
  83. }
  84. //==============================================================================
  85. MainWindow& mainWindow;
  86. std::unique_ptr<Component> componentToShow;
  87. ImageConvolutionKernel kernel { 3 };
  88. Image componentImage;
  89. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlurOverlayWithComponent)
  90. };
  91. //==============================================================================
  92. MainWindow::MainWindow()
  93. : DocumentWindow (ProjucerApplication::getApp().getApplicationName(),
  94. ProjucerApplication::getApp().lookAndFeel.getCurrentColourScheme()
  95. .getUIColour (LookAndFeel_V4::ColourScheme::UIColour::windowBackground),
  96. DocumentWindow::allButtons,
  97. false)
  98. {
  99. setUsingNativeTitleBar (true);
  100. setResizable (true, false);
  101. setResizeLimits (600, 500, 32000, 32000);
  102. #if ! JUCE_MAC
  103. setMenuBar (ProjucerApplication::getApp().getMenuModel());
  104. #endif
  105. createProjectContentCompIfNeeded();
  106. auto& commandManager = ProjucerApplication::getCommandManager();
  107. auto registerAllAppCommands = [&]
  108. {
  109. commandManager.registerAllCommandsForTarget (this);
  110. commandManager.registerAllCommandsForTarget (getProjectContentComponent());
  111. };
  112. auto updateAppKeyMappings = [&]
  113. {
  114. commandManager.getKeyMappings()->resetToDefaultMappings();
  115. if (auto keys = getGlobalProperties().getXmlValue ("keyMappings"))
  116. commandManager.getKeyMappings()->restoreFromXml (*keys);
  117. addKeyListener (commandManager.getKeyMappings());
  118. };
  119. registerAllAppCommands();
  120. updateAppKeyMappings();
  121. setWantsKeyboardFocus (false);
  122. getLookAndFeel().setColour (ColourSelector::backgroundColourId, Colours::transparentBlack);
  123. projectNameValue.addListener (this);
  124. centreWithSize (800, 600);
  125. }
  126. MainWindow::~MainWindow()
  127. {
  128. #if ! JUCE_MAC
  129. setMenuBar (nullptr);
  130. #endif
  131. removeKeyListener (ProjucerApplication::getCommandManager().getKeyMappings());
  132. // save the current size and position to our settings file..
  133. getGlobalProperties().setValue ("lastMainWindowPos", getWindowStateAsString());
  134. clearContentComponent();
  135. }
  136. void MainWindow::createProjectContentCompIfNeeded()
  137. {
  138. if (getProjectContentComponent() == nullptr)
  139. {
  140. clearContentComponent();
  141. setContentOwned (new ProjectContentComponent(), false);
  142. }
  143. }
  144. void MainWindow::updateTitleBarIcon()
  145. {
  146. if (auto* peer = getPeer())
  147. {
  148. if (currentProject != nullptr)
  149. {
  150. peer->setRepresentedFile (currentProject->getFile());
  151. peer->setIcon (ImageCache::getFromMemory (BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize));
  152. }
  153. else
  154. {
  155. peer->setRepresentedFile ({});
  156. }
  157. }
  158. }
  159. void MainWindow::makeVisible()
  160. {
  161. setVisible (true);
  162. addToDesktop();
  163. restoreWindowPosition();
  164. updateTitleBarIcon();
  165. getContentComponent()->grabKeyboardFocus();
  166. }
  167. ProjectContentComponent* MainWindow::getProjectContentComponent() const
  168. {
  169. return dynamic_cast<ProjectContentComponent*> (getContentComponent());
  170. }
  171. void MainWindow::closeButtonPressed()
  172. {
  173. ProjucerApplication::getApp().mainWindowList.closeWindow (this);
  174. }
  175. void MainWindow::closeCurrentProject (OpenDocumentManager::SaveIfNeeded askUserToSave, std::function<void (bool)> callback)
  176. {
  177. if (currentProject == nullptr)
  178. {
  179. if (callback != nullptr)
  180. callback (true);
  181. return;
  182. }
  183. currentProject->getStoredProperties().setValue (getProjectWindowPosName(), getWindowStateAsString());
  184. if (auto* pcc = getProjectContentComponent())
  185. {
  186. pcc->saveOpenDocumentList();
  187. pcc->hideEditor();
  188. }
  189. ProjucerApplication::getApp().openDocumentManager
  190. .closeAllDocumentsUsingProjectAsync (*currentProject,
  191. askUserToSave,
  192. [parent = SafePointer<MainWindow> { this }, askUserToSave, callback] (bool closedSuccessfully)
  193. {
  194. if (parent == nullptr)
  195. return;
  196. if (! closedSuccessfully)
  197. {
  198. if (callback != nullptr)
  199. callback (false);
  200. return;
  201. }
  202. auto setProjectAndCallback = [parent, callback]
  203. {
  204. parent->setProject (nullptr);
  205. if (callback != nullptr)
  206. callback (true);
  207. };
  208. if (askUserToSave == OpenDocumentManager::SaveIfNeeded::no)
  209. {
  210. setProjectAndCallback();
  211. return;
  212. }
  213. parent->currentProject->saveIfNeededAndUserAgreesAsync ([parent, setProjectAndCallback, callback] (FileBasedDocument::SaveResult saveResult)
  214. {
  215. if (parent == nullptr)
  216. return;
  217. if (saveResult == FileBasedDocument::savedOk)
  218. setProjectAndCallback();
  219. else if (callback != nullptr)
  220. callback (false);
  221. });
  222. });
  223. }
  224. void MainWindow::moveProject (File newProjectFileToOpen, OpenInIDE openInIDE)
  225. {
  226. closeCurrentProject (OpenDocumentManager::SaveIfNeeded::no,
  227. [parent = SafePointer<MainWindow> { this }, newProjectFileToOpen, openInIDE] (bool)
  228. {
  229. if (parent == nullptr)
  230. return;
  231. parent->openFile (newProjectFileToOpen, [parent, openInIDE] (bool openedSuccessfully)
  232. {
  233. if (! (openedSuccessfully && parent != nullptr && parent->currentProject != nullptr && openInIDE == OpenInIDE::yes))
  234. return;
  235. // The project component knows how to process the saveAndOpenInIDE command, but the
  236. // main application does not. In order to process the command successfully, we need
  237. // to ensure that the project content component has focus.
  238. auto& manager = ProjucerApplication::getApp().getCommandManager();
  239. manager.setFirstCommandTarget (parent->getProjectContentComponent());
  240. ProjucerApplication::getApp().getCommandManager().invokeDirectly (CommandIDs::saveAndOpenInIDE, false);
  241. manager.setFirstCommandTarget (nullptr);
  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. if (const auto frameSize = peer->getFrameSizeIfPresent())
  800. frameSize->subtractFrom (screenLimits);
  801. auto constrainedX = jlimit (screenLimits.getX(), jmax (screenLimits.getX(), screenLimits.getRight() - windowBounds.getWidth()), windowBounds.getX());
  802. auto constrainedY = jlimit (screenLimits.getY(), jmax (screenLimits.getY(), screenLimits.getBottom() - windowBounds.getHeight()), windowBounds.getY());
  803. Point<int> constrainedTopLeft (constrainedX, constrainedY);
  804. if (windowBounds.getPosition() != constrainedTopLeft)
  805. windowToCheck.setTopLeftPosition (constrainedTopLeft);
  806. };
  807. avoidSuperimposedWindows();
  808. ensureWindowIsFullyOnscreen();
  809. }
  810. void MainWindowList::saveCurrentlyOpenProjectList()
  811. {
  812. Array<File> projects;
  813. auto& desktop = Desktop::getInstance();
  814. for (int i = 0; i < desktop.getNumComponents(); ++i)
  815. {
  816. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  817. if (auto* p = mw->getProject())
  818. if (! p->isTemporaryProject())
  819. projects.add (p->getFile());
  820. }
  821. getAppSettings().setLastProjects (projects);
  822. }
  823. void MainWindowList::reopenLastProjects()
  824. {
  825. const ScopedValueSetter<bool> setter (isInReopenLastProjects, true);
  826. for (auto& p : getAppSettings().getLastProjects())
  827. if (p.existsAsFile())
  828. openFile (p, nullptr, true);
  829. }
  830. void MainWindowList::sendLookAndFeelChange()
  831. {
  832. for (auto* w : windows)
  833. w->sendLookAndFeelChange();
  834. }
  835. Project* MainWindowList::getFrontmostProject()
  836. {
  837. auto& desktop = Desktop::getInstance();
  838. for (int i = desktop.getNumComponents(); --i >= 0;)
  839. if (auto* mw = dynamic_cast<MainWindow*> (desktop.getComponent(i)))
  840. if (auto* p = mw->getProject())
  841. return p;
  842. return nullptr;
  843. }