PythonBindings.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. * its licensors.
  4. *
  5. * For complete copyright and license terms please see the LICENSE at the root of this
  6. * distribution (the "License"). All use of this software is governed by the License,
  7. * or, if provided, by the license below or the license accompanying this file. Do not
  8. * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. *
  11. */
  12. #include <PythonBindings.h>
  13. // Qt defines slots, which interferes with the use here.
  14. #pragma push_macro("slots")
  15. #undef slots
  16. #include <pybind11/functional.h>
  17. #include <pybind11/embed.h>
  18. #include <pybind11/eval.h>
  19. #pragma pop_macro("slots")
  20. #include <AzCore/IO/FileIO.h>
  21. #include <AzCore/IO/SystemFile.h>
  22. #include <AzCore/std/string/conversions.h>
  23. #include <AzCore/StringFunc/StringFunc.h>
  24. namespace Platform
  25. {
  26. bool InsertPythonLibraryPath(
  27. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  28. {
  29. // append lib path to Python paths
  30. AZ::IO::FixedMaxPath libPath = engineRoot;
  31. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  32. libPath = libPath.LexicallyNormal();
  33. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  34. {
  35. paths.insert(libPath.c_str());
  36. return true;
  37. }
  38. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  39. return false;
  40. }
  41. // Implemented in each different platform's PAL implentation files, as it differs per platform.
  42. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  43. } // namespace Platform
  44. #define Py_To_String(obj) obj.cast<std::string>().c_str()
  45. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  46. namespace RedirectOutput
  47. {
  48. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  49. struct RedirectOutput
  50. {
  51. PyObject_HEAD RedirectOutputFunc write;
  52. };
  53. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  54. {
  55. std::size_t written(0);
  56. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  57. if (selfimpl->write)
  58. {
  59. char* data;
  60. if (!PyArg_ParseTuple(args, "s", &data))
  61. {
  62. return PyLong_FromSize_t(0);
  63. }
  64. selfimpl->write(data);
  65. written = strlen(data);
  66. }
  67. return PyLong_FromSize_t(written);
  68. }
  69. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  70. {
  71. // no-op
  72. return Py_BuildValue("");
  73. }
  74. PyMethodDef RedirectMethods[] = {
  75. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  76. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  77. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  78. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  79. {0, 0, 0, 0} // sentinel
  80. };
  81. PyTypeObject RedirectOutputType = {
  82. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  83. sizeof(RedirectOutput), /* tp_basicsize */
  84. 0, /* tp_itemsize */
  85. 0, /* tp_dealloc */
  86. 0, /* tp_print */
  87. 0, /* tp_getattr */
  88. 0, /* tp_setattr */
  89. 0, /* tp_reserved */
  90. 0, /* tp_repr */
  91. 0, /* tp_as_number */
  92. 0, /* tp_as_sequence */
  93. 0, /* tp_as_mapping */
  94. 0, /* tp_hash */
  95. 0, /* tp_call */
  96. 0, /* tp_str */
  97. 0, /* tp_getattro */
  98. 0, /* tp_setattro */
  99. 0, /* tp_as_buffer */
  100. Py_TPFLAGS_DEFAULT, /* tp_flags */
  101. "azlmbr_redirect objects", /* tp_doc */
  102. 0, /* tp_traverse */
  103. 0, /* tp_clear */
  104. 0, /* tp_richcompare */
  105. 0, /* tp_weaklistoffset */
  106. 0, /* tp_iter */
  107. 0, /* tp_iternext */
  108. RedirectMethods, /* tp_methods */
  109. 0, /* tp_members */
  110. 0, /* tp_getset */
  111. 0, /* tp_base */
  112. 0, /* tp_dict */
  113. 0, /* tp_descr_get */
  114. 0, /* tp_descr_set */
  115. 0, /* tp_dictoffset */
  116. 0, /* tp_init */
  117. 0, /* tp_alloc */
  118. 0 /* tp_new */
  119. };
  120. PyModuleDef RedirectOutputModule = {
  121. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  122. };
  123. // Internal state
  124. PyObject* g_redirect_stdout = nullptr;
  125. PyObject* g_redirect_stdout_saved = nullptr;
  126. PyObject* g_redirect_stderr = nullptr;
  127. PyObject* g_redirect_stderr_saved = nullptr;
  128. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  129. {
  130. g_redirect_stdout = nullptr;
  131. g_redirect_stdout_saved = nullptr;
  132. g_redirect_stderr = nullptr;
  133. g_redirect_stderr_saved = nullptr;
  134. RedirectOutputType.tp_new = PyType_GenericNew;
  135. if (PyType_Ready(&RedirectOutputType) < 0)
  136. {
  137. return 0;
  138. }
  139. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  140. if (redirectModule)
  141. {
  142. Py_INCREF(&RedirectOutputType);
  143. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  144. }
  145. return redirectModule;
  146. }
  147. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  148. {
  149. if (PyType_Ready(&RedirectOutputType) < 0)
  150. {
  151. AZ_Warning("python", false, "RedirectOutputType not ready!");
  152. return;
  153. }
  154. if (!current)
  155. {
  156. saved = PySys_GetObject(funcname); // borrowed
  157. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  158. }
  159. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  160. redirectOutput->write = func;
  161. PySys_SetObject(funcname, current);
  162. }
  163. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  164. {
  165. if (current)
  166. {
  167. PySys_SetObject(funcname, saved);
  168. }
  169. Py_XDECREF(current);
  170. current = nullptr;
  171. }
  172. PyObject* s_RedirectModule = nullptr;
  173. void Intialize(PyObject* module)
  174. {
  175. s_RedirectModule = module;
  176. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, []([[maybe_unused]] const char* msg) {
  177. AZ_TracePrintf("Python", msg);
  178. });
  179. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) {
  180. AZ_TracePrintf("Python", msg);
  181. });
  182. PySys_WriteStdout("RedirectOutput installed");
  183. }
  184. void Shutdown()
  185. {
  186. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  187. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  188. Py_XDECREF(s_RedirectModule);
  189. s_RedirectModule = nullptr;
  190. }
  191. } // namespace RedirectOutput
  192. namespace O3DE::ProjectManager
  193. {
  194. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  195. : m_enginePath(enginePath)
  196. {
  197. StartPython();
  198. }
  199. PythonBindings::~PythonBindings()
  200. {
  201. StopPython();
  202. }
  203. bool PythonBindings::StartPython()
  204. {
  205. if (Py_IsInitialized())
  206. {
  207. AZ_Warning("python", false, "Python is already active");
  208. return false;
  209. }
  210. // set PYTHON_HOME
  211. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  212. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  213. {
  214. AZ_Warning("python", false, "Python home path must exist. path:%s", pyBasePath.c_str());
  215. return false;
  216. }
  217. AZStd::wstring pyHomePath;
  218. AZStd::to_wstring(pyHomePath, pyBasePath);
  219. Py_SetPythonHome(pyHomePath.c_str());
  220. // display basic Python information
  221. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  222. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  223. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  224. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  225. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  226. try
  227. {
  228. // ignore system location for sites site-packages
  229. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  230. Py_IgnoreEnvironmentFlag = 1; // -E
  231. const bool initializeSignalHandlers = true;
  232. pybind11::initialize_interpreter(initializeSignalHandlers);
  233. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  234. // Acquire GIL before calling Python code
  235. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  236. pybind11::gil_scoped_acquire acquire;
  237. // Setup sys.path
  238. int result = PyRun_SimpleString("import sys");
  239. AZ_Warning("ProjectManagerWindow", result != -1, "Import sys failed");
  240. result = PyRun_SimpleString(AZStd::string::format("sys.path.append('%s')", m_enginePath.c_str()).c_str());
  241. AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed");
  242. // import required modules
  243. m_register = pybind11::module::import("o3de.register");
  244. m_manifest = pybind11::module::import("o3de.manifest");
  245. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  246. m_addGemProject = pybind11::module::import("o3de.add_gem_project");
  247. m_removeGemProject = pybind11::module::import("o3de.remove_gem_project");
  248. return result == 0 && !PyErr_Occurred();
  249. } catch ([[maybe_unused]] const std::exception& e)
  250. {
  251. AZ_Warning("ProjectManagerWindow", false, "Py_Initialize() failed with %s", e.what());
  252. return false;
  253. }
  254. }
  255. bool PythonBindings::StopPython()
  256. {
  257. if (Py_IsInitialized())
  258. {
  259. RedirectOutput::Shutdown();
  260. pybind11::finalize_interpreter();
  261. }
  262. else
  263. {
  264. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  265. }
  266. return !PyErr_Occurred();
  267. }
  268. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  269. {
  270. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  271. pybind11::gil_scoped_release release;
  272. pybind11::gil_scoped_acquire acquire;
  273. try
  274. {
  275. executionCallback();
  276. return true;
  277. }
  278. catch ([[maybe_unused]] const std::exception& e)
  279. {
  280. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  281. return false;
  282. }
  283. }
  284. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  285. {
  286. EngineInfo engineInfo;
  287. bool result = ExecuteWithLock([&] {
  288. pybind11::str enginePath = m_manifest.attr("get_this_engine_path")();
  289. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  290. if (pybind11::isinstance<pybind11::dict>(o3deData))
  291. {
  292. engineInfo.m_path = Py_To_String(enginePath);
  293. engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]);
  294. engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]);
  295. engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]);
  296. engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]);
  297. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData,"third_party_path","");
  298. }
  299. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  300. if (pybind11::isinstance<pybind11::dict>(engineData))
  301. {
  302. try
  303. {
  304. engineInfo.m_version = Py_To_String_Optional(engineData,"O3DEVersion","0.0.0.0");
  305. engineInfo.m_name = Py_To_String_Optional(engineData,"engine_name","O3DE");
  306. }
  307. catch ([[maybe_unused]] const std::exception& e)
  308. {
  309. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  310. }
  311. }
  312. });
  313. if (!result || !engineInfo.IsValid())
  314. {
  315. return AZ::Failure();
  316. }
  317. else
  318. {
  319. return AZ::Success(AZStd::move(engineInfo));
  320. }
  321. return AZ::Failure();
  322. }
  323. bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo)
  324. {
  325. bool result = ExecuteWithLock([&] {
  326. pybind11::str enginePath = engineInfo.m_path.toStdString();
  327. pybind11::str defaultProjectsFolder = engineInfo.m_defaultProjectsFolder.toStdString();
  328. pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString();
  329. pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString();
  330. auto registrationResult = m_register.attr("register")(
  331. enginePath, // engine_path
  332. pybind11::none(), // project_path
  333. pybind11::none(), // gem_path
  334. pybind11::none(), // template_path
  335. pybind11::none(), // restricted_path
  336. pybind11::none(), // repo_uri
  337. pybind11::none(), // default_engines_folder
  338. defaultProjectsFolder,
  339. defaultGemsFolder,
  340. defaultTemplatesFolder
  341. );
  342. if (registrationResult.cast<int>() != 0)
  343. {
  344. result = false;
  345. }
  346. auto manifest = m_manifest.attr("load_o3de_manifest")();
  347. if (pybind11::isinstance<pybind11::dict>(manifest))
  348. {
  349. try
  350. {
  351. manifest["third_party_path"] = engineInfo.m_thirdPartyPath.toStdString();
  352. m_manifest.attr("save_o3de_manifest")(manifest);
  353. }
  354. catch ([[maybe_unused]] const std::exception& e)
  355. {
  356. AZ_Warning("PythonBindings", false, "Failed to set third party path.");
  357. }
  358. }
  359. });
  360. return result;
  361. }
  362. AZ::Outcome<GemInfo> PythonBindings::GetGem(const QString& path)
  363. {
  364. GemInfo gemInfo = GemInfoFromPath(pybind11::str(path.toStdString()));
  365. if (gemInfo.IsValid())
  366. {
  367. return AZ::Success(AZStd::move(gemInfo));
  368. }
  369. else
  370. {
  371. return AZ::Failure();
  372. }
  373. }
  374. AZ::Outcome<QVector<GemInfo>> PythonBindings::GetGems()
  375. {
  376. QVector<GemInfo> gems;
  377. bool result = ExecuteWithLock([&] {
  378. // external gems
  379. for (auto path : m_manifest.attr("get_gems")())
  380. {
  381. gems.push_back(GemInfoFromPath(path));
  382. }
  383. // gems from the engine
  384. for (auto path : m_manifest.attr("get_engine_gems")())
  385. {
  386. gems.push_back(GemInfoFromPath(path));
  387. }
  388. });
  389. if (!result)
  390. {
  391. return AZ::Failure();
  392. }
  393. else
  394. {
  395. return AZ::Success(AZStd::move(gems));
  396. }
  397. }
  398. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  399. {
  400. ProjectInfo createdProjectInfo;
  401. bool result = ExecuteWithLock([&] {
  402. pybind11::str projectPath = projectInfo.m_path.toStdString();
  403. pybind11::str templatePath = projectTemplatePath.toStdString();
  404. auto createProjectResult = m_engineTemplate.attr("create_project")(projectPath, templatePath);
  405. if (createProjectResult.cast<int>() == 0)
  406. {
  407. createdProjectInfo = ProjectInfoFromPath(projectPath);
  408. }
  409. });
  410. if (!result || !createdProjectInfo.IsValid())
  411. {
  412. return AZ::Failure();
  413. }
  414. else
  415. {
  416. return AZ::Success(AZStd::move(createdProjectInfo));
  417. }
  418. }
  419. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  420. {
  421. ProjectInfo projectInfo = ProjectInfoFromPath(pybind11::str(path.toStdString()));
  422. if (projectInfo.IsValid())
  423. {
  424. return AZ::Success(AZStd::move(projectInfo));
  425. }
  426. else
  427. {
  428. return AZ::Failure();
  429. }
  430. }
  431. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path)
  432. {
  433. GemInfo gemInfo;
  434. gemInfo.m_path = Py_To_String(path);
  435. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path);
  436. if (pybind11::isinstance<pybind11::dict>(data))
  437. {
  438. try
  439. {
  440. // required
  441. gemInfo.m_name = Py_To_String(data["gem_name"]);
  442. // optional
  443. gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name);
  444. gemInfo.m_summary = Py_To_String_Optional(data, "Summary", "");
  445. gemInfo.m_version = Py_To_String_Optional(data, "Version", "");
  446. if (data.contains("Tags"))
  447. {
  448. for (auto tag : data["Tags"])
  449. {
  450. gemInfo.m_features.push_back(Py_To_String(tag));
  451. }
  452. }
  453. }
  454. catch ([[maybe_unused]] const std::exception& e)
  455. {
  456. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  457. }
  458. }
  459. return gemInfo;
  460. }
  461. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  462. {
  463. ProjectInfo projectInfo;
  464. projectInfo.m_path = Py_To_String(path);
  465. projectInfo.m_isNew = false;
  466. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  467. if (pybind11::isinstance<pybind11::dict>(projectData))
  468. {
  469. try
  470. {
  471. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  472. projectInfo.m_displayName = Py_To_String_Optional(projectData,"display_name", projectInfo.m_projectName);
  473. }
  474. catch ([[maybe_unused]] const std::exception& e)
  475. {
  476. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  477. }
  478. }
  479. return projectInfo;
  480. }
  481. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  482. {
  483. QVector<ProjectInfo> projects;
  484. bool result = ExecuteWithLock([&] {
  485. // external projects
  486. for (auto path : m_manifest.attr("get_projects")())
  487. {
  488. projects.push_back(ProjectInfoFromPath(path));
  489. }
  490. // projects from the engine
  491. for (auto path : m_manifest.attr("get_engine_projects")())
  492. {
  493. projects.push_back(ProjectInfoFromPath(path));
  494. }
  495. });
  496. if (!result)
  497. {
  498. return AZ::Failure();
  499. }
  500. else
  501. {
  502. return AZ::Success(AZStd::move(projects));
  503. }
  504. }
  505. bool PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  506. {
  507. bool result = ExecuteWithLock([&] {
  508. pybind11::str pyGemPath = gemPath.toStdString();
  509. pybind11::str pyProjectPath = projectPath.toStdString();
  510. m_addGemProject.attr("add_gem_to_project")(
  511. pybind11::none(), // gem_name
  512. pyGemPath,
  513. pybind11::none(), // gem_target
  514. pybind11::none(), // project_name
  515. pyProjectPath
  516. );
  517. });
  518. return result;
  519. }
  520. bool PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  521. {
  522. bool result = ExecuteWithLock([&] {
  523. pybind11::str pyGemPath = gemPath.toStdString();
  524. pybind11::str pyProjectPath = projectPath.toStdString();
  525. m_removeGemProject.attr("remove_gem_from_project")(
  526. pybind11::none(), // gem_name
  527. pyGemPath,
  528. pybind11::none(), // gem_target
  529. pybind11::none(), // project_name
  530. pyProjectPath
  531. );
  532. });
  533. return result;
  534. }
  535. bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo)
  536. {
  537. return false;
  538. }
  539. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path)
  540. {
  541. ProjectTemplateInfo templateInfo;
  542. templateInfo.m_path = Py_To_String(path);
  543. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path);
  544. if (pybind11::isinstance<pybind11::dict>(data))
  545. {
  546. try
  547. {
  548. // required
  549. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  550. templateInfo.m_name = Py_To_String(data["template_name"]);
  551. templateInfo.m_summary = Py_To_String(data["summary"]);
  552. // optional
  553. if (data.contains("canonical_tags"))
  554. {
  555. for (auto tag : data["canonical_tags"])
  556. {
  557. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  558. }
  559. }
  560. if (data.contains("user_tags"))
  561. {
  562. for (auto tag : data["user_tags"])
  563. {
  564. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  565. }
  566. }
  567. }
  568. catch ([[maybe_unused]] const std::exception& e)
  569. {
  570. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  571. }
  572. }
  573. return templateInfo;
  574. }
  575. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates()
  576. {
  577. QVector<ProjectTemplateInfo> templates;
  578. bool result = ExecuteWithLock([&] {
  579. for (auto path : m_manifest.attr("get_project_templates")())
  580. {
  581. templates.push_back(ProjectTemplateInfoFromPath(path));
  582. }
  583. });
  584. if (!result)
  585. {
  586. return AZ::Failure();
  587. }
  588. else
  589. {
  590. return AZ::Success(AZStd::move(templates));
  591. }
  592. }
  593. }