Application.cpp 12 KB

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