Application.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Application.h>
  9. #include <ProjectUtils.h>
  10. #include <AzCore/IO/FileIO.h>
  11. #include <AzCore/Utils/Utils.h>
  12. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  13. #include <AzFramework/Logging/LoggingComponent.h>
  14. #include <AzQtComponents/Utilities/HandleDpiAwareness.h>
  15. #include <AzQtComponents/Components/StyleManager.h>
  16. #include <AzQtComponents/Components/WindowDecorationWrapper.h>
  17. #include <ProjectManager_Traits_Platform.h>
  18. #include <QApplication>
  19. #include <QDir>
  20. #include <QMessageBox>
  21. #include <QInputDialog>
  22. #include <QIcon>
  23. namespace O3DE::ProjectManager
  24. {
  25. Application::~Application()
  26. {
  27. TearDown();
  28. }
  29. bool Application::Init(bool interactive, AZStd::unique_ptr<PythonBindings> pythonBindings)
  30. {
  31. constexpr const char* applicationName { "O3DE" };
  32. QApplication::setOrganizationName(applicationName);
  33. QApplication::setOrganizationDomain("o3de.org");
  34. QCoreApplication::setApplicationName(applicationName);
  35. QCoreApplication::setApplicationVersion("1.0");
  36. // Use the LogComponent for non-dev logging log
  37. RegisterComponentDescriptor(AzFramework::LogComponent::CreateDescriptor());
  38. // set the log alias to .o3de/Logs instead of the default user/logs
  39. AZ::IO::FixedMaxPath path = AZ::Utils::GetO3deLogsDirectory();
  40. // DevWriteStorage is where the event log is written during development
  41. m_settingsRegistry->Set(AZ::SettingsRegistryMergeUtils::FilePathKey_DevWriteStorage, path.LexicallyNormal().Native());
  42. // Save event logs to .o3de/Logs/eventlogger/EventLogO3DE.azsl
  43. m_settingsRegistry->Set(AZ::SettingsRegistryMergeUtils::BuildTargetNameKey, applicationName);
  44. Start(AzFramework::Application::Descriptor());
  45. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  46. QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  47. QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  48. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  49. AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware);
  50. // Create the actual Qt Application - this needs to happen before using QMessageBox
  51. m_app.reset(new QApplication(*GetArgC(), *GetArgV()));
  52. if(!InitLog(applicationName))
  53. {
  54. AZ_Warning("ProjectManager", false, "Failed to init logging");
  55. }
  56. // Set window icon after QGuiApplication is created otherwise QPixmap for the icon fails to intialize
  57. QApplication::setWindowIcon(QIcon(":/ProjectManager-Icon.ico"));
  58. // unit tests may provide custom python bindings
  59. m_pythonBindings = pythonBindings ? AZStd::move(pythonBindings) : AZStd::make_unique<PythonBindings>(GetEngineRoot());
  60. // If the first attempt of starting python failed, then attempt to bootstrap python by
  61. // calling the get python script
  62. if (!m_pythonBindings->PythonStarted())
  63. {
  64. auto getPythonResult = ProjectUtils::RunGetPythonScript(GetEngineRoot());
  65. if (getPythonResult.IsSuccess())
  66. {
  67. // If the bootstrap for python was successful, then attempt to start python again
  68. m_pythonBindings->StartPython();
  69. }
  70. }
  71. if (!m_pythonBindings->PythonStarted())
  72. {
  73. if (interactive)
  74. {
  75. QMessageBox::critical(nullptr, QObject::tr("Failed to start Python"),
  76. QObject::tr("This tool requires an O3DE engine with a Python runtime, "
  77. "but was unable to automatically install O3DE's built-in Python."
  78. "You can troubleshoot this issue by trying to manually install O3DE's built-in "
  79. "Python by running the '%1' script.")
  80. .arg(GetPythonScriptPath));
  81. }
  82. return false;
  83. }
  84. m_settings = AZStd::make_unique<Settings>();
  85. if (!RegisterEngine(interactive))
  86. {
  87. return false;
  88. }
  89. const AZ::CommandLine* commandLine = GetCommandLine();
  90. AZ_Assert(commandLine, "Failed to get command line");
  91. ProjectManagerScreen startScreen = ProjectManagerScreen::Projects;
  92. if (size_t screenSwitchCount = commandLine->GetNumSwitchValues("screen"); screenSwitchCount > 0)
  93. {
  94. QString screenOption = commandLine->GetSwitchValue("screen", screenSwitchCount - 1).c_str();
  95. ProjectManagerScreen screen = ProjectUtils::GetProjectManagerScreen(screenOption);
  96. if (screen != ProjectManagerScreen::Invalid)
  97. {
  98. startScreen = screen;
  99. }
  100. }
  101. AZ::IO::FixedMaxPath projectPath;
  102. if (size_t projectSwitchCount = commandLine->GetNumSwitchValues("project-path"); projectSwitchCount > 0)
  103. {
  104. projectPath = commandLine->GetSwitchValue("project-path", projectSwitchCount - 1).c_str();
  105. }
  106. m_mainWindow.reset(new ProjectManagerWindow(nullptr, projectPath, startScreen));
  107. return true;
  108. }
  109. bool Application::InitLog(const char* logName)
  110. {
  111. if (!m_entity)
  112. {
  113. // override the log alias to the O3de Logs directory instead of the default project user/Logs folder
  114. AZ::IO::FixedMaxPath path = AZ::Utils::GetO3deLogsDirectory();
  115. AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
  116. AZ_Assert(fileIO, "Failed to get FileIOBase instance");
  117. fileIO->SetAlias("@log@", path.LexicallyNormal().Native().c_str());
  118. // this entity exists because we need a home for LogComponent
  119. // and cannot use the system entity because we need to be able to call SetLogFileBaseName
  120. // so the log will be named O3DE.log
  121. m_entity = aznew AZ::Entity("Application Entity");
  122. if (m_entity)
  123. {
  124. AzFramework::LogComponent* logger = aznew AzFramework::LogComponent();
  125. AZ_Assert(logger, "Failed to create LogComponent");
  126. logger->SetLogFileBaseName(logName);
  127. m_entity->AddComponent(logger);
  128. m_entity->Init();
  129. m_entity->Activate();
  130. }
  131. }
  132. return m_entity != nullptr;
  133. }
  134. bool Application::RegisterEngine(bool interactive)
  135. {
  136. auto engineInfoOutcome = m_pythonBindings->GetEngineInfo();
  137. if (!engineInfoOutcome)
  138. {
  139. if (interactive)
  140. {
  141. QMessageBox::critical(nullptr,
  142. QObject::tr("Failed to get engine info"),
  143. QObject::tr("A valid engine.json could not be found or loaded. "
  144. "Please verify a valid engine.json file exists in %1")
  145. .arg(GetEngineRoot()));
  146. }
  147. AZ_Error("Project Manager", false, "Failed to get engine info");
  148. return false;
  149. }
  150. EngineInfo engineInfo = engineInfoOutcome.GetValue();
  151. if (engineInfo.m_registered)
  152. {
  153. return true;
  154. }
  155. // We no longer force registration because we no longer require that only one engine can
  156. // be registered with each engine name
  157. constexpr bool forceRegistration = false;
  158. auto registerOutcome = m_pythonBindings->SetEngineInfo(engineInfo, forceRegistration);
  159. if (!registerOutcome)
  160. {
  161. if (interactive)
  162. {
  163. ProjectUtils::DisplayDetailedError(QObject::tr("Failed to register engine"), registerOutcome);
  164. }
  165. AZ_Error("Project Manager", false, "Failed to register engine %s : %s",
  166. engineInfo.m_path.toUtf8().constData(), registerOutcome.GetError().first.c_str());
  167. return false;
  168. }
  169. return true;
  170. }
  171. void Application::TearDown()
  172. {
  173. if (m_entity)
  174. {
  175. m_entity->Deactivate();
  176. delete m_entity;
  177. m_entity = nullptr;
  178. }
  179. m_pythonBindings.reset();
  180. m_mainWindow.reset();
  181. m_app.reset();
  182. }
  183. bool Application::Run()
  184. {
  185. // Set up the Style Manager
  186. AzQtComponents::StyleManager styleManager(qApp);
  187. styleManager.initialize(qApp, GetEngineRoot());
  188. // setup stylesheets and hot reloading
  189. AZ::IO::FixedMaxPath engineRoot(GetEngineRoot());
  190. QDir rootDir(engineRoot.c_str());
  191. const auto pathOnDisk = rootDir.absoluteFilePath("Code/Tools/ProjectManager/Resources");
  192. const auto qrcPath = QStringLiteral(":/ProjectManager/style");
  193. AzQtComponents::StyleManager::addSearchPaths("style", pathOnDisk, qrcPath, engineRoot);
  194. // set stylesheet after creating the main window or their styles won't get updated
  195. AzQtComponents::StyleManager::setStyleSheet(m_mainWindow.data(), QStringLiteral("style:ProjectManager.qss"));
  196. // the decoration wrapper is intended to remember window positioning and sizing
  197. #if AZ_TRAIT_PROJECT_MANAGER_CUSTOM_TITLEBAR
  198. auto wrapper = new AzQtComponents::WindowDecorationWrapper();
  199. #else
  200. auto wrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled);
  201. #endif
  202. wrapper->setGuest(m_mainWindow.data());
  203. // show the main window here to apply the stylesheet before restoring geometry or we
  204. // can end up with empty white space at the bottom of the window until the frame is resized again
  205. m_mainWindow->show();
  206. wrapper->enableSaveRestoreGeometry("O3DE", "ProjectManager", "mainWindowGeometry");
  207. wrapper->showFromSettings();
  208. qApp->setQuitOnLastWindowClosed(true);
  209. // Run the application
  210. return qApp->exec();
  211. }
  212. }