Application.cpp 10 KB

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