Application.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. namespace O3DE::ProjectManager
  23. {
  24. Application::~Application()
  25. {
  26. TearDown();
  27. }
  28. bool Application::Init(bool interactive)
  29. {
  30. constexpr const char* applicationName { "O3DE" };
  31. QApplication::setOrganizationName(applicationName);
  32. QApplication::setOrganizationDomain("o3de.org");
  33. QCoreApplication::setApplicationName(applicationName);
  34. QCoreApplication::setApplicationVersion("1.0");
  35. // Use the LogComponent for non-dev logging log
  36. RegisterComponentDescriptor(AzFramework::LogComponent::CreateDescriptor());
  37. // set the log alias to .o3de/Logs instead of the default user/logs
  38. AZ::IO::FixedMaxPath path = AZ::Utils::GetO3deLogsDirectory();
  39. // DevWriteStorage is where the event log is written during development
  40. m_settingsRegistry->Set(AZ::SettingsRegistryMergeUtils::FilePathKey_DevWriteStorage, path.LexicallyNormal().Native());
  41. // Save event logs to .o3de/Logs/eventlogger/EventLogO3DE.azsl
  42. m_settingsRegistry->Set(AZ::SettingsRegistryMergeUtils::BuildTargetNameKey, applicationName);
  43. Start(AzFramework::Application::Descriptor());
  44. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  45. QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  46. QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  47. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  48. AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware);
  49. // Create the actual Qt Application - this needs to happen before using QMessageBox
  50. m_app.reset(new QApplication(*GetArgC(), *GetArgV()));
  51. if(!InitLog(applicationName))
  52. {
  53. AZ_Warning("ProjectManager", false, "Failed to init logging");
  54. }
  55. m_pythonBindings = AZStd::make_unique<PythonBindings>(GetEngineRoot());
  56. AZ_Assert(m_pythonBindings, "Failed to create PythonBindings");
  57. if (!m_pythonBindings->PythonStarted())
  58. {
  59. if (!interactive)
  60. {
  61. return false;
  62. }
  63. int result = QMessageBox::warning(nullptr, QObject::tr("Failed to start Python"),
  64. QObject::tr("This tool requires an O3DE engine with a Python runtime, "
  65. "but either Python is missing or mis-configured.<br><br>Press 'OK' to "
  66. "run the %1 script automatically, or 'Cancel' "
  67. " if you want to manually resolve the issue by renaming your "
  68. " python/runtime folder and running %1 yourself.")
  69. .arg(GetPythonScriptPath),
  70. QMessageBox::Cancel, QMessageBox::Ok);
  71. if (result == QMessageBox::Ok)
  72. {
  73. auto getPythonResult = ProjectUtils::RunGetPythonScript(GetEngineRoot());
  74. if (!getPythonResult.IsSuccess())
  75. {
  76. QMessageBox::critical(
  77. nullptr, QObject::tr("Failed to run %1 script").arg(GetPythonScriptPath),
  78. QObject::tr("The %1 script failed, was canceled, or could not be run. "
  79. "Please rename your python/runtime folder and then run "
  80. "<pre>%1</pre>").arg(GetPythonScriptPath));
  81. }
  82. else if (!m_pythonBindings->StartPython())
  83. {
  84. QMessageBox::critical(
  85. nullptr, QObject::tr("Failed to start Python"),
  86. QObject::tr("Failed to start Python after running %1")
  87. .arg(GetPythonScriptPath));
  88. }
  89. }
  90. if (!m_pythonBindings->PythonStarted())
  91. {
  92. return false;
  93. }
  94. }
  95. if (!RegisterEngine(interactive))
  96. {
  97. return false;
  98. }
  99. const AZ::CommandLine* commandLine = GetCommandLine();
  100. AZ_Assert(commandLine, "Failed to get command line");
  101. ProjectManagerScreen startScreen = ProjectManagerScreen::Projects;
  102. if (size_t screenSwitchCount = commandLine->GetNumSwitchValues("screen"); screenSwitchCount > 0)
  103. {
  104. QString screenOption = commandLine->GetSwitchValue("screen", screenSwitchCount - 1).c_str();
  105. ProjectManagerScreen screen = ProjectUtils::GetProjectManagerScreen(screenOption);
  106. if (screen != ProjectManagerScreen::Invalid)
  107. {
  108. startScreen = screen;
  109. }
  110. }
  111. AZ::IO::FixedMaxPath projectPath;
  112. if (size_t projectSwitchCount = commandLine->GetNumSwitchValues("project-path"); projectSwitchCount > 0)
  113. {
  114. projectPath = commandLine->GetSwitchValue("project-path", projectSwitchCount - 1).c_str();
  115. }
  116. m_mainWindow.reset(new ProjectManagerWindow(nullptr, projectPath, startScreen));
  117. return true;
  118. }
  119. bool Application::InitLog(const char* logName)
  120. {
  121. if (!m_entity)
  122. {
  123. // override the log alias to the O3de Logs directory instead of the default project user/Logs folder
  124. AZ::IO::FixedMaxPath path = AZ::Utils::GetO3deLogsDirectory();
  125. AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
  126. AZ_Assert(fileIO, "Failed to get FileIOBase instance");
  127. fileIO->SetAlias("@log@", path.LexicallyNormal().Native().c_str());
  128. // this entity exists because we need a home for LogComponent
  129. // and cannot use the system entity because we need to be able to call SetLogFileBaseName
  130. // so the log will be named O3DE.log
  131. m_entity = aznew AZ::Entity("Application Entity");
  132. if (m_entity)
  133. {
  134. AzFramework::LogComponent* logger = aznew AzFramework::LogComponent();
  135. AZ_Assert(logger, "Failed to create LogComponent");
  136. logger->SetLogFileBaseName(logName);
  137. m_entity->AddComponent(logger);
  138. m_entity->Init();
  139. m_entity->Activate();
  140. }
  141. }
  142. return m_entity != nullptr;
  143. }
  144. bool Application::RegisterEngine(bool interactive)
  145. {
  146. // get this engine's info
  147. auto engineInfoOutcome = m_pythonBindings->GetEngineInfo();
  148. if (!engineInfoOutcome)
  149. {
  150. if (interactive)
  151. {
  152. QMessageBox::critical(nullptr,
  153. QObject::tr("Failed to get engine info"),
  154. QObject::tr("A valid engine.json could not be found or loaded. "
  155. "Please verify a valid engine.json file exists in %1")
  156. .arg(GetEngineRoot()));
  157. }
  158. AZ_Error("Project Manager", false, "Failed to get engine info");
  159. return false;
  160. }
  161. EngineInfo engineInfo = engineInfoOutcome.GetValue();
  162. if (engineInfo.m_registered)
  163. {
  164. return true;
  165. }
  166. // check if an engine with this name is already registered and has a valid engine.json
  167. auto existingEngineResult = m_pythonBindings->GetEngineInfo(engineInfo.m_name);
  168. if (existingEngineResult)
  169. {
  170. if (!interactive)
  171. {
  172. AZ_Error("Project Manager", false, "An engine with the name %s is already registered with the path %s",
  173. engineInfo.m_name.toUtf8().constData(), engineInfo.m_path.toUtf8().constData());
  174. return false;
  175. }
  176. // get the updated engine name unless the user wants to cancel
  177. bool okPressed = false;
  178. const EngineInfo& otherEngineInfo = existingEngineResult.GetValue();
  179. engineInfo.m_name = QInputDialog::getText(nullptr,
  180. QObject::tr("Engine '%1' already registered").arg(engineInfo.m_name),
  181. QObject::tr("An engine named '%1' is already registered.<br /><br />"
  182. "<b>Current path</b><br />%2<br/><br />"
  183. "<b>New path</b><br />%3<br /><br />"
  184. "Press 'OK' to force registration, or provide a new engine name below.<br />"
  185. "Alternatively, press `Cancel` to close the Project Manager and resolve the issue manually.")
  186. .arg(engineInfo.m_name, otherEngineInfo.m_path, engineInfo.m_path),
  187. QLineEdit::Normal,
  188. engineInfo.m_name,
  189. &okPressed);
  190. if (!okPressed)
  191. {
  192. // user elected not to change the name or force registration
  193. return false;
  194. }
  195. }
  196. // always force register in case there is an engine registered in o3de_manifest.json, but
  197. // the engine.json is missing or corrupt in which case GetEngineInfo() fails
  198. constexpr bool forceRegistration = true;
  199. auto registerOutcome = m_pythonBindings->SetEngineInfo(engineInfo, forceRegistration);
  200. if (!registerOutcome)
  201. {
  202. if (interactive)
  203. {
  204. ProjectUtils::DisplayDetailedError(QObject::tr("Failed to register engine"), registerOutcome);
  205. }
  206. AZ_Error("Project Manager", false, "Failed to register engine %s : %s",
  207. engineInfo.m_path.toUtf8().constData(), registerOutcome.GetError().first.c_str());
  208. return false;
  209. }
  210. return true;
  211. }
  212. void Application::TearDown()
  213. {
  214. if (m_entity)
  215. {
  216. m_entity->Deactivate();
  217. delete m_entity;
  218. m_entity = nullptr;
  219. }
  220. m_pythonBindings.reset();
  221. m_mainWindow.reset();
  222. m_app.reset();
  223. }
  224. bool Application::Run()
  225. {
  226. // Set up the Style Manager
  227. AzQtComponents::StyleManager styleManager(qApp);
  228. styleManager.initialize(qApp, GetEngineRoot());
  229. // setup stylesheets and hot reloading
  230. AZ::IO::FixedMaxPath engineRoot(GetEngineRoot());
  231. QDir rootDir(engineRoot.c_str());
  232. const auto pathOnDisk = rootDir.absoluteFilePath("Code/Tools/ProjectManager/Resources");
  233. const auto qrcPath = QStringLiteral(":/ProjectManager/style");
  234. AzQtComponents::StyleManager::addSearchPaths("style", pathOnDisk, qrcPath, engineRoot);
  235. // set stylesheet after creating the main window or their styles won't get updated
  236. AzQtComponents::StyleManager::setStyleSheet(m_mainWindow.data(), QStringLiteral("style:ProjectManager.qss"));
  237. // the decoration wrapper is intended to remember window positioning and sizing
  238. #if AZ_TRAIT_PROJECT_MANAGER_CUSTOM_TITLEBAR
  239. auto wrapper = new AzQtComponents::WindowDecorationWrapper();
  240. #else
  241. auto wrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled);
  242. #endif
  243. wrapper->setGuest(m_mainWindow.data());
  244. // show the main window here to apply the stylesheet before restoring geometry or we
  245. // can end up with empty white space at the bottom of the window until the frame is resized again
  246. m_mainWindow->show();
  247. wrapper->enableSaveRestoreGeometry("O3DE", "ProjectManager", "mainWindowGeometry");
  248. wrapper->showFromSettings();
  249. qApp->setQuitOnLastWindowClosed(true);
  250. // Run the application
  251. return qApp->exec();
  252. }
  253. }