PythonBindings.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <PythonBindings.h>
  8. #include <ProjectManagerDefs.h>
  9. // Qt defines slots, which interferes with the use here.
  10. #pragma push_macro("slots")
  11. #undef slots
  12. #include <pybind11/functional.h>
  13. #include <pybind11/embed.h>
  14. #include <pybind11/eval.h>
  15. #include <pybind11/stl.h>
  16. #pragma pop_macro("slots")
  17. #include <AzCore/IO/FileIO.h>
  18. #include <AzCore/IO/SystemFile.h>
  19. #include <AzCore/std/string/conversions.h>
  20. #include <AzCore/StringFunc/StringFunc.h>
  21. namespace Platform
  22. {
  23. bool InsertPythonLibraryPath(
  24. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  25. {
  26. // append lib path to Python paths
  27. AZ::IO::FixedMaxPath libPath = engineRoot;
  28. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  29. libPath = libPath.LexicallyNormal();
  30. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  31. {
  32. paths.insert(libPath.c_str());
  33. return true;
  34. }
  35. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  36. return false;
  37. }
  38. // Implemented in each different platform's PAL implentation files, as it differs per platform.
  39. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  40. } // namespace Platform
  41. #define Py_To_String(obj) pybind11::str(obj).cast<std::string>().c_str()
  42. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  43. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  44. #define QString_To_Py_Path(value) m_pathlib.attr("Path")(value.toStdString())
  45. namespace RedirectOutput
  46. {
  47. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  48. struct RedirectOutput
  49. {
  50. PyObject_HEAD RedirectOutputFunc write;
  51. };
  52. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  53. {
  54. std::size_t written(0);
  55. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  56. if (selfimpl->write)
  57. {
  58. char* data;
  59. if (!PyArg_ParseTuple(args, "s", &data))
  60. {
  61. return PyLong_FromSize_t(0);
  62. }
  63. selfimpl->write(data);
  64. written = strlen(data);
  65. }
  66. return PyLong_FromSize_t(written);
  67. }
  68. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  69. {
  70. // no-op
  71. return Py_BuildValue("");
  72. }
  73. PyMethodDef RedirectMethods[] = {
  74. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  75. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  76. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  77. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  78. {0, 0, 0, 0} // sentinel
  79. };
  80. PyTypeObject RedirectOutputType = {
  81. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  82. sizeof(RedirectOutput), /* tp_basicsize */
  83. 0, /* tp_itemsize */
  84. 0, /* tp_dealloc */
  85. 0, /* tp_print */
  86. 0, /* tp_getattr */
  87. 0, /* tp_setattr */
  88. 0, /* tp_reserved */
  89. 0, /* tp_repr */
  90. 0, /* tp_as_number */
  91. 0, /* tp_as_sequence */
  92. 0, /* tp_as_mapping */
  93. 0, /* tp_hash */
  94. 0, /* tp_call */
  95. 0, /* tp_str */
  96. 0, /* tp_getattro */
  97. 0, /* tp_setattro */
  98. 0, /* tp_as_buffer */
  99. Py_TPFLAGS_DEFAULT, /* tp_flags */
  100. "azlmbr_redirect objects", /* tp_doc */
  101. 0, /* tp_traverse */
  102. 0, /* tp_clear */
  103. 0, /* tp_richcompare */
  104. 0, /* tp_weaklistoffset */
  105. 0, /* tp_iter */
  106. 0, /* tp_iternext */
  107. RedirectMethods, /* tp_methods */
  108. 0, /* tp_members */
  109. 0, /* tp_getset */
  110. 0, /* tp_base */
  111. 0, /* tp_dict */
  112. 0, /* tp_descr_get */
  113. 0, /* tp_descr_set */
  114. 0, /* tp_dictoffset */
  115. 0, /* tp_init */
  116. 0, /* tp_alloc */
  117. 0 /* tp_new */
  118. };
  119. PyModuleDef RedirectOutputModule = {
  120. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  121. };
  122. // Internal state
  123. PyObject* g_redirect_stdout = nullptr;
  124. PyObject* g_redirect_stdout_saved = nullptr;
  125. PyObject* g_redirect_stderr = nullptr;
  126. PyObject* g_redirect_stderr_saved = nullptr;
  127. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  128. {
  129. g_redirect_stdout = nullptr;
  130. g_redirect_stdout_saved = nullptr;
  131. g_redirect_stderr = nullptr;
  132. g_redirect_stderr_saved = nullptr;
  133. RedirectOutputType.tp_new = PyType_GenericNew;
  134. if (PyType_Ready(&RedirectOutputType) < 0)
  135. {
  136. return 0;
  137. }
  138. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  139. if (redirectModule)
  140. {
  141. Py_INCREF(&RedirectOutputType);
  142. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  143. }
  144. return redirectModule;
  145. }
  146. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  147. {
  148. if (PyType_Ready(&RedirectOutputType) < 0)
  149. {
  150. AZ_Warning("python", false, "RedirectOutputType not ready!");
  151. return;
  152. }
  153. if (!current)
  154. {
  155. saved = PySys_GetObject(funcname); // borrowed
  156. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  157. }
  158. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  159. redirectOutput->write = func;
  160. PySys_SetObject(funcname, current);
  161. }
  162. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  163. {
  164. if (current)
  165. {
  166. PySys_SetObject(funcname, saved);
  167. }
  168. Py_XDECREF(current);
  169. current = nullptr;
  170. }
  171. PyObject* s_RedirectModule = nullptr;
  172. void Intialize(PyObject* module)
  173. {
  174. s_RedirectModule = module;
  175. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, []([[maybe_unused]] const char* msg) {
  176. AZ_TracePrintf("Python", msg);
  177. });
  178. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) {
  179. AZ_TracePrintf("Python", msg);
  180. });
  181. PySys_WriteStdout("RedirectOutput installed");
  182. }
  183. void Shutdown()
  184. {
  185. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  186. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  187. Py_XDECREF(s_RedirectModule);
  188. s_RedirectModule = nullptr;
  189. }
  190. } // namespace RedirectOutput
  191. namespace O3DE::ProjectManager
  192. {
  193. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  194. : m_enginePath(enginePath)
  195. {
  196. m_pythonStarted = StartPython();
  197. }
  198. PythonBindings::~PythonBindings()
  199. {
  200. StopPython();
  201. }
  202. bool PythonBindings::PythonStarted()
  203. {
  204. return m_pythonStarted && Py_IsInitialized();
  205. }
  206. bool PythonBindings::StartPython()
  207. {
  208. if (Py_IsInitialized())
  209. {
  210. AZ_Warning("python", false, "Python is already active");
  211. return false;
  212. }
  213. // set PYTHON_HOME
  214. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  215. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  216. {
  217. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  218. return false;
  219. }
  220. AZStd::wstring pyHomePath;
  221. AZStd::to_wstring(pyHomePath, pyBasePath);
  222. Py_SetPythonHome(pyHomePath.c_str());
  223. // display basic Python information
  224. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  225. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  226. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  227. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  228. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  229. try
  230. {
  231. // ignore system location for sites site-packages
  232. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  233. Py_IgnoreEnvironmentFlag = 1; // -E
  234. const bool initializeSignalHandlers = true;
  235. pybind11::initialize_interpreter(initializeSignalHandlers);
  236. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  237. // Acquire GIL before calling Python code
  238. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  239. pybind11::gil_scoped_acquire acquire;
  240. // sanity import check
  241. if (PyRun_SimpleString("import sys") != 0)
  242. {
  243. AZ_Assert(false, "Import sys failed");
  244. return false;
  245. }
  246. // import required modules
  247. m_cmake = pybind11::module::import("o3de.cmake");
  248. m_register = pybind11::module::import("o3de.register");
  249. m_manifest = pybind11::module::import("o3de.manifest");
  250. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  251. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  252. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  253. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  254. m_pathlib = pybind11::module::import("pathlib");
  255. // make sure the engine is registered
  256. RegisterThisEngine();
  257. return !PyErr_Occurred();
  258. }
  259. catch ([[maybe_unused]] const std::exception& e)
  260. {
  261. AZ_Assert(false, "Py_Initialize() failed with %s", e.what());
  262. return false;
  263. }
  264. }
  265. bool PythonBindings::StopPython()
  266. {
  267. if (Py_IsInitialized())
  268. {
  269. RedirectOutput::Shutdown();
  270. pybind11::finalize_interpreter();
  271. }
  272. else
  273. {
  274. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  275. }
  276. return !PyErr_Occurred();
  277. }
  278. bool PythonBindings::RegisterThisEngine()
  279. {
  280. bool registrationResult = true; // already registered is considered successful
  281. bool pythonResult = ExecuteWithLock(
  282. [&]
  283. {
  284. // check current engine path against all other registered engines
  285. // to see if we are already registered
  286. auto allEngines = m_manifest.attr("get_engines")();
  287. if (pybind11::isinstance<pybind11::list>(allEngines))
  288. {
  289. for (auto engine : allEngines)
  290. {
  291. AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"]));
  292. if (enginePath.Compare(m_enginePath) == 0)
  293. {
  294. return;
  295. }
  296. }
  297. }
  298. auto result = m_register.attr("register")(QString_To_Py_Path(QString(m_enginePath.c_str())));
  299. registrationResult = (result.cast<int>() == 0);
  300. });
  301. bool finalResult = (registrationResult && pythonResult);
  302. AZ_Assert(finalResult, "Registration of this engine failed!");
  303. return finalResult;
  304. }
  305. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback)
  306. {
  307. if (!Py_IsInitialized())
  308. {
  309. return AZ::Failure<AZStd::string>("Python is not initialized");
  310. }
  311. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  312. pybind11::gil_scoped_release release;
  313. pybind11::gil_scoped_acquire acquire;
  314. try
  315. {
  316. executionCallback();
  317. }
  318. catch ([[maybe_unused]] const std::exception& e)
  319. {
  320. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  321. return AZ::Failure<AZStd::string>(e.what());
  322. }
  323. return AZ::Success();
  324. }
  325. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  326. {
  327. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  328. }
  329. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  330. {
  331. EngineInfo engineInfo;
  332. bool result = ExecuteWithLock([&] {
  333. auto enginePath = m_manifest.attr("get_this_engine_path")();
  334. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  335. if (pybind11::isinstance<pybind11::dict>(o3deData))
  336. {
  337. engineInfo.m_path = Py_To_String(enginePath);
  338. engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]);
  339. engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]);
  340. engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]);
  341. engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]);
  342. auto defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")();
  343. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"default_third_party_folder", Py_To_String(defaultThirdPartyFolder));
  344. }
  345. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  346. if (pybind11::isinstance<pybind11::dict>(engineData))
  347. {
  348. try
  349. {
  350. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  351. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  352. }
  353. catch ([[maybe_unused]] const std::exception& e)
  354. {
  355. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  356. }
  357. }
  358. });
  359. if (!result || !engineInfo.IsValid())
  360. {
  361. return AZ::Failure();
  362. }
  363. else
  364. {
  365. return AZ::Success(AZStd::move(engineInfo));
  366. }
  367. return AZ::Failure();
  368. }
  369. bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo)
  370. {
  371. bool result = ExecuteWithLock([&] {
  372. auto registrationResult = m_register.attr("register")(
  373. QString_To_Py_Path(engineInfo.m_path),
  374. pybind11::none(), // project_path
  375. pybind11::none(), // gem_path
  376. pybind11::none(), // external_subdir_path
  377. pybind11::none(), // template_path
  378. pybind11::none(), // restricted_path
  379. pybind11::none(), // repo_uri
  380. pybind11::none(), // default_engines_folder
  381. QString_To_Py_Path(engineInfo.m_defaultProjectsFolder),
  382. QString_To_Py_Path(engineInfo.m_defaultGemsFolder),
  383. QString_To_Py_Path(engineInfo.m_defaultTemplatesFolder),
  384. pybind11::none(), // default_restricted_folder
  385. QString_To_Py_Path(engineInfo.m_thirdPartyPath)
  386. );
  387. if (registrationResult.cast<int>() != 0)
  388. {
  389. result = false;
  390. }
  391. });
  392. return result;
  393. }
  394. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  395. {
  396. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  397. if (gemInfo.IsValid())
  398. {
  399. return AZ::Success(AZStd::move(gemInfo));
  400. }
  401. else
  402. {
  403. return AZ::Failure();
  404. }
  405. }
  406. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  407. {
  408. QVector<GemInfo> gems;
  409. auto result = ExecuteWithLockErrorHandling([&]
  410. {
  411. for (auto path : m_manifest.attr("get_engine_gems")())
  412. {
  413. gems.push_back(GemInfoFromPath(path, pybind11::none()));
  414. }
  415. });
  416. if (!result.IsSuccess())
  417. {
  418. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  419. }
  420. std::sort(gems.begin(), gems.end());
  421. return AZ::Success(AZStd::move(gems));
  422. }
  423. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  424. {
  425. QVector<GemInfo> gems;
  426. auto result = ExecuteWithLockErrorHandling([&]
  427. {
  428. auto pyProjectPath = QString_To_Py_Path(projectPath);
  429. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  430. {
  431. gems.push_back(GemInfoFromPath(path, pyProjectPath));
  432. }
  433. });
  434. if (!result.IsSuccess())
  435. {
  436. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  437. }
  438. std::sort(gems.begin(), gems.end());
  439. return AZ::Success(AZStd::move(gems));
  440. }
  441. AZ::Outcome<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath)
  442. {
  443. // Retrieve the path to the cmake file that lists the enabled gems.
  444. pybind11::str enabledGemsFilename;
  445. auto result = ExecuteWithLockErrorHandling([&]
  446. {
  447. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  448. pybind11::none(), // project_name
  449. QString_To_Py_Path(projectPath)); // project_path
  450. });
  451. if (!result.IsSuccess())
  452. {
  453. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  454. }
  455. // Retrieve the actual list of names from the cmake file.
  456. QVector<AZStd::string> gemNames;
  457. result = ExecuteWithLockErrorHandling([&]
  458. {
  459. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  460. for (auto gemName : pyGemNames)
  461. {
  462. gemNames.push_back(Py_To_String(gemName));
  463. }
  464. });
  465. if (!result.IsSuccess())
  466. {
  467. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  468. }
  469. return AZ::Success(AZStd::move(gemNames));
  470. }
  471. bool PythonBindings::AddProject(const QString& path)
  472. {
  473. bool registrationResult = false;
  474. bool result = ExecuteWithLock(
  475. [&]
  476. {
  477. auto projectPath = QString_To_Py_Path(path);
  478. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  479. // Returns an exit code so boolify it then invert result
  480. registrationResult = !pythonRegistrationResult.cast<bool>();
  481. });
  482. return result && registrationResult;
  483. }
  484. bool PythonBindings::RemoveProject(const QString& path)
  485. {
  486. bool registrationResult = false;
  487. bool result = ExecuteWithLock(
  488. [&]
  489. {
  490. auto pythonRegistrationResult = m_register.attr("register")(
  491. pybind11::none(), // engine_path
  492. QString_To_Py_Path(path), // project_path
  493. pybind11::none(), // gem_path
  494. pybind11::none(), // external_subdir_path
  495. pybind11::none(), // template_path
  496. pybind11::none(), // restricted_path
  497. pybind11::none(), // repo_uri
  498. pybind11::none(), // default_engines_folder
  499. pybind11::none(), // default_projects_folder
  500. pybind11::none(), // default_gems_folder
  501. pybind11::none(), // default_templates_folder
  502. pybind11::none(), // default_restricted_folder
  503. pybind11::none(), // default_third_party_folder
  504. pybind11::none(), // external_subdir_engine_path
  505. pybind11::none(), // external_subdir_project_path
  506. true, // remove
  507. false // force
  508. );
  509. // Returns an exit code so boolify it then invert result
  510. registrationResult = !pythonRegistrationResult.cast<bool>();
  511. });
  512. return result && registrationResult;
  513. }
  514. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  515. {
  516. ProjectInfo createdProjectInfo;
  517. bool result = ExecuteWithLock([&] {
  518. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  519. auto createProjectResult = m_engineTemplate.attr("create_project")(
  520. projectPath,
  521. QString_To_Py_String(projectInfo.m_projectName),
  522. QString_To_Py_Path(projectTemplatePath)
  523. );
  524. if (createProjectResult.cast<int>() == 0)
  525. {
  526. createdProjectInfo = ProjectInfoFromPath(projectPath);
  527. }
  528. });
  529. if (!result || !createdProjectInfo.IsValid())
  530. {
  531. return AZ::Failure();
  532. }
  533. else
  534. {
  535. return AZ::Success(AZStd::move(createdProjectInfo));
  536. }
  537. }
  538. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  539. {
  540. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  541. if (projectInfo.IsValid())
  542. {
  543. return AZ::Success(AZStd::move(projectInfo));
  544. }
  545. else
  546. {
  547. return AZ::Failure();
  548. }
  549. }
  550. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  551. {
  552. GemInfo gemInfo;
  553. gemInfo.m_path = Py_To_String(path);
  554. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  555. if (pybind11::isinstance<pybind11::dict>(data))
  556. {
  557. try
  558. {
  559. // required
  560. gemInfo.m_name = Py_To_String(data["gem_name"]);
  561. // optional
  562. gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name);
  563. gemInfo.m_summary = Py_To_String_Optional(data, "Summary", "");
  564. gemInfo.m_version = Py_To_String_Optional(data, "Version", "");
  565. gemInfo.m_requirement = Py_To_String_Optional(data, "Requirements", "");
  566. if (data.contains("Tags"))
  567. {
  568. for (auto tag : data["Tags"])
  569. {
  570. gemInfo.m_features.push_back(Py_To_String(tag));
  571. }
  572. }
  573. }
  574. catch ([[maybe_unused]] const std::exception& e)
  575. {
  576. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  577. }
  578. }
  579. return gemInfo;
  580. }
  581. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  582. {
  583. ProjectInfo projectInfo;
  584. projectInfo.m_path = Py_To_String(path);
  585. projectInfo.m_needsBuild = false;
  586. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  587. if (pybind11::isinstance<pybind11::dict>(projectData))
  588. {
  589. try
  590. {
  591. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  592. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  593. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  594. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  595. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  596. if (projectData.contains("user_tags"))
  597. {
  598. for (auto tag : projectData["user_tags"])
  599. {
  600. projectInfo.m_userTags.append(Py_To_String(tag));
  601. }
  602. }
  603. }
  604. catch ([[maybe_unused]] const std::exception& e)
  605. {
  606. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  607. }
  608. }
  609. return projectInfo;
  610. }
  611. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  612. {
  613. QVector<ProjectInfo> projects;
  614. bool result = ExecuteWithLock([&] {
  615. // external projects
  616. for (auto path : m_manifest.attr("get_projects")())
  617. {
  618. projects.push_back(ProjectInfoFromPath(path));
  619. }
  620. // projects from the engine
  621. for (auto path : m_manifest.attr("get_engine_projects")())
  622. {
  623. projects.push_back(ProjectInfoFromPath(path));
  624. }
  625. });
  626. if (!result)
  627. {
  628. return AZ::Failure();
  629. }
  630. else
  631. {
  632. return AZ::Success(AZStd::move(projects));
  633. }
  634. }
  635. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  636. {
  637. return ExecuteWithLockErrorHandling([&]
  638. {
  639. m_enableGemProject.attr("enable_gem_in_project")(
  640. pybind11::none(), // gem name not needed as path is provided
  641. QString_To_Py_Path(gemPath),
  642. pybind11::none(), // project name not needed as path is provided
  643. QString_To_Py_Path(projectPath)
  644. );
  645. });
  646. }
  647. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  648. {
  649. return ExecuteWithLockErrorHandling([&]
  650. {
  651. m_disableGemProject.attr("disable_gem_in_project")(
  652. pybind11::none(), // gem name not needed as path is provided
  653. QString_To_Py_Path(gemPath),
  654. pybind11::none(), // project name not needed as path is provided
  655. QString_To_Py_Path(projectPath)
  656. );
  657. });
  658. }
  659. bool PythonBindings::RemoveInvalidProjects()
  660. {
  661. bool removalResult = false;
  662. bool result = ExecuteWithLock(
  663. [&]
  664. {
  665. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  666. // Returns an exit code so boolify it then invert result
  667. removalResult = !pythonRemovalResult.cast<bool>();
  668. });
  669. return result && removalResult;
  670. }
  671. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  672. {
  673. bool updateProjectSucceeded = false;
  674. auto result = ExecuteWithLockErrorHandling([&]
  675. {
  676. std::list<std::string> newTags;
  677. for (const auto& i : projectInfo.m_userTags)
  678. {
  679. newTags.push_back(i.toStdString());
  680. }
  681. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  682. QString_To_Py_Path(projectInfo.m_path),
  683. pybind11::none(), // proj_name not used
  684. QString_To_Py_String(projectInfo.m_projectName),
  685. QString_To_Py_String(projectInfo.m_origin),
  686. QString_To_Py_String(projectInfo.m_displayName),
  687. QString_To_Py_String(projectInfo.m_summary),
  688. QString_To_Py_String(projectInfo.m_iconPath), // new_icon
  689. pybind11::none(), // add_tags not used
  690. pybind11::none(), // remove_tags not used
  691. pybind11::list(pybind11::cast(newTags)));
  692. updateProjectSucceeded = (editResult.cast<int>() == 0);
  693. });
  694. if (!result.IsSuccess())
  695. {
  696. return result;
  697. }
  698. else if (!updateProjectSucceeded)
  699. {
  700. return AZ::Failure<AZStd::string>("Failed to update project.");
  701. }
  702. return AZ::Success();
  703. }
  704. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  705. {
  706. ProjectTemplateInfo templateInfo;
  707. templateInfo.m_path = Py_To_String(path);
  708. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path, pyProjectPath);
  709. if (pybind11::isinstance<pybind11::dict>(data))
  710. {
  711. try
  712. {
  713. // required
  714. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  715. templateInfo.m_name = Py_To_String(data["template_name"]);
  716. templateInfo.m_summary = Py_To_String(data["summary"]);
  717. // optional
  718. if (data.contains("canonical_tags"))
  719. {
  720. for (auto tag : data["canonical_tags"])
  721. {
  722. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  723. }
  724. }
  725. if (data.contains("user_tags"))
  726. {
  727. for (auto tag : data["user_tags"])
  728. {
  729. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  730. }
  731. }
  732. if (data.contains("included_gems"))
  733. {
  734. for (auto gem : data["included_gems"])
  735. {
  736. templateInfo.m_includedGems.push_back(Py_To_String(gem));
  737. }
  738. }
  739. }
  740. catch ([[maybe_unused]] const std::exception& e)
  741. {
  742. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  743. }
  744. }
  745. return templateInfo;
  746. }
  747. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates(const QString& projectPath)
  748. {
  749. QVector<ProjectTemplateInfo> templates;
  750. bool result = ExecuteWithLock([&] {
  751. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  752. {
  753. templates.push_back(ProjectTemplateInfoFromPath(path, QString_To_Py_Path(projectPath)));
  754. }
  755. });
  756. if (!result)
  757. {
  758. return AZ::Failure();
  759. }
  760. else
  761. {
  762. return AZ::Success(AZStd::move(templates));
  763. }
  764. }
  765. }