PythonBindings.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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_cmake = pybind11::module::import("o3de.cmake");
  244. m_register = pybind11::module::import("o3de.register");
  245. m_manifest = pybind11::module::import("o3de.manifest");
  246. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  247. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  248. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  249. // make sure the engine is registered
  250. RegisterThisEngine();
  251. return result == 0 && !PyErr_Occurred();
  252. }
  253. catch ([[maybe_unused]] const std::exception& e)
  254. {
  255. AZ_Warning("ProjectManagerWindow", false, "Py_Initialize() failed with %s", e.what());
  256. return false;
  257. }
  258. }
  259. bool PythonBindings::StopPython()
  260. {
  261. if (Py_IsInitialized())
  262. {
  263. RedirectOutput::Shutdown();
  264. pybind11::finalize_interpreter();
  265. }
  266. else
  267. {
  268. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  269. }
  270. return !PyErr_Occurred();
  271. }
  272. bool PythonBindings::RegisterThisEngine()
  273. {
  274. bool registrationResult = true; // already registered is considered successful
  275. bool pythonResult = ExecuteWithLock(
  276. [&]
  277. {
  278. // check current engine path against all other registered engines
  279. // to see if we are already registered
  280. auto allEngines = m_manifest.attr("get_engines")();
  281. if (pybind11::isinstance<pybind11::list>(allEngines))
  282. {
  283. for (auto engine : allEngines)
  284. {
  285. AZ::IO::FixedMaxPath enginePath(Py_To_String(engine["path"]));
  286. if (enginePath.Compare(m_enginePath) == 0)
  287. {
  288. return;
  289. }
  290. }
  291. }
  292. auto result = m_register.attr("register")(m_enginePath.c_str());
  293. registrationResult = (result.cast<int>() == 0);
  294. });
  295. bool finalResult = (registrationResult && pythonResult);
  296. AZ_Assert(finalResult, "Registration of this engine failed!");
  297. return finalResult;
  298. }
  299. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback)
  300. {
  301. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  302. pybind11::gil_scoped_release release;
  303. pybind11::gil_scoped_acquire acquire;
  304. try
  305. {
  306. executionCallback();
  307. }
  308. catch ([[maybe_unused]] const std::exception& e)
  309. {
  310. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  311. return AZ::Failure<AZStd::string>(e.what());
  312. }
  313. return AZ::Success();
  314. }
  315. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  316. {
  317. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  318. }
  319. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  320. {
  321. EngineInfo engineInfo;
  322. bool result = ExecuteWithLock([&] {
  323. pybind11::str enginePath = m_manifest.attr("get_this_engine_path")();
  324. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  325. if (pybind11::isinstance<pybind11::dict>(o3deData))
  326. {
  327. engineInfo.m_path = Py_To_String(enginePath);
  328. engineInfo.m_defaultGemsFolder = Py_To_String(o3deData["default_gems_folder"]);
  329. engineInfo.m_defaultProjectsFolder = Py_To_String(o3deData["default_projects_folder"]);
  330. engineInfo.m_defaultRestrictedFolder = Py_To_String(o3deData["default_restricted_folder"]);
  331. engineInfo.m_defaultTemplatesFolder = Py_To_String(o3deData["default_templates_folder"]);
  332. engineInfo.m_thirdPartyPath = Py_To_String(o3deData["default_third_party_folder"]);
  333. }
  334. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  335. if (pybind11::isinstance<pybind11::dict>(engineData))
  336. {
  337. try
  338. {
  339. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  340. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  341. }
  342. catch ([[maybe_unused]] const std::exception& e)
  343. {
  344. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  345. }
  346. }
  347. });
  348. if (!result || !engineInfo.IsValid())
  349. {
  350. return AZ::Failure();
  351. }
  352. else
  353. {
  354. return AZ::Success(AZStd::move(engineInfo));
  355. }
  356. return AZ::Failure();
  357. }
  358. bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo)
  359. {
  360. bool result = ExecuteWithLock([&] {
  361. pybind11::str enginePath = engineInfo.m_path.toStdString();
  362. pybind11::str defaultProjectsFolder = engineInfo.m_defaultProjectsFolder.toStdString();
  363. pybind11::str defaultGemsFolder = engineInfo.m_defaultGemsFolder.toStdString();
  364. pybind11::str defaultTemplatesFolder = engineInfo.m_defaultTemplatesFolder.toStdString();
  365. pybind11::str defaultThirdPartyFolder = engineInfo.m_thirdPartyPath.toStdString();
  366. auto registrationResult = m_register.attr("register")(
  367. enginePath, // engine_path
  368. pybind11::none(), // project_path
  369. pybind11::none(), // gem_path
  370. pybind11::none(), // external_subdir_path
  371. pybind11::none(), // template_path
  372. pybind11::none(), // restricted_path
  373. pybind11::none(), // repo_uri
  374. pybind11::none(), // default_engines_folder
  375. defaultProjectsFolder,
  376. defaultGemsFolder,
  377. defaultTemplatesFolder,
  378. pybind11::none(), // default_restricted_folder
  379. defaultThirdPartyFolder
  380. );
  381. if (registrationResult.cast<int>() != 0)
  382. {
  383. result = false;
  384. }
  385. });
  386. return result;
  387. }
  388. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path)
  389. {
  390. GemInfo gemInfo = GemInfoFromPath(pybind11::str(path.toStdString()));
  391. if (gemInfo.IsValid())
  392. {
  393. return AZ::Success(AZStd::move(gemInfo));
  394. }
  395. else
  396. {
  397. return AZ::Failure();
  398. }
  399. }
  400. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  401. {
  402. QVector<GemInfo> gems;
  403. auto result = ExecuteWithLockErrorHandling([&]
  404. {
  405. for (auto path : m_manifest.attr("get_engine_gems")())
  406. {
  407. gems.push_back(GemInfoFromPath(path));
  408. }
  409. });
  410. if (!result.IsSuccess())
  411. {
  412. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  413. }
  414. std::sort(gems.begin(), gems.end());
  415. return AZ::Success(AZStd::move(gems));
  416. }
  417. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  418. {
  419. QVector<GemInfo> gems;
  420. auto result = ExecuteWithLockErrorHandling([&]
  421. {
  422. pybind11::str pyProjectPath = projectPath.toStdString();
  423. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  424. {
  425. gems.push_back(GemInfoFromPath(path));
  426. }
  427. });
  428. if (!result.IsSuccess())
  429. {
  430. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  431. }
  432. std::sort(gems.begin(), gems.end());
  433. return AZ::Success(AZStd::move(gems));
  434. }
  435. AZ::Outcome<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath)
  436. {
  437. // Retrieve the path to the cmake file that lists the enabled gems.
  438. pybind11::str enabledGemsFilename;
  439. auto result = ExecuteWithLockErrorHandling([&]
  440. {
  441. const pybind11::str pyProjectPath = projectPath.toStdString();
  442. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  443. pybind11::none(), // project_name
  444. pyProjectPath); // project_path
  445. });
  446. if (!result.IsSuccess())
  447. {
  448. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  449. }
  450. // Retrieve the actual list of names from the cmake file.
  451. QVector<AZStd::string> gemNames;
  452. result = ExecuteWithLockErrorHandling([&]
  453. {
  454. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  455. for (auto gemName : pyGemNames)
  456. {
  457. gemNames.push_back(Py_To_String(gemName));
  458. }
  459. });
  460. if (!result.IsSuccess())
  461. {
  462. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  463. }
  464. return AZ::Success(AZStd::move(gemNames));
  465. }
  466. bool PythonBindings::AddProject(const QString& path)
  467. {
  468. bool registrationResult = false;
  469. bool result = ExecuteWithLock(
  470. [&]
  471. {
  472. pybind11::str projectPath = path.toStdString();
  473. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  474. // Returns an exit code so boolify it then invert result
  475. registrationResult = !pythonRegistrationResult.cast<bool>();
  476. });
  477. return result && registrationResult;
  478. }
  479. bool PythonBindings::RemoveProject(const QString& path)
  480. {
  481. bool registrationResult = false;
  482. bool result = ExecuteWithLock(
  483. [&]
  484. {
  485. pybind11::str projectPath = path.toStdString();
  486. auto pythonRegistrationResult = m_register.attr("register")(
  487. pybind11::none(), // engine_path
  488. projectPath, // project_path
  489. pybind11::none(), // gem_path
  490. pybind11::none(), // external_subdir_path
  491. pybind11::none(), // template_path
  492. pybind11::none(), // restricted_path
  493. pybind11::none(), // repo_uri
  494. pybind11::none(), // default_engines_folder
  495. pybind11::none(), // default_projects_folder
  496. pybind11::none(), // default_gems_folder
  497. pybind11::none(), // default_templates_folder
  498. pybind11::none(), // default_restricted_folder
  499. pybind11::none(), // default_third_party_folder
  500. pybind11::none(), // external_subdir_engine_path
  501. pybind11::none(), // external_subdir_project_path
  502. true, // remove
  503. false // force
  504. );
  505. // Returns an exit code so boolify it then invert result
  506. registrationResult = !pythonRegistrationResult.cast<bool>();
  507. });
  508. return result && registrationResult;
  509. }
  510. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  511. {
  512. ProjectInfo createdProjectInfo;
  513. bool result = ExecuteWithLock([&] {
  514. pybind11::str projectPath = projectInfo.m_path.toStdString();
  515. pybind11::str projectName = projectInfo.m_projectName.toStdString();
  516. pybind11::str templatePath = projectTemplatePath.toStdString();
  517. auto createProjectResult = m_engineTemplate.attr("create_project")(
  518. projectPath,
  519. projectName,
  520. templatePath
  521. );
  522. if (createProjectResult.cast<int>() == 0)
  523. {
  524. createdProjectInfo = ProjectInfoFromPath(projectPath);
  525. }
  526. });
  527. if (!result || !createdProjectInfo.IsValid())
  528. {
  529. return AZ::Failure();
  530. }
  531. else
  532. {
  533. return AZ::Success(AZStd::move(createdProjectInfo));
  534. }
  535. }
  536. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  537. {
  538. ProjectInfo projectInfo = ProjectInfoFromPath(pybind11::str(path.toStdString()));
  539. if (projectInfo.IsValid())
  540. {
  541. return AZ::Success(AZStd::move(projectInfo));
  542. }
  543. else
  544. {
  545. return AZ::Failure();
  546. }
  547. }
  548. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path)
  549. {
  550. GemInfo gemInfo;
  551. gemInfo.m_path = Py_To_String(path);
  552. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path);
  553. if (pybind11::isinstance<pybind11::dict>(data))
  554. {
  555. try
  556. {
  557. // required
  558. gemInfo.m_name = Py_To_String(data["gem_name"]);
  559. // optional
  560. gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name);
  561. gemInfo.m_summary = Py_To_String_Optional(data, "Summary", "");
  562. gemInfo.m_version = Py_To_String_Optional(data, "Version", "");
  563. if (data.contains("Tags"))
  564. {
  565. for (auto tag : data["Tags"])
  566. {
  567. gemInfo.m_features.push_back(Py_To_String(tag));
  568. }
  569. }
  570. }
  571. catch ([[maybe_unused]] const std::exception& e)
  572. {
  573. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  574. }
  575. }
  576. return gemInfo;
  577. }
  578. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  579. {
  580. ProjectInfo projectInfo;
  581. projectInfo.m_path = Py_To_String(path);
  582. projectInfo.m_needsBuild = false;
  583. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  584. if (pybind11::isinstance<pybind11::dict>(projectData))
  585. {
  586. try
  587. {
  588. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  589. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  590. }
  591. catch ([[maybe_unused]] const std::exception& e)
  592. {
  593. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  594. }
  595. }
  596. return projectInfo;
  597. }
  598. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  599. {
  600. QVector<ProjectInfo> projects;
  601. bool result = ExecuteWithLock([&] {
  602. // external projects
  603. for (auto path : m_manifest.attr("get_projects")())
  604. {
  605. projects.push_back(ProjectInfoFromPath(path));
  606. }
  607. // projects from the engine
  608. for (auto path : m_manifest.attr("get_engine_projects")())
  609. {
  610. projects.push_back(ProjectInfoFromPath(path));
  611. }
  612. });
  613. if (!result)
  614. {
  615. return AZ::Failure();
  616. }
  617. else
  618. {
  619. return AZ::Success(AZStd::move(projects));
  620. }
  621. }
  622. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  623. {
  624. return ExecuteWithLockErrorHandling([&]
  625. {
  626. pybind11::str pyGemPath = gemPath.toStdString();
  627. pybind11::str pyProjectPath = projectPath.toStdString();
  628. m_enableGemProject.attr("enable_gem_in_project")(
  629. pybind11::none(), // gem name not needed as path is provided
  630. pyGemPath,
  631. pybind11::none(), // project name not needed as path is provided
  632. pyProjectPath
  633. );
  634. });
  635. }
  636. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  637. {
  638. return ExecuteWithLockErrorHandling([&]
  639. {
  640. pybind11::str pyGemPath = gemPath.toStdString();
  641. pybind11::str pyProjectPath = projectPath.toStdString();
  642. m_disableGemProject.attr("disable_gem_in_project")(
  643. pybind11::none(), // gem name not needed as path is provided
  644. pyGemPath,
  645. pybind11::none(), // project name not needed as path is provided
  646. pyProjectPath
  647. );
  648. });
  649. }
  650. bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo)
  651. {
  652. return false;
  653. }
  654. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path)
  655. {
  656. ProjectTemplateInfo templateInfo;
  657. templateInfo.m_path = Py_To_String(pybind11::str(path));
  658. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path);
  659. if (pybind11::isinstance<pybind11::dict>(data))
  660. {
  661. try
  662. {
  663. // required
  664. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  665. templateInfo.m_name = Py_To_String(data["template_name"]);
  666. templateInfo.m_summary = Py_To_String(data["summary"]);
  667. // optional
  668. if (data.contains("canonical_tags"))
  669. {
  670. for (auto tag : data["canonical_tags"])
  671. {
  672. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  673. }
  674. }
  675. if (data.contains("user_tags"))
  676. {
  677. for (auto tag : data["user_tags"])
  678. {
  679. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  680. }
  681. }
  682. if (data.contains("included_gems"))
  683. {
  684. for (auto gem : data["included_gems"])
  685. {
  686. templateInfo.m_includedGems.push_back(Py_To_String(gem));
  687. }
  688. }
  689. }
  690. catch ([[maybe_unused]] const std::exception& e)
  691. {
  692. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  693. }
  694. }
  695. return templateInfo;
  696. }
  697. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates()
  698. {
  699. QVector<ProjectTemplateInfo> templates;
  700. bool result = ExecuteWithLock([&] {
  701. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  702. {
  703. templates.push_back(ProjectTemplateInfoFromPath(path));
  704. }
  705. });
  706. if (!result)
  707. {
  708. return AZ::Failure();
  709. }
  710. else
  711. {
  712. return AZ::Success(AZStd::move(templates));
  713. }
  714. }
  715. }