PythonBindings.cpp 30 KB

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