PythonBindings.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <PythonBindings.h>
  9. #include <ProjectManagerDefs.h>
  10. // Qt defines slots, which interferes with the use here.
  11. #pragma push_macro("slots")
  12. #undef slots
  13. #include <pybind11/functional.h>
  14. #include <pybind11/embed.h>
  15. #include <pybind11/eval.h>
  16. #include <pybind11/stl.h>
  17. #pragma pop_macro("slots")
  18. #include <AzCore/IO/FileIO.h>
  19. #include <AzCore/IO/SystemFile.h>
  20. #include <AzCore/std/containers/unordered_set.h>
  21. #include <AzCore/std/string/conversions.h>
  22. #include <AzCore/std/numeric.h>
  23. #include <AzCore/StringFunc/StringFunc.h>
  24. #include <QDir>
  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 implementation 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) pybind11::str(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_Int(obj) obj.cast<int>()
  48. #define Py_To_Int_Optional(dict, key, default_int) dict.contains(key) ? Py_To_Int(dict[key]) : default_int
  49. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  50. #define QString_To_Py_Path(value) m_pathlib.attr("Path")(value.toStdString())
  51. namespace RedirectOutput
  52. {
  53. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  54. struct RedirectOutput
  55. {
  56. PyObject_HEAD RedirectOutputFunc write;
  57. };
  58. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  59. {
  60. std::size_t written(0);
  61. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  62. if (selfimpl->write)
  63. {
  64. char* data;
  65. if (!PyArg_ParseTuple(args, "s", &data))
  66. {
  67. return PyLong_FromSize_t(0);
  68. }
  69. selfimpl->write(data);
  70. written = strlen(data);
  71. }
  72. return PyLong_FromSize_t(written);
  73. }
  74. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  75. {
  76. // no-op
  77. return Py_BuildValue("");
  78. }
  79. PyMethodDef RedirectMethods[] = {
  80. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  81. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  82. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  83. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  84. {0, 0, 0, 0} // sentinel
  85. };
  86. PyTypeObject RedirectOutputType = {
  87. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  88. sizeof(RedirectOutput), /* tp_basicsize */
  89. 0, /* tp_itemsize */
  90. 0, /* tp_dealloc */
  91. 0, /* tp_print */
  92. 0, /* tp_getattr */
  93. 0, /* tp_setattr */
  94. 0, /* tp_reserved */
  95. 0, /* tp_repr */
  96. 0, /* tp_as_number */
  97. 0, /* tp_as_sequence */
  98. 0, /* tp_as_mapping */
  99. 0, /* tp_hash */
  100. 0, /* tp_call */
  101. 0, /* tp_str */
  102. 0, /* tp_getattro */
  103. 0, /* tp_setattro */
  104. 0, /* tp_as_buffer */
  105. Py_TPFLAGS_DEFAULT, /* tp_flags */
  106. "azlmbr_redirect objects", /* tp_doc */
  107. 0, /* tp_traverse */
  108. 0, /* tp_clear */
  109. 0, /* tp_richcompare */
  110. 0, /* tp_weaklistoffset */
  111. 0, /* tp_iter */
  112. 0, /* tp_iternext */
  113. RedirectMethods, /* tp_methods */
  114. 0, /* tp_members */
  115. 0, /* tp_getset */
  116. 0, /* tp_base */
  117. 0, /* tp_dict */
  118. 0, /* tp_descr_get */
  119. 0, /* tp_descr_set */
  120. 0, /* tp_dictoffset */
  121. 0, /* tp_init */
  122. 0, /* tp_alloc */
  123. 0 /* tp_new */
  124. };
  125. PyModuleDef RedirectOutputModule = {
  126. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  127. };
  128. // Internal state
  129. PyObject* g_redirect_stdout = nullptr;
  130. PyObject* g_redirect_stdout_saved = nullptr;
  131. PyObject* g_redirect_stderr = nullptr;
  132. PyObject* g_redirect_stderr_saved = nullptr;
  133. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  134. {
  135. g_redirect_stdout = nullptr;
  136. g_redirect_stdout_saved = nullptr;
  137. g_redirect_stderr = nullptr;
  138. g_redirect_stderr_saved = nullptr;
  139. RedirectOutputType.tp_new = PyType_GenericNew;
  140. if (PyType_Ready(&RedirectOutputType) < 0)
  141. {
  142. return 0;
  143. }
  144. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  145. if (redirectModule)
  146. {
  147. Py_INCREF(&RedirectOutputType);
  148. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  149. }
  150. return redirectModule;
  151. }
  152. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  153. {
  154. if (PyType_Ready(&RedirectOutputType) < 0)
  155. {
  156. AZ_Warning("python", false, "RedirectOutputType not ready!");
  157. return;
  158. }
  159. if (!current)
  160. {
  161. saved = PySys_GetObject(funcname); // borrowed
  162. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  163. }
  164. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  165. redirectOutput->write = func;
  166. PySys_SetObject(funcname, current);
  167. }
  168. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  169. {
  170. if (current)
  171. {
  172. PySys_SetObject(funcname, saved);
  173. }
  174. Py_XDECREF(current);
  175. current = nullptr;
  176. }
  177. PyObject* s_RedirectModule = nullptr;
  178. void Intialize(PyObject* module)
  179. {
  180. s_RedirectModule = module;
  181. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, []([[maybe_unused]] const char* msg) {
  182. AZ_TracePrintf("Python", msg);
  183. });
  184. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) {
  185. AZStd::string lastPythonError = msg;
  186. constexpr const char* pythonErrorPrefix = "ERROR:root:";
  187. constexpr size_t lengthOfErrorPrefix = AZStd::char_traits<char>::length(pythonErrorPrefix);
  188. auto errorPrefix = lastPythonError.find(pythonErrorPrefix);
  189. if (errorPrefix != AZStd::string::npos)
  190. {
  191. lastPythonError.erase(errorPrefix, lengthOfErrorPrefix);
  192. }
  193. O3DE::ProjectManager::PythonBindingsInterface::Get()->AddErrorString(lastPythonError);
  194. AZ_TracePrintf("Python", msg);
  195. });
  196. PySys_WriteStdout("RedirectOutput installed");
  197. }
  198. void Shutdown()
  199. {
  200. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  201. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  202. Py_XDECREF(s_RedirectModule);
  203. s_RedirectModule = nullptr;
  204. }
  205. } // namespace RedirectOutput
  206. namespace O3DE::ProjectManager
  207. {
  208. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  209. : m_enginePath(enginePath)
  210. {
  211. m_pythonStarted = StartPython();
  212. }
  213. PythonBindings::~PythonBindings()
  214. {
  215. StopPython();
  216. }
  217. bool PythonBindings::PythonStarted()
  218. {
  219. return m_pythonStarted && Py_IsInitialized();
  220. }
  221. bool PythonBindings::StartPython()
  222. {
  223. if (Py_IsInitialized())
  224. {
  225. AZ_Warning("python", false, "Python is already active");
  226. return m_pythonStarted;
  227. }
  228. m_pythonStarted = false;
  229. // set PYTHON_HOME
  230. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  231. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  232. {
  233. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  234. return false;
  235. }
  236. AZStd::wstring pyHomePath;
  237. AZStd::to_wstring(pyHomePath, pyBasePath);
  238. Py_SetPythonHome(pyHomePath.c_str());
  239. // display basic Python information
  240. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  241. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  242. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  243. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  244. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  245. try
  246. {
  247. // ignore system location for sites site-packages
  248. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  249. Py_IgnoreEnvironmentFlag = 1; // -E
  250. const bool initializeSignalHandlers = true;
  251. pybind11::initialize_interpreter(initializeSignalHandlers);
  252. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  253. // Acquire GIL before calling Python code
  254. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  255. pybind11::gil_scoped_acquire acquire;
  256. // sanity import check
  257. if (PyRun_SimpleString("import sys") != 0)
  258. {
  259. AZ_Assert(false, "Import sys failed");
  260. return false;
  261. }
  262. // import required modules
  263. m_cmake = pybind11::module::import("o3de.cmake");
  264. m_register = pybind11::module::import("o3de.register");
  265. m_manifest = pybind11::module::import("o3de.manifest");
  266. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  267. m_engineProperties = pybind11::module::import("o3de.engine_properties");
  268. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  269. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  270. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  271. m_download = pybind11::module::import("o3de.download");
  272. m_repo = pybind11::module::import("o3de.repo");
  273. m_pathlib = pybind11::module::import("pathlib");
  274. m_pythonStarted = !PyErr_Occurred();
  275. return m_pythonStarted;
  276. }
  277. catch ([[maybe_unused]] const std::exception& e)
  278. {
  279. AZ_Assert(false, "Py_Initialize() failed with %s", e.what());
  280. return false;
  281. }
  282. }
  283. bool PythonBindings::StopPython()
  284. {
  285. if (Py_IsInitialized())
  286. {
  287. RedirectOutput::Shutdown();
  288. pybind11::finalize_interpreter();
  289. }
  290. else
  291. {
  292. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  293. }
  294. return !PyErr_Occurred();
  295. }
  296. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback)
  297. {
  298. if (!Py_IsInitialized())
  299. {
  300. return AZ::Failure<AZStd::string>("Python is not initialized");
  301. }
  302. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  303. pybind11::gil_scoped_release release;
  304. pybind11::gil_scoped_acquire acquire;
  305. ClearErrorStrings();
  306. try
  307. {
  308. executionCallback();
  309. }
  310. catch ([[maybe_unused]] const std::exception& e)
  311. {
  312. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  313. return AZ::Failure<AZStd::string>(e.what());
  314. }
  315. return AZ::Success();
  316. }
  317. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  318. {
  319. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  320. }
  321. EngineInfo PythonBindings::EngineInfoFromPath(pybind11::handle enginePath)
  322. {
  323. EngineInfo engineInfo;
  324. try
  325. {
  326. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  327. if (pybind11::isinstance<pybind11::dict>(engineData))
  328. {
  329. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  330. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  331. engineInfo.m_path = Py_To_String(enginePath);
  332. }
  333. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  334. if (pybind11::isinstance<pybind11::dict>(o3deData))
  335. {
  336. auto defaultGemsFolder = m_manifest.attr("get_o3de_gems_folder")();
  337. engineInfo.m_defaultGemsFolder = Py_To_String_Optional(o3deData, "default_gems_folder", Py_To_String(defaultGemsFolder));
  338. auto defaultProjectsFolder = m_manifest.attr("get_o3de_projects_folder")();
  339. engineInfo.m_defaultProjectsFolder = Py_To_String_Optional(o3deData, "default_projects_folder", Py_To_String(defaultProjectsFolder));
  340. auto defaultRestrictedFolder = m_manifest.attr("get_o3de_restricted_folder")();
  341. engineInfo.m_defaultRestrictedFolder = Py_To_String_Optional(o3deData, "default_restricted_folder", Py_To_String(defaultRestrictedFolder));
  342. auto defaultTemplatesFolder = m_manifest.attr("get_o3de_templates_folder")();
  343. engineInfo.m_defaultTemplatesFolder = Py_To_String_Optional(o3deData, "default_templates_folder", Py_To_String(defaultTemplatesFolder));
  344. auto defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")();
  345. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData, "default_third_party_folder", Py_To_String(defaultThirdPartyFolder));
  346. }
  347. // check if engine path is registered
  348. auto allEngines = m_manifest.attr("get_engines")();
  349. if (pybind11::isinstance<pybind11::list>(allEngines))
  350. {
  351. const AZ::IO::FixedMaxPath enginePathFixed(Py_To_String(enginePath));
  352. for (auto engine : allEngines)
  353. {
  354. AZ::IO::FixedMaxPath otherEnginePath(Py_To_String(engine));
  355. if (otherEnginePath.Compare(enginePathFixed) == 0)
  356. {
  357. engineInfo.m_registered = true;
  358. break;
  359. }
  360. }
  361. }
  362. }
  363. catch ([[maybe_unused]] const std::exception& e)
  364. {
  365. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  366. }
  367. return engineInfo;
  368. }
  369. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  370. {
  371. EngineInfo engineInfo;
  372. bool result = ExecuteWithLock([&] {
  373. auto enginePath = m_manifest.attr("get_this_engine_path")();
  374. engineInfo = EngineInfoFromPath(enginePath);
  375. });
  376. if (!result || !engineInfo.IsValid())
  377. {
  378. return AZ::Failure();
  379. }
  380. else
  381. {
  382. return AZ::Success(AZStd::move(engineInfo));
  383. }
  384. }
  385. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo(const QString& engineName)
  386. {
  387. EngineInfo engineInfo;
  388. bool result = ExecuteWithLock([&] {
  389. auto enginePathResult = m_manifest.attr("get_registered")(QString_To_Py_String(engineName));
  390. // if a valid registered object is not found None is returned
  391. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  392. {
  393. engineInfo = EngineInfoFromPath(enginePathResult);
  394. // it is possible an engine is registered in o3de_manifest.json but the engine.json is
  395. // missing or corrupt in which case we do not consider it a registered engine
  396. }
  397. });
  398. if (!result || !engineInfo.IsValid())
  399. {
  400. return AZ::Failure();
  401. }
  402. else
  403. {
  404. return AZ::Success(AZStd::move(engineInfo));
  405. }
  406. }
  407. IPythonBindings::DetailedOutcome PythonBindings::SetEngineInfo(const EngineInfo& engineInfo, bool force)
  408. {
  409. bool registrationSuccess = false;
  410. bool pythonSuccess = ExecuteWithLock([&] {
  411. EngineInfo currentEngine = EngineInfoFromPath(QString_To_Py_Path(engineInfo.m_path));
  412. // be kind to source control and avoid needlessly updating engine.json
  413. if (currentEngine.IsValid() &&
  414. (currentEngine.m_name.compare(engineInfo.m_name) != 0 || currentEngine.m_version.compare(engineInfo.m_version) != 0))
  415. {
  416. auto enginePropsResult = m_engineProperties.attr("edit_engine_props")(
  417. QString_To_Py_Path(engineInfo.m_path),
  418. pybind11::none(), // existing engine_name
  419. QString_To_Py_String(engineInfo.m_name),
  420. QString_To_Py_String(engineInfo.m_version)
  421. );
  422. if (enginePropsResult.cast<int>() != 0)
  423. {
  424. // do not proceed with registration
  425. return;
  426. }
  427. }
  428. auto result = m_register.attr("register")(
  429. QString_To_Py_Path(engineInfo.m_path),
  430. pybind11::none(), // project_path
  431. pybind11::none(), // gem_path
  432. pybind11::none(), // external_subdir_path
  433. pybind11::none(), // template_path
  434. pybind11::none(), // restricted_path
  435. pybind11::none(), // repo_uri
  436. pybind11::none(), // default_engines_folder
  437. QString_To_Py_Path(engineInfo.m_defaultProjectsFolder),
  438. QString_To_Py_Path(engineInfo.m_defaultGemsFolder),
  439. QString_To_Py_Path(engineInfo.m_defaultTemplatesFolder),
  440. pybind11::none(), // default_restricted_folder
  441. QString_To_Py_Path(engineInfo.m_thirdPartyPath),
  442. pybind11::none(), // external_subdir_engine_path
  443. pybind11::none(), // external_subdir_project_path
  444. false, // remove
  445. force
  446. );
  447. registrationSuccess = result.cast<int>() == 0;
  448. });
  449. if (pythonSuccess && registrationSuccess)
  450. {
  451. return AZ::Success();
  452. }
  453. return AZ::Failure<ErrorPair>(GetErrorPair());
  454. }
  455. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  456. {
  457. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  458. if (gemInfo.IsValid())
  459. {
  460. return AZ::Success(AZStd::move(gemInfo));
  461. }
  462. else
  463. {
  464. return AZ::Failure();
  465. }
  466. }
  467. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  468. {
  469. QVector<GemInfo> gems;
  470. auto result = ExecuteWithLockErrorHandling([&]
  471. {
  472. for (auto path : m_manifest.attr("get_engine_gems")())
  473. {
  474. gems.push_back(GemInfoFromPath(path, pybind11::none()));
  475. }
  476. });
  477. if (!result.IsSuccess())
  478. {
  479. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  480. }
  481. std::sort(gems.begin(), gems.end());
  482. return AZ::Success(AZStd::move(gems));
  483. }
  484. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  485. {
  486. QVector<GemInfo> gems;
  487. auto result = ExecuteWithLockErrorHandling([&]
  488. {
  489. auto pyProjectPath = QString_To_Py_Path(projectPath);
  490. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  491. {
  492. GemInfo gemInfo = GemInfoFromPath(path, pyProjectPath);
  493. // Mark as downloaded because this gem was registered with an existing directory
  494. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  495. gems.push_back(AZStd::move(gemInfo));
  496. }
  497. });
  498. if (!result.IsSuccess())
  499. {
  500. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  501. }
  502. std::sort(gems.begin(), gems.end());
  503. return AZ::Success(AZStd::move(gems));
  504. }
  505. AZ::Outcome<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath)
  506. {
  507. // Retrieve the path to the cmake file that lists the enabled gems.
  508. pybind11::str enabledGemsFilename;
  509. auto result = ExecuteWithLockErrorHandling([&]
  510. {
  511. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  512. pybind11::none(), // project_name
  513. QString_To_Py_Path(projectPath)); // project_path
  514. });
  515. if (!result.IsSuccess())
  516. {
  517. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  518. }
  519. // Retrieve the actual list of names from the cmake file.
  520. QVector<AZStd::string> gemNames;
  521. result = ExecuteWithLockErrorHandling([&]
  522. {
  523. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  524. for (auto gemName : pyGemNames)
  525. {
  526. gemNames.push_back(Py_To_String(gemName));
  527. }
  528. });
  529. if (!result.IsSuccess())
  530. {
  531. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  532. }
  533. return AZ::Success(AZStd::move(gemNames));
  534. }
  535. AZ::Outcome<void, AZStd::string> PythonBindings::GemRegistration(const QString& gemPath, const QString& projectPath, bool remove)
  536. {
  537. bool registrationResult = false;
  538. auto result = ExecuteWithLockErrorHandling(
  539. [&]
  540. {
  541. auto externalProjectPath = projectPath.isEmpty() ? pybind11::none() : QString_To_Py_Path(projectPath);
  542. auto pythonRegistrationResult = m_register.attr("register")(
  543. pybind11::none(), // engine_path
  544. pybind11::none(), // project_path
  545. QString_To_Py_Path(gemPath), // gem folder
  546. pybind11::none(), // external subdirectory
  547. pybind11::none(), // template_path
  548. pybind11::none(), // restricted folder
  549. pybind11::none(), // repo uri
  550. pybind11::none(), // default_engines_folder
  551. pybind11::none(), // default_projects_folder
  552. pybind11::none(), // default_gems_folder
  553. pybind11::none(), // default_templates_folder
  554. pybind11::none(), // default_restricted_folder
  555. pybind11::none(), // default_third_party_folder
  556. pybind11::none(), // external_subdir_engine_path
  557. externalProjectPath, // external_subdir_project_path
  558. remove // remove
  559. );
  560. // Returns an exit code so boolify it then invert result
  561. registrationResult = !pythonRegistrationResult.cast<bool>();
  562. });
  563. if (!result.IsSuccess())
  564. {
  565. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  566. }
  567. else if (!registrationResult)
  568. {
  569. return AZ::Failure<AZStd::string>(AZStd::string::format(
  570. "Failed to %s gem path %s", remove ? "unregister" : "register", gemPath.toUtf8().constData()));
  571. }
  572. return AZ::Success();
  573. }
  574. AZ::Outcome<void, AZStd::string> PythonBindings::RegisterGem(const QString& gemPath, const QString& projectPath)
  575. {
  576. return GemRegistration(gemPath, projectPath);
  577. }
  578. AZ::Outcome<void, AZStd::string> PythonBindings::UnregisterGem(const QString& gemPath, const QString& projectPath)
  579. {
  580. return GemRegistration(gemPath, projectPath, /*remove*/true);
  581. }
  582. bool PythonBindings::AddProject(const QString& path)
  583. {
  584. bool registrationResult = false;
  585. bool result = ExecuteWithLock(
  586. [&]
  587. {
  588. auto projectPath = QString_To_Py_Path(path);
  589. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  590. // Returns an exit code so boolify it then invert result
  591. registrationResult = !pythonRegistrationResult.cast<bool>();
  592. });
  593. return result && registrationResult;
  594. }
  595. bool PythonBindings::RemoveProject(const QString& path)
  596. {
  597. bool registrationResult = false;
  598. bool result = ExecuteWithLock(
  599. [&]
  600. {
  601. auto pythonRegistrationResult = m_register.attr("register")(
  602. pybind11::none(), // engine_path
  603. QString_To_Py_Path(path), // project_path
  604. pybind11::none(), // gem_path
  605. pybind11::none(), // external_subdir_path
  606. pybind11::none(), // template_path
  607. pybind11::none(), // restricted_path
  608. pybind11::none(), // repo_uri
  609. pybind11::none(), // default_engines_folder
  610. pybind11::none(), // default_projects_folder
  611. pybind11::none(), // default_gems_folder
  612. pybind11::none(), // default_templates_folder
  613. pybind11::none(), // default_restricted_folder
  614. pybind11::none(), // default_third_party_folder
  615. pybind11::none(), // external_subdir_engine_path
  616. pybind11::none(), // external_subdir_project_path
  617. true, // remove
  618. false // force
  619. );
  620. // Returns an exit code so boolify it then invert result
  621. registrationResult = !pythonRegistrationResult.cast<bool>();
  622. });
  623. return result && registrationResult;
  624. }
  625. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  626. {
  627. ProjectInfo createdProjectInfo;
  628. bool result = ExecuteWithLock([&] {
  629. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  630. auto createProjectResult = m_engineTemplate.attr("create_project")(
  631. projectPath,
  632. QString_To_Py_String(projectInfo.m_projectName),
  633. QString_To_Py_Path(projectTemplatePath)
  634. );
  635. if (createProjectResult.cast<int>() == 0)
  636. {
  637. createdProjectInfo = ProjectInfoFromPath(projectPath);
  638. }
  639. });
  640. if (!result || !createdProjectInfo.IsValid())
  641. {
  642. return AZ::Failure();
  643. }
  644. else
  645. {
  646. return AZ::Success(AZStd::move(createdProjectInfo));
  647. }
  648. }
  649. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  650. {
  651. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  652. if (projectInfo.IsValid())
  653. {
  654. return AZ::Success(AZStd::move(projectInfo));
  655. }
  656. else
  657. {
  658. return AZ::Failure();
  659. }
  660. }
  661. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  662. {
  663. GemInfo gemInfo;
  664. gemInfo.m_path = Py_To_String(path);
  665. gemInfo.m_directoryLink = gemInfo.m_path;
  666. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  667. if (pybind11::isinstance<pybind11::dict>(data))
  668. {
  669. try
  670. {
  671. // required
  672. gemInfo.m_name = Py_To_String(data["gem_name"]);
  673. // optional
  674. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  675. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  676. gemInfo.m_version = Py_To_String_Optional(data, "version", gemInfo.m_version);
  677. gemInfo.m_lastUpdatedDate = Py_To_String_Optional(data, "last_updated", gemInfo.m_lastUpdatedDate);
  678. gemInfo.m_binarySizeInKB = Py_To_Int_Optional(data, "binary_size", gemInfo.m_binarySizeInKB);
  679. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  680. gemInfo.m_creator = Py_To_String_Optional(data, "origin", "");
  681. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  682. gemInfo.m_licenseText = Py_To_String_Optional(data, "license", "Unspecified License");
  683. gemInfo.m_licenseLink = Py_To_String_Optional(data, "license_url", "");
  684. gemInfo.m_repoUri = Py_To_String_Optional(data, "repo_uri", "");
  685. if (gemInfo.m_creator.contains("Open 3D Engine"))
  686. {
  687. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEngine;
  688. }
  689. else if (gemInfo.m_creator.contains("Amazon Web Services"))
  690. {
  691. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  692. }
  693. else if (data.contains("origin"))
  694. {
  695. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Remote;
  696. }
  697. // If no origin was provided this cannot be remote and would be specified if O3DE so it should be local
  698. else
  699. {
  700. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  701. }
  702. // As long Base Open3DEngine gems are installed before first startup non-remote gems will be downloaded
  703. if (gemInfo.m_gemOrigin != GemInfo::GemOrigin::Remote)
  704. {
  705. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  706. }
  707. if (data.contains("user_tags"))
  708. {
  709. for (auto tag : data["user_tags"])
  710. {
  711. gemInfo.m_features.push_back(Py_To_String(tag));
  712. }
  713. }
  714. if (data.contains("dependencies"))
  715. {
  716. for (auto dependency : data["dependencies"])
  717. {
  718. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  719. }
  720. }
  721. QString gemType = Py_To_String_Optional(data, "type", "");
  722. if (gemType == "Asset")
  723. {
  724. gemInfo.m_types |= GemInfo::Type::Asset;
  725. }
  726. if (gemType == "Code")
  727. {
  728. gemInfo.m_types |= GemInfo::Type::Code;
  729. }
  730. if (gemType == "Tool")
  731. {
  732. gemInfo.m_types |= GemInfo::Type::Tool;
  733. }
  734. }
  735. catch ([[maybe_unused]] const std::exception& e)
  736. {
  737. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  738. }
  739. }
  740. return gemInfo;
  741. }
  742. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  743. {
  744. ProjectInfo projectInfo;
  745. projectInfo.m_path = Py_To_String(path);
  746. projectInfo.m_needsBuild = false;
  747. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  748. if (pybind11::isinstance<pybind11::dict>(projectData))
  749. {
  750. try
  751. {
  752. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  753. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  754. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  755. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  756. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  757. if (projectData.contains("user_tags"))
  758. {
  759. for (auto tag : projectData["user_tags"])
  760. {
  761. projectInfo.m_userTags.append(Py_To_String(tag));
  762. }
  763. }
  764. }
  765. catch ([[maybe_unused]] const std::exception& e)
  766. {
  767. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  768. }
  769. }
  770. return projectInfo;
  771. }
  772. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  773. {
  774. QVector<ProjectInfo> projects;
  775. bool result = ExecuteWithLock([&] {
  776. // external projects
  777. for (auto path : m_manifest.attr("get_projects")())
  778. {
  779. projects.push_back(ProjectInfoFromPath(path));
  780. }
  781. // projects from the engine
  782. for (auto path : m_manifest.attr("get_engine_projects")())
  783. {
  784. projects.push_back(ProjectInfoFromPath(path));
  785. }
  786. });
  787. if (!result)
  788. {
  789. return AZ::Failure();
  790. }
  791. else
  792. {
  793. return AZ::Success(AZStd::move(projects));
  794. }
  795. }
  796. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  797. {
  798. return ExecuteWithLockErrorHandling([&]
  799. {
  800. m_enableGemProject.attr("enable_gem_in_project")(
  801. pybind11::none(), // gem name not needed as path is provided
  802. QString_To_Py_Path(gemPath),
  803. pybind11::none(), // project name not needed as path is provided
  804. QString_To_Py_Path(projectPath)
  805. );
  806. });
  807. }
  808. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  809. {
  810. return ExecuteWithLockErrorHandling([&]
  811. {
  812. m_disableGemProject.attr("disable_gem_in_project")(
  813. pybind11::none(), // gem name not needed as path is provided
  814. QString_To_Py_Path(gemPath),
  815. pybind11::none(), // project name not needed as path is provided
  816. QString_To_Py_Path(projectPath)
  817. );
  818. });
  819. }
  820. bool PythonBindings::RemoveInvalidProjects()
  821. {
  822. bool removalResult = false;
  823. bool result = ExecuteWithLock(
  824. [&]
  825. {
  826. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  827. // Returns an exit code so boolify it then invert result
  828. removalResult = !pythonRemovalResult.cast<bool>();
  829. });
  830. return result && removalResult;
  831. }
  832. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  833. {
  834. bool updateProjectSucceeded = false;
  835. auto result = ExecuteWithLockErrorHandling([&]
  836. {
  837. std::list<std::string> newTags;
  838. for (const auto& i : projectInfo.m_userTags)
  839. {
  840. newTags.push_back(i.toStdString());
  841. }
  842. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  843. QString_To_Py_Path(projectInfo.m_path),
  844. pybind11::none(), // proj_name not used
  845. QString_To_Py_String(projectInfo.m_projectName),
  846. QString_To_Py_String(projectInfo.m_origin),
  847. QString_To_Py_String(projectInfo.m_displayName),
  848. QString_To_Py_String(projectInfo.m_summary),
  849. QString_To_Py_String(projectInfo.m_iconPath), // new_icon
  850. pybind11::none(), // add_tags not used
  851. pybind11::none(), // remove_tags not used
  852. pybind11::list(pybind11::cast(newTags)));
  853. updateProjectSucceeded = (editResult.cast<int>() == 0);
  854. });
  855. if (!result.IsSuccess())
  856. {
  857. return result;
  858. }
  859. else if (!updateProjectSucceeded)
  860. {
  861. return AZ::Failure<AZStd::string>("Failed to update project.");
  862. }
  863. return AZ::Success();
  864. }
  865. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  866. {
  867. ProjectTemplateInfo templateInfo;
  868. templateInfo.m_path = Py_To_String(path);
  869. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path, pyProjectPath);
  870. if (pybind11::isinstance<pybind11::dict>(data))
  871. {
  872. try
  873. {
  874. // required
  875. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  876. templateInfo.m_name = Py_To_String(data["template_name"]);
  877. templateInfo.m_summary = Py_To_String(data["summary"]);
  878. // optional
  879. if (data.contains("canonical_tags"))
  880. {
  881. for (auto tag : data["canonical_tags"])
  882. {
  883. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  884. }
  885. }
  886. if (data.contains("user_tags"))
  887. {
  888. for (auto tag : data["user_tags"])
  889. {
  890. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  891. }
  892. }
  893. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  894. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  895. if (enabledGemNames)
  896. {
  897. for (auto gem : enabledGemNames.GetValue())
  898. {
  899. // Exclude the template ${Name} placeholder for the list of included gems
  900. // That Gem gets created with the project
  901. if (!gem.contains("${Name}"))
  902. {
  903. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  904. }
  905. }
  906. }
  907. }
  908. catch ([[maybe_unused]] const std::exception& e)
  909. {
  910. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  911. }
  912. }
  913. return templateInfo;
  914. }
  915. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates(const QString& projectPath)
  916. {
  917. QVector<ProjectTemplateInfo> templates;
  918. bool result = ExecuteWithLock([&] {
  919. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  920. {
  921. templates.push_back(ProjectTemplateInfoFromPath(path, QString_To_Py_Path(projectPath)));
  922. }
  923. });
  924. if (!result)
  925. {
  926. return AZ::Failure();
  927. }
  928. else
  929. {
  930. return AZ::Success(AZStd::move(templates));
  931. }
  932. }
  933. AZ::Outcome<void, AZStd::string> PythonBindings::RefreshGemRepo(const QString& repoUri)
  934. {
  935. bool refreshResult = false;
  936. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  937. [&]
  938. {
  939. auto pyUri = QString_To_Py_String(repoUri);
  940. auto pythonRefreshResult = m_repo.attr("refresh_repo")(pyUri);
  941. // Returns an exit code so boolify it then invert result
  942. refreshResult = !pythonRefreshResult.cast<bool>();
  943. });
  944. if (!result.IsSuccess())
  945. {
  946. return result;
  947. }
  948. else if (!refreshResult)
  949. {
  950. return AZ::Failure<AZStd::string>("Failed to refresh repo.");
  951. }
  952. return AZ::Success();
  953. }
  954. bool PythonBindings::RefreshAllGemRepos()
  955. {
  956. bool refreshResult = false;
  957. bool result = ExecuteWithLock(
  958. [&]
  959. {
  960. auto pythonRefreshResult = m_repo.attr("refresh_repos")();
  961. // Returns an exit code so boolify it then invert result
  962. refreshResult = !pythonRefreshResult.cast<bool>();
  963. });
  964. return result && refreshResult;
  965. }
  966. IPythonBindings::DetailedOutcome PythonBindings::AddGemRepo(const QString& repoUri)
  967. {
  968. bool registrationResult = false;
  969. bool result = ExecuteWithLock(
  970. [&]
  971. {
  972. auto pyUri = QString_To_Py_String(repoUri);
  973. auto pythonRegistrationResult = m_register.attr("register")(
  974. pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pyUri);
  975. // Returns an exit code so boolify it then invert result
  976. registrationResult = !pythonRegistrationResult.cast<bool>();
  977. });
  978. if (!result || !registrationResult)
  979. {
  980. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  981. }
  982. return AZ::Success();
  983. }
  984. bool PythonBindings::RemoveGemRepo(const QString& repoUri)
  985. {
  986. bool registrationResult = false;
  987. bool result = ExecuteWithLock(
  988. [&]
  989. {
  990. auto pythonRegistrationResult = m_register.attr("register")(
  991. pybind11::none(), // engine_path
  992. pybind11::none(), // project_path
  993. pybind11::none(), // gem_path
  994. pybind11::none(), // external_subdir_path
  995. pybind11::none(), // template_path
  996. pybind11::none(), // restricted_path
  997. QString_To_Py_String(repoUri), // repo_uri
  998. pybind11::none(), // default_engines_folder
  999. pybind11::none(), // default_projects_folder
  1000. pybind11::none(), // default_gems_folder
  1001. pybind11::none(), // default_templates_folder
  1002. pybind11::none(), // default_restricted_folder
  1003. pybind11::none(), // default_third_party_folder
  1004. pybind11::none(), // external_subdir_engine_path
  1005. pybind11::none(), // external_subdir_project_path
  1006. true, // remove
  1007. false // force
  1008. );
  1009. // Returns an exit code so boolify it then invert result
  1010. registrationResult = !pythonRegistrationResult.cast<bool>();
  1011. });
  1012. return result && registrationResult;
  1013. }
  1014. GemRepoInfo PythonBindings::GetGemRepoInfo(pybind11::handle repoUri)
  1015. {
  1016. GemRepoInfo gemRepoInfo;
  1017. gemRepoInfo.m_repoUri = Py_To_String(repoUri);
  1018. auto data = m_manifest.attr("get_repo_json_data")(repoUri);
  1019. if (pybind11::isinstance<pybind11::dict>(data))
  1020. {
  1021. try
  1022. {
  1023. // required
  1024. gemRepoInfo.m_repoUri = Py_To_String(data["repo_uri"]);
  1025. gemRepoInfo.m_name = Py_To_String(data["repo_name"]);
  1026. gemRepoInfo.m_creator = Py_To_String(data["origin"]);
  1027. // optional
  1028. gemRepoInfo.m_summary = Py_To_String_Optional(data, "summary", "No summary provided.");
  1029. gemRepoInfo.m_additionalInfo = Py_To_String_Optional(data, "additional_info", "");
  1030. auto repoPath = m_manifest.attr("get_repo_path")(repoUri);
  1031. gemRepoInfo.m_path = gemRepoInfo.m_directoryLink = Py_To_String(repoPath);
  1032. QString lastUpdated = Py_To_String_Optional(data, "last_updated", "");
  1033. gemRepoInfo.m_lastUpdated = QDateTime::fromString(lastUpdated, RepoTimeFormat);
  1034. if (data.contains("enabled"))
  1035. {
  1036. gemRepoInfo.m_isEnabled = data["enabled"].cast<bool>();
  1037. }
  1038. else
  1039. {
  1040. gemRepoInfo.m_isEnabled = false;
  1041. }
  1042. if (data.contains("gems"))
  1043. {
  1044. for (auto gemPath : data["gems"])
  1045. {
  1046. gemRepoInfo.m_includedGemUris.push_back(Py_To_String(gemPath));
  1047. }
  1048. }
  1049. }
  1050. catch ([[maybe_unused]] const std::exception& e)
  1051. {
  1052. AZ_Warning("PythonBindings", false, "Failed to get GemRepoInfo for repo %s", Py_To_String(repoUri));
  1053. }
  1054. }
  1055. return gemRepoInfo;
  1056. }
  1057. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  1058. {
  1059. QVector<GemRepoInfo> gemRepos;
  1060. auto result = ExecuteWithLockErrorHandling(
  1061. [&]
  1062. {
  1063. for (auto repoUri : m_manifest.attr("get_repos")())
  1064. {
  1065. gemRepos.push_back(GetGemRepoInfo(repoUri));
  1066. }
  1067. });
  1068. if (!result.IsSuccess())
  1069. {
  1070. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  1071. }
  1072. std::sort(gemRepos.begin(), gemRepos.end());
  1073. return AZ::Success(AZStd::move(gemRepos));
  1074. }
  1075. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForRepo(const QString& repoUri)
  1076. {
  1077. QVector<GemInfo> gemInfos;
  1078. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1079. [&]
  1080. {
  1081. auto pyUri = QString_To_Py_String(repoUri);
  1082. auto gemPaths = m_repo.attr("get_gem_json_paths_from_cached_repo")(pyUri);
  1083. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1084. {
  1085. for (auto path : gemPaths)
  1086. {
  1087. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1088. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1089. gemInfos.push_back(gemInfo);
  1090. }
  1091. }
  1092. });
  1093. if (!result.IsSuccess())
  1094. {
  1095. return AZ::Failure(result.GetError());
  1096. }
  1097. return AZ::Success(AZStd::move(gemInfos));
  1098. }
  1099. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForAllRepos()
  1100. {
  1101. QVector<GemInfo> gemInfos;
  1102. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1103. [&]
  1104. {
  1105. auto gemPaths = m_repo.attr("get_gem_json_paths_from_all_cached_repos")();
  1106. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1107. {
  1108. for (auto path : gemPaths)
  1109. {
  1110. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1111. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1112. gemInfos.push_back(gemInfo);
  1113. }
  1114. }
  1115. });
  1116. if (!result.IsSuccess())
  1117. {
  1118. return AZ::Failure(result.GetError());
  1119. }
  1120. return AZ::Success(AZStd::move(gemInfos));
  1121. }
  1122. IPythonBindings::DetailedOutcome PythonBindings::DownloadGem(
  1123. const QString& gemName, std::function<void(int, int)> gemProgressCallback, bool force)
  1124. {
  1125. // This process is currently limited to download a single gem at a time.
  1126. bool downloadSucceeded = false;
  1127. m_requestCancelDownload = false;
  1128. auto result = ExecuteWithLockErrorHandling(
  1129. [&]
  1130. {
  1131. auto downloadResult = m_download.attr("download_gem")(
  1132. QString_To_Py_String(gemName), // gem name
  1133. pybind11::none(), // destination path
  1134. false, // skip auto register
  1135. force, // force overwrite
  1136. pybind11::cpp_function(
  1137. [this, gemProgressCallback](int bytesDownloaded, int totalBytes)
  1138. {
  1139. gemProgressCallback(bytesDownloaded, totalBytes);
  1140. return m_requestCancelDownload;
  1141. }) // Callback for download progress and cancelling
  1142. );
  1143. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1144. });
  1145. if (!result.IsSuccess())
  1146. {
  1147. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1148. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1149. }
  1150. else if (!downloadSucceeded)
  1151. {
  1152. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1153. }
  1154. return AZ::Success();
  1155. }
  1156. void PythonBindings::CancelDownload()
  1157. {
  1158. m_requestCancelDownload = true;
  1159. }
  1160. bool PythonBindings::IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated)
  1161. {
  1162. bool updateAvaliableResult = false;
  1163. bool result = ExecuteWithLock(
  1164. [&]
  1165. {
  1166. auto pyGemName = QString_To_Py_String(gemName);
  1167. auto pyLastUpdated = QString_To_Py_String(lastUpdated);
  1168. auto pythonUpdateAvaliableResult = m_download.attr("is_o3de_gem_update_available")(pyGemName, pyLastUpdated);
  1169. updateAvaliableResult = pythonUpdateAvaliableResult.cast<bool>();
  1170. });
  1171. return result && updateAvaliableResult;
  1172. }
  1173. IPythonBindings::ErrorPair PythonBindings::GetErrorPair()
  1174. {
  1175. AZStd::string detailedString = m_pythonErrorStrings.size() == 1
  1176. ? ""
  1177. : AZStd::accumulate(m_pythonErrorStrings.begin(), m_pythonErrorStrings.end(), AZStd::string(""));
  1178. return IPythonBindings::ErrorPair(m_pythonErrorStrings.front(), detailedString);
  1179. }
  1180. void PythonBindings::AddErrorString(AZStd::string errorString)
  1181. {
  1182. m_pythonErrorStrings.push_back(errorString);
  1183. }
  1184. void PythonBindings::ClearErrorStrings()
  1185. {
  1186. m_pythonErrorStrings.clear();
  1187. }
  1188. }