Application.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 (!m_pythonBindings->PythonStarted())
  61. {
  62. if (!interactive)
  63. {
  64. return false;
  65. }
  66. int result = QMessageBox::warning(nullptr, QObject::tr("Failed to start Python"),
  67. QObject::tr("This tool requires an O3DE engine with a Python runtime, "
  68. "but either Python is missing or mis-configured.<br><br>Press 'OK' to "
  69. "run the %1 script automatically, or 'Cancel' "
  70. " if you want to manually resolve the issue by renaming your "
  71. " python/runtime folder and running %1 yourself.")
  72. .arg(GetPythonScriptPath),
  73. QMessageBox::Cancel, QMessageBox::Ok);
  74. if (result == QMessageBox::Ok)
  75. {
  76. auto getPythonResult = ProjectUtils::RunGetPythonScript(GetEngineRoot());
  77. if (!getPythonResult.IsSuccess())
  78. {
  79. QMessageBox::critical(
  80. nullptr, QObject::tr("Failed to run %1 script").arg(GetPythonScriptPath),
  81. QObject::tr("The %1 script failed, was canceled, or could not be run. "
  82. "Please rename your python/runtime folder and then run "
  83. "<pre>%1</pre>").arg(GetPythonScriptPath));
  84. }
  85. else if (!m_pythonBindings->StartPython())
  86. {
  87. QMessageBox::critical(
  88. nullptr, QObject::tr("Failed to start Python"),
  89. QObject::tr("Failed to start Python after running %1")
  90. .arg(GetPythonScriptPath));
  91. }
  92. }
  93. if (!m_pythonBindings->PythonStarted())
  94. {
  95. return false;
  96. }
  97. }
  98. m_settings = AZStd::make_unique<Settings>();
  99. if (!RegisterEngine(interactive))
  100. {
  101. return false;
  102. }
  103. const AZ::CommandLine* commandLine = GetCommandLine();
  104. AZ_Assert(commandLine, "Failed to get command line");
  105. ProjectManagerScreen startScreen = ProjectManagerScreen::Projects;
  106. if (size_t screenSwitchCount = commandLine->GetNumSwitchValues("screen"); screenSwitchCount > 0)
  107. {
  108. QString screenOption = commandLine->GetSwitchValue("screen", screenSwitchCount - 1).c_str();
  109. ProjectManagerScreen screen = ProjectUtils::GetProjectManagerScreen(screenOption);
  110. if (screen != ProjectManagerScreen::Invalid)
  111. {
  112. startScreen = screen;
  113. }
  114. }
  115. AZ::IO::FixedMaxPath projectPath;
  116. if (size_t projectSwitchCount = commandLine->GetNumSwitchValues("project-path"); projectSwitchCount > 0)
  117. {
  118. projectPath = commandLine->GetSwitchValue("project-path", projectSwitchCount - 1).c_str();
  119. }
  120. m_mainWindow.reset(new ProjectManagerWindow(nullptr, projectPath, startScreen));
  121. return true;
  122. }
  123. bool Application::InitLog(const char* logName)
  124. {
  125. if (!m_entity)
  126. {
  127. // override the log alias to the O3de Logs directory instead of the default project user/Logs folder
  128. AZ::IO::FixedMaxPath path = AZ::Utils::GetO3deLogsDirectory();
  129. AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
  130. AZ_Assert(fileIO, "Failed to get FileIOBase instance");
  131. fileIO->SetAlias("@log@", path.LexicallyNormal().Native().c_str());
  132. // this entity exists because we need a home for LogComponent
  133. // and cannot use the system entity because we need to be able to call SetLogFileBaseName
  134. // so the log will be named O3DE.log
  135. m_entity = aznew AZ::Entity("Application Entity");
  136. if (m_entity)
  137. {
  138. AzFramework::LogComponent* logger = aznew AzFramework::LogComponent();
  139. AZ_Assert(logger, "Failed to create LogComponent");
  140. logger->SetLogFileBaseName(logName);
  141. m_entity->AddComponent(logger);
  142. m_entity->Init();
  143. m_entity->Activate();
  144. }
  145. }
  146. return m_entity != nullptr;
  147. }
  148. bool Application::RegisterEngine(bool interactive)
  149. {
  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. // We no longer force registration because we no longer require that only one engine can
  170. // be registered with each engine name
  171. constexpr bool forceRegistration = false;
  172. auto registerOutcome = m_pythonBindings->SetEngineInfo(engineInfo, forceRegistration);
  173. if (!registerOutcome)
  174. {
  175. if (interactive)
  176. {
  177. ProjectUtils::DisplayDetailedError(QObject::tr("Failed to register engine"), registerOutcome);
  178. }
  179. AZ_Error("Project Manager", false, "Failed to register engine %s : %s",
  180. engineInfo.m_path.toUtf8().constData(), registerOutcome.GetError().first.c_str());
  181. return false;
  182. }
  183. return true;
  184. }
  185. void Application::TearDown()
  186. {
  187. if (m_entity)
  188. {
  189. m_entity->Deactivate();
  190. delete m_entity;
  191. m_entity = nullptr;
  192. }
  193. m_pythonBindings.reset();
  194. m_mainWindow.reset();
  195. m_app.reset();
  196. }
  197. bool Application::Run()
  198. {
  199. // Set up the Style Manager
  200. AzQtComponents::StyleManager styleManager(qApp);
  201. styleManager.initialize(qApp, GetEngineRoot());
  202. // setup stylesheets and hot reloading
  203. AZ::IO::FixedMaxPath engineRoot(GetEngineRoot());
  204. QDir rootDir(engineRoot.c_str());
  205. const auto pathOnDisk = rootDir.absoluteFilePath("Code/Tools/ProjectManager/Resources");
  206. const auto qrcPath = QStringLiteral(":/ProjectManager/style");
  207. AzQtComponents::StyleManager::addSearchPaths("style", pathOnDisk, qrcPath, engineRoot);
  208. // set stylesheet after creating the main window or their styles won't get updated
  209. AzQtComponents::StyleManager::setStyleSheet(m_mainWindow.data(), QStringLiteral("style:ProjectManager.qss"));
  210. // the decoration wrapper is intended to remember window positioning and sizing
  211. #if AZ_TRAIT_PROJECT_MANAGER_CUSTOM_TITLEBAR
  212. auto wrapper = new AzQtComponents::WindowDecorationWrapper();
  213. #else
  214. auto wrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled);
  215. #endif
  216. wrapper->setGuest(m_mainWindow.data());
  217. // show the main window here to apply the stylesheet before restoring geometry or we
  218. // can end up with empty white space at the bottom of the window until the frame is resized again
  219. m_mainWindow->show();
  220. wrapper->enableSaveRestoreGeometry("O3DE", "ProjectManager", "mainWindowGeometry");
  221. wrapper->showFromSettings();
  222. qApp->setQuitOnLastWindowClosed(true);
  223. // Run the application
  224. return qApp->exec();
  225. }
  226. }