PythonBindings.cpp 30 KB

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