PythonBindings.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  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 <AzCore/std/sort.h>
  25. #include <QDir>
  26. namespace Platform
  27. {
  28. bool InsertPythonLibraryPath(
  29. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  30. {
  31. // append lib path to Python paths
  32. AZ::IO::FixedMaxPath libPath = engineRoot;
  33. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  34. libPath = libPath.LexicallyNormal();
  35. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  36. {
  37. paths.insert(libPath.c_str());
  38. return true;
  39. }
  40. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  41. return false;
  42. }
  43. // Implemented in each different platform's PAL implementation files, as it differs per platform.
  44. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  45. } // namespace Platform
  46. #define Py_To_String(obj) pybind11::str(obj).cast<std::string>().c_str()
  47. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  48. #define Py_To_Int(obj) obj.cast<int>()
  49. #define Py_To_Int_Optional(dict, key, default_int) dict.contains(key) ? Py_To_Int(dict[key]) : default_int
  50. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  51. #define QString_To_Py_Path(value) m_pathlib.attr("Path")(value.toStdString())
  52. namespace RedirectOutput
  53. {
  54. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  55. struct RedirectOutput
  56. {
  57. PyObject_HEAD RedirectOutputFunc write;
  58. };
  59. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  60. {
  61. std::size_t written(0);
  62. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  63. if (selfimpl->write)
  64. {
  65. char* data;
  66. if (!PyArg_ParseTuple(args, "s", &data))
  67. {
  68. return PyLong_FromSize_t(0);
  69. }
  70. selfimpl->write(data);
  71. written = strlen(data);
  72. }
  73. return PyLong_FromSize_t(written);
  74. }
  75. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  76. {
  77. // no-op
  78. return Py_BuildValue("");
  79. }
  80. PyMethodDef RedirectMethods[] = {
  81. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  82. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  83. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  84. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  85. {0, 0, 0, 0} // sentinel
  86. };
  87. PyTypeObject RedirectOutputType = {
  88. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  89. sizeof(RedirectOutput), /* tp_basicsize */
  90. 0, /* tp_itemsize */
  91. 0, /* tp_dealloc */
  92. 0, /* tp_print */
  93. 0, /* tp_getattr */
  94. 0, /* tp_setattr */
  95. 0, /* tp_reserved */
  96. 0, /* tp_repr */
  97. 0, /* tp_as_number */
  98. 0, /* tp_as_sequence */
  99. 0, /* tp_as_mapping */
  100. 0, /* tp_hash */
  101. 0, /* tp_call */
  102. 0, /* tp_str */
  103. 0, /* tp_getattro */
  104. 0, /* tp_setattro */
  105. 0, /* tp_as_buffer */
  106. Py_TPFLAGS_DEFAULT, /* tp_flags */
  107. "azlmbr_redirect objects", /* tp_doc */
  108. 0, /* tp_traverse */
  109. 0, /* tp_clear */
  110. 0, /* tp_richcompare */
  111. 0, /* tp_weaklistoffset */
  112. 0, /* tp_iter */
  113. 0, /* tp_iternext */
  114. RedirectMethods, /* tp_methods */
  115. 0, /* tp_members */
  116. 0, /* tp_getset */
  117. 0, /* tp_base */
  118. 0, /* tp_dict */
  119. 0, /* tp_descr_get */
  120. 0, /* tp_descr_set */
  121. 0, /* tp_dictoffset */
  122. 0, /* tp_init */
  123. 0, /* tp_alloc */
  124. 0 /* tp_new */
  125. };
  126. PyModuleDef RedirectOutputModule = {
  127. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  128. };
  129. // Internal state
  130. PyObject* g_redirect_stdout = nullptr;
  131. PyObject* g_redirect_stdout_saved = nullptr;
  132. PyObject* g_redirect_stderr = nullptr;
  133. PyObject* g_redirect_stderr_saved = nullptr;
  134. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  135. {
  136. g_redirect_stdout = nullptr;
  137. g_redirect_stdout_saved = nullptr;
  138. g_redirect_stderr = nullptr;
  139. g_redirect_stderr_saved = nullptr;
  140. RedirectOutputType.tp_new = PyType_GenericNew;
  141. if (PyType_Ready(&RedirectOutputType) < 0)
  142. {
  143. return 0;
  144. }
  145. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  146. if (redirectModule)
  147. {
  148. Py_INCREF(&RedirectOutputType);
  149. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  150. }
  151. return redirectModule;
  152. }
  153. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  154. {
  155. if (PyType_Ready(&RedirectOutputType) < 0)
  156. {
  157. AZ_Warning("python", false, "RedirectOutputType not ready!");
  158. return;
  159. }
  160. if (!current)
  161. {
  162. saved = PySys_GetObject(funcname); // borrowed
  163. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  164. }
  165. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  166. redirectOutput->write = func;
  167. PySys_SetObject(funcname, current);
  168. }
  169. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  170. {
  171. if (current)
  172. {
  173. PySys_SetObject(funcname, saved);
  174. }
  175. Py_XDECREF(current);
  176. current = nullptr;
  177. }
  178. PyObject* s_RedirectModule = nullptr;
  179. void Intialize(PyObject* module, RedirectOutputFunc stdoutFunction, RedirectOutputFunc stderrFunction)
  180. {
  181. s_RedirectModule = module;
  182. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, stdoutFunction);
  183. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, stderrFunction);
  184. PySys_WriteStdout("RedirectOutput installed\n");
  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. m_pythonStarted = StartPython();
  200. }
  201. PythonBindings::~PythonBindings()
  202. {
  203. if (m_pythonStarted)
  204. {
  205. StopPython();
  206. }
  207. }
  208. void PythonBindings::OnStdOut(const char* msg)
  209. {
  210. AZ::Debug::Trace::Instance().Output("Python", msg);
  211. }
  212. void PythonBindings::OnStdError(const char* msg)
  213. {
  214. AZStd::string_view lastPythonError{ msg };
  215. if (constexpr AZStd::string_view pythonErrorPrefix = "ERROR:root:";
  216. lastPythonError.starts_with(pythonErrorPrefix))
  217. {
  218. lastPythonError = lastPythonError.substr(pythonErrorPrefix.size());
  219. }
  220. PythonBindingsInterface::Get()->AddErrorString(lastPythonError);
  221. AZ::Debug::Trace::Instance().Output("Python", msg);
  222. }
  223. bool PythonBindings::PythonStarted()
  224. {
  225. return m_pythonStarted && Py_IsInitialized();
  226. }
  227. bool PythonBindings::StartPython()
  228. {
  229. if (Py_IsInitialized())
  230. {
  231. AZ_Warning("python", false, "Python is already active");
  232. return m_pythonStarted;
  233. }
  234. m_pythonStarted = false;
  235. // set PYTHON_HOME
  236. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  237. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  238. {
  239. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  240. return false;
  241. }
  242. AZStd::wstring pyHomePath;
  243. AZStd::to_wstring(pyHomePath, pyBasePath);
  244. Py_SetPythonHome(pyHomePath.c_str());
  245. // display basic Python information
  246. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  247. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  248. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  249. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  250. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  251. try
  252. {
  253. // ignore system location for sites site-packages
  254. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  255. Py_IgnoreEnvironmentFlag = 1; // -E
  256. const bool initializeSignalHandlers = true;
  257. pybind11::initialize_interpreter(initializeSignalHandlers);
  258. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"), &PythonBindings::OnStdOut, &PythonBindings::OnStdError);
  259. // Acquire GIL before calling Python code
  260. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  261. pybind11::gil_scoped_acquire acquire;
  262. // sanity import check
  263. if (PyRun_SimpleString("import sys") != 0)
  264. {
  265. AZ_Assert(false, "Import sys failed");
  266. return false;
  267. }
  268. // import required modules
  269. m_cmake = pybind11::module::import("o3de.cmake");
  270. m_register = pybind11::module::import("o3de.register");
  271. m_manifest = pybind11::module::import("o3de.manifest");
  272. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  273. m_gemProperties = pybind11::module::import("o3de.gem_properties");
  274. m_engineProperties = pybind11::module::import("o3de.engine_properties");
  275. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  276. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  277. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  278. m_download = pybind11::module::import("o3de.download");
  279. m_repo = pybind11::module::import("o3de.repo");
  280. m_pathlib = pybind11::module::import("pathlib");
  281. m_pythonStarted = !PyErr_Occurred();
  282. return m_pythonStarted;
  283. }
  284. catch ([[maybe_unused]] const std::exception& e)
  285. {
  286. AZ_Assert(false, "Py_Initialize() failed with %s", e.what());
  287. return false;
  288. }
  289. }
  290. bool PythonBindings::StopPython()
  291. {
  292. if (Py_IsInitialized())
  293. {
  294. RedirectOutput::Shutdown();
  295. pybind11::finalize_interpreter();
  296. }
  297. return Py_IsInitialized() == 0;
  298. }
  299. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback) const
  300. {
  301. if (!Py_IsInitialized())
  302. {
  303. return AZ::Failure<AZStd::string>("Python is not initialized");
  304. }
  305. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  306. pybind11::gil_scoped_release release;
  307. pybind11::gil_scoped_acquire acquire;
  308. m_pythonErrorStrings.clear();
  309. try
  310. {
  311. executionCallback();
  312. }
  313. catch ([[maybe_unused]] const std::exception& e)
  314. {
  315. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  316. return AZ::Failure<AZStd::string>(e.what());
  317. }
  318. return AZ::Success();
  319. }
  320. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback) const
  321. {
  322. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  323. }
  324. EngineInfo PythonBindings::EngineInfoFromPath(pybind11::handle enginePath)
  325. {
  326. EngineInfo engineInfo;
  327. try
  328. {
  329. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  330. if (pybind11::isinstance<pybind11::dict>(engineData))
  331. {
  332. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  333. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  334. engineInfo.m_path = Py_To_String(enginePath);
  335. auto thisEnginePath = m_manifest.attr("get_this_engine_path")();
  336. if (pybind11::isinstance(thisEnginePath, m_pathlib.attr("Path")().get_type()) &&
  337. thisEnginePath.attr("samefile")(enginePath).cast<bool>())
  338. {
  339. engineInfo.m_thisEngine = true;
  340. }
  341. }
  342. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  343. if (pybind11::isinstance<pybind11::dict>(o3deData))
  344. {
  345. auto defaultGemsFolder = m_manifest.attr("get_o3de_gems_folder")();
  346. engineInfo.m_defaultGemsFolder = Py_To_String_Optional(o3deData, "default_gems_folder", Py_To_String(defaultGemsFolder));
  347. auto defaultProjectsFolder = m_manifest.attr("get_o3de_projects_folder")();
  348. engineInfo.m_defaultProjectsFolder = Py_To_String_Optional(o3deData, "default_projects_folder", Py_To_String(defaultProjectsFolder));
  349. auto defaultRestrictedFolder = m_manifest.attr("get_o3de_restricted_folder")();
  350. engineInfo.m_defaultRestrictedFolder = Py_To_String_Optional(o3deData, "default_restricted_folder", Py_To_String(defaultRestrictedFolder));
  351. auto defaultTemplatesFolder = m_manifest.attr("get_o3de_templates_folder")();
  352. engineInfo.m_defaultTemplatesFolder = Py_To_String_Optional(o3deData, "default_templates_folder", Py_To_String(defaultTemplatesFolder));
  353. auto defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")();
  354. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData, "default_third_party_folder", Py_To_String(defaultThirdPartyFolder));
  355. }
  356. // check if engine path is registered
  357. auto allEngines = m_manifest.attr("get_manifest_engines")();
  358. if (pybind11::isinstance<pybind11::list>(allEngines))
  359. {
  360. const AZ::IO::FixedMaxPath enginePathFixed(Py_To_String(enginePath));
  361. for (auto engine : allEngines)
  362. {
  363. AZ::IO::FixedMaxPath otherEnginePath(Py_To_String(engine));
  364. if (otherEnginePath.Compare(enginePathFixed) == 0)
  365. {
  366. engineInfo.m_registered = true;
  367. break;
  368. }
  369. }
  370. }
  371. }
  372. catch ([[maybe_unused]] const std::exception& e)
  373. {
  374. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  375. }
  376. return engineInfo;
  377. }
  378. AZ::Outcome<QVector<EngineInfo>> PythonBindings::GetAllEngineInfos()
  379. {
  380. QVector<EngineInfo> engines;
  381. auto result = ExecuteWithLockErrorHandling([&]
  382. {
  383. for (auto path : m_manifest.attr("get_manifest_engines")())
  384. {
  385. engines.push_back(EngineInfoFromPath(path));
  386. }
  387. });
  388. if (!result.IsSuccess())
  389. {
  390. return AZ::Failure();
  391. }
  392. AZStd::sort(engines.begin(), engines.end());
  393. return AZ::Success(AZStd::move(engines));
  394. }
  395. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  396. {
  397. EngineInfo engineInfo;
  398. bool result = ExecuteWithLock([&] {
  399. auto enginePath = m_manifest.attr("get_this_engine_path")();
  400. engineInfo = EngineInfoFromPath(enginePath);
  401. });
  402. if (!result || !engineInfo.IsValid())
  403. {
  404. return AZ::Failure();
  405. }
  406. else
  407. {
  408. return AZ::Success(AZStd::move(engineInfo));
  409. }
  410. }
  411. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo(const QString& engineName)
  412. {
  413. EngineInfo engineInfo;
  414. bool result = ExecuteWithLock([&] {
  415. auto enginePathResult = m_manifest.attr("get_registered")(QString_To_Py_String(engineName));
  416. // if a valid registered object is not found None is returned
  417. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  418. {
  419. engineInfo = EngineInfoFromPath(enginePathResult);
  420. // it is possible an engine is registered in o3de_manifest.json but the engine.json is
  421. // missing or corrupt in which case we do not consider it a registered engine
  422. }
  423. });
  424. if (!result || !engineInfo.IsValid())
  425. {
  426. return AZ::Failure();
  427. }
  428. else
  429. {
  430. return AZ::Success(AZStd::move(engineInfo));
  431. }
  432. }
  433. AZ::Outcome<EngineInfo> PythonBindings::GetProjectEngine(const QString& projectPath)
  434. {
  435. EngineInfo engineInfo;
  436. bool result = ExecuteWithLock([&] {
  437. auto enginePathResult = m_manifest.attr("get_project_engine_path")(QString_To_Py_Path(projectPath));
  438. // if a valid registered object is not found None is returned
  439. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  440. {
  441. // request a posix path so it looks like what is in o3de_manifest.json
  442. engineInfo = EngineInfoFromPath(enginePathResult.attr("as_posix")());
  443. }
  444. });
  445. if (!result || !engineInfo.IsValid())
  446. {
  447. return AZ::Failure();
  448. }
  449. else
  450. {
  451. return AZ::Success(AZStd::move(engineInfo));
  452. }
  453. }
  454. IPythonBindings::DetailedOutcome PythonBindings::SetEngineInfo(const EngineInfo& engineInfo, bool force)
  455. {
  456. using namespace pybind11::literals;
  457. bool registrationSuccess = false;
  458. bool pythonSuccess = ExecuteWithLock([&] {
  459. EngineInfo currentEngine = EngineInfoFromPath(QString_To_Py_Path(engineInfo.m_path));
  460. // be kind to source control and avoid needlessly updating engine.json
  461. if (currentEngine.IsValid() &&
  462. (currentEngine.m_name.compare(engineInfo.m_name) != 0 || currentEngine.m_version.compare(engineInfo.m_version) != 0))
  463. {
  464. auto enginePropsResult = m_engineProperties.attr("edit_engine_props")(
  465. QString_To_Py_Path(engineInfo.m_path),
  466. pybind11::none(), // existing engine_name
  467. QString_To_Py_String(engineInfo.m_name),
  468. QString_To_Py_String(engineInfo.m_version)
  469. );
  470. if (enginePropsResult.cast<int>() != 0)
  471. {
  472. // do not proceed with registration
  473. return;
  474. }
  475. }
  476. auto result = m_register.attr("register")(
  477. "engine_path"_a = QString_To_Py_Path(engineInfo.m_path),
  478. "project_path"_a = pybind11::none(),
  479. "gem_path"_a = pybind11::none(),
  480. "external_subdir_path"_a = pybind11::none(),
  481. "template_path"_a = pybind11::none(),
  482. "restricted_path"_a = pybind11::none(),
  483. "repo_uri"_a = pybind11::none(),
  484. "default_engines_folder"_a = pybind11::none(),
  485. "default_projects_folder"_a = QString_To_Py_Path(engineInfo.m_defaultProjectsFolder),
  486. "default_gems_folder"_a = QString_To_Py_Path(engineInfo.m_defaultGemsFolder),
  487. "default_templates_folder"_a = QString_To_Py_Path(engineInfo.m_defaultTemplatesFolder),
  488. "default_restricted_folder"_a = pybind11::none(),
  489. "default_third_party_folder"_a = QString_To_Py_Path(engineInfo.m_thirdPartyPath),
  490. "external_subdir_engine_path"_a = pybind11::none(),
  491. "external_subdir_project_path"_a = pybind11::none(),
  492. "external_subdir_gem_path"_a = pybind11::none(),
  493. "remove"_a = false,
  494. "force"_a = force
  495. );
  496. registrationSuccess = result.cast<int>() == 0;
  497. });
  498. if (pythonSuccess && registrationSuccess)
  499. {
  500. return AZ::Success();
  501. }
  502. return AZ::Failure<ErrorPair>(GetErrorPair());
  503. }
  504. bool PythonBindings::ValidateRepository(const QString& repoUri)
  505. {
  506. bool validateResult = false;
  507. bool result = ExecuteWithLock(
  508. [&]
  509. {
  510. auto pythonRepoUri = QString_To_Py_String(repoUri);
  511. auto pythonValidationResult = m_repo.attr("validate_remote_repo")(pythonRepoUri, true);
  512. validateResult = pythonValidationResult.cast<bool>();
  513. });
  514. return result && validateResult;
  515. }
  516. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  517. {
  518. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  519. if (gemInfo.IsValid())
  520. {
  521. return AZ::Success(AZStd::move(gemInfo));
  522. }
  523. else
  524. {
  525. return AZ::Failure();
  526. }
  527. }
  528. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  529. {
  530. QVector<GemInfo> gems;
  531. auto result = ExecuteWithLockErrorHandling([&]
  532. {
  533. for (auto path : m_manifest.attr("get_engine_gems")())
  534. {
  535. gems.push_back(GemInfoFromPath(path, pybind11::none()));
  536. }
  537. });
  538. if (!result.IsSuccess())
  539. {
  540. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  541. }
  542. AZStd::sort(gems.begin(), gems.end());
  543. return AZ::Success(AZStd::move(gems));
  544. }
  545. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  546. {
  547. QVector<GemInfo> gems;
  548. auto result = ExecuteWithLockErrorHandling([&]
  549. {
  550. auto pyProjectPath = QString_To_Py_Path(projectPath);
  551. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  552. {
  553. GemInfo gemInfo = GemInfoFromPath(path, pyProjectPath);
  554. // Mark as downloaded because this gem was registered with an existing directory
  555. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  556. gems.push_back(AZStd::move(gemInfo));
  557. }
  558. });
  559. if (!result.IsSuccess())
  560. {
  561. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  562. }
  563. AZStd::sort(gems.begin(), gems.end());
  564. return AZ::Success(AZStd::move(gems));
  565. }
  566. AZ::Outcome<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath) const
  567. {
  568. // Retrieve the path to the cmake file that lists the enabled gems.
  569. pybind11::str enabledGemsFilename;
  570. auto result = ExecuteWithLockErrorHandling([&]
  571. {
  572. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  573. pybind11::none(), // project_name
  574. QString_To_Py_Path(projectPath)); // project_path
  575. });
  576. if (!result.IsSuccess())
  577. {
  578. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  579. }
  580. // Retrieve the actual list of names from the cmake file.
  581. QVector<AZStd::string> gemNames;
  582. result = ExecuteWithLockErrorHandling([&]
  583. {
  584. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  585. for (auto gemName : pyGemNames)
  586. {
  587. gemNames.push_back(Py_To_String(gemName));
  588. }
  589. });
  590. if (!result.IsSuccess())
  591. {
  592. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  593. }
  594. return AZ::Success(AZStd::move(gemNames));
  595. }
  596. AZ::Outcome<void, AZStd::string> PythonBindings::GemRegistration(const QString& gemPath, const QString& projectPath, bool remove)
  597. {
  598. using namespace pybind11::literals;
  599. bool registrationResult = false;
  600. auto result = ExecuteWithLockErrorHandling(
  601. [&]
  602. {
  603. auto externalProjectPath = projectPath.isEmpty() ? pybind11::none() : QString_To_Py_Path(projectPath);
  604. auto pythonRegistrationResult = m_register.attr("register")(
  605. "engine_path"_a = pybind11::none(),
  606. "project_path"_a = pybind11::none(),
  607. "gem_path"_a = QString_To_Py_Path(gemPath),
  608. "external_subdir_path"_a = pybind11::none(),
  609. "template_path"_a = pybind11::none(),
  610. "restricted_path"_a = pybind11::none(),
  611. "repo_uri"_a = pybind11::none(),
  612. "default_engines_folder"_a = pybind11::none(),
  613. "default_projects_folder"_a = pybind11::none(),
  614. "default_gems_folder"_a = pybind11::none(),
  615. "default_templates_folder"_a = pybind11::none(),
  616. "default_restricted_folder"_a = pybind11::none(),
  617. "default_third_party_folder"_a = pybind11::none(),
  618. "external_subdir_engine_path"_a = pybind11::none(),
  619. "external_subdir_project_path"_a = externalProjectPath,
  620. "external_subdir_gem_path"_a = pybind11::none(),
  621. "remove"_a = remove
  622. );
  623. // Returns an exit code so boolify it then invert result
  624. registrationResult = !pythonRegistrationResult.cast<bool>();
  625. });
  626. if (!result.IsSuccess())
  627. {
  628. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  629. }
  630. else if (!registrationResult)
  631. {
  632. return AZ::Failure<AZStd::string>(AZStd::string::format(
  633. "Failed to %s gem path %s", remove ? "unregister" : "register", gemPath.toUtf8().constData()));
  634. }
  635. return AZ::Success();
  636. }
  637. AZ::Outcome<void, AZStd::string> PythonBindings::RegisterGem(const QString& gemPath, const QString& projectPath)
  638. {
  639. return GemRegistration(gemPath, projectPath);
  640. }
  641. AZ::Outcome<void, AZStd::string> PythonBindings::UnregisterGem(const QString& gemPath, const QString& projectPath)
  642. {
  643. return GemRegistration(gemPath, projectPath, /*remove*/true);
  644. }
  645. bool PythonBindings::AddProject(const QString& path)
  646. {
  647. bool registrationResult = false;
  648. bool result = ExecuteWithLock(
  649. [&]
  650. {
  651. auto projectPath = QString_To_Py_Path(path);
  652. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  653. // Returns an exit code so boolify it then invert result
  654. registrationResult = !pythonRegistrationResult.cast<bool>();
  655. });
  656. return result && registrationResult;
  657. }
  658. bool PythonBindings::RemoveProject(const QString& path)
  659. {
  660. using namespace pybind11::literals;
  661. bool registrationResult = false;
  662. bool result = ExecuteWithLock(
  663. [&]
  664. {
  665. auto pythonRegistrationResult = m_register.attr("register")(
  666. "engine_path"_a = pybind11::none(),
  667. "project_path"_a = QString_To_Py_Path(path),
  668. "gem_path"_a = pybind11::none(),
  669. "external_subdir_path"_a = pybind11::none(),
  670. "template_path"_a = pybind11::none(),
  671. "restricted_path"_a = pybind11::none(),
  672. "repo_uri"_a = pybind11::none(),
  673. "default_engines_folder"_a = pybind11::none(),
  674. "default_projects_folder"_a = pybind11::none(),
  675. "default_gems_folder"_a = pybind11::none(),
  676. "default_templates_folder"_a = pybind11::none(),
  677. "default_restricted_folder"_a = pybind11::none(),
  678. "default_third_party_folder"_a = pybind11::none(),
  679. "external_subdir_engine_path"_a = pybind11::none(),
  680. "external_subdir_project_path"_a = pybind11::none(),
  681. "external_subdir_gem_path"_a = pybind11::none(),
  682. "remove"_a = true,
  683. "force"_a = false
  684. );
  685. // Returns an exit code so boolify it then invert result
  686. registrationResult = !pythonRegistrationResult.cast<bool>();
  687. });
  688. return result && registrationResult;
  689. }
  690. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo, bool registerProject)
  691. {
  692. using namespace pybind11::literals;
  693. ProjectInfo createdProjectInfo;
  694. bool result = ExecuteWithLock([&] {
  695. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  696. auto createProjectResult = m_engineTemplate.attr("create_project")(
  697. "project_path"_a = projectPath,
  698. "project_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  699. "template_path"_a = QString_To_Py_Path(projectTemplatePath),
  700. "no_register"_a = !registerProject
  701. );
  702. if (createProjectResult.cast<int>() == 0)
  703. {
  704. createdProjectInfo = ProjectInfoFromPath(projectPath);
  705. }
  706. });
  707. if (!result || !createdProjectInfo.IsValid())
  708. {
  709. return AZ::Failure();
  710. }
  711. else
  712. {
  713. return AZ::Success(AZStd::move(createdProjectInfo));
  714. }
  715. }
  716. AZ::Outcome<GemInfo> PythonBindings::CreateGem(const QString& templatePath, const GemInfo& gemInfo, bool registerGem/*=true*/)
  717. {
  718. using namespace pybind11::literals;
  719. GemInfo gemInfoResult;
  720. bool result = ExecuteWithLock(
  721. [&]
  722. {
  723. auto gemPath = QString_To_Py_Path(gemInfo.m_path);
  724. auto createGemResult = m_engineTemplate.attr("create_gem")(
  725. "gem_path"_a = gemPath,
  726. "template_path"_a = QString_To_Py_Path(templatePath),
  727. "gem_name"_a = QString_To_Py_String(gemInfo.m_name),
  728. "display_name"_a = QString_To_Py_String(gemInfo.m_displayName),
  729. "summary"_a = QString_To_Py_String(gemInfo.m_summary),
  730. "requirements"_a = QString_To_Py_String(gemInfo.m_requirement),
  731. "license"_a = QString_To_Py_String(gemInfo.m_licenseText),
  732. "license_url"_a = QString_To_Py_String(gemInfo.m_licenseLink),
  733. "origin"_a = QString_To_Py_String(gemInfo.m_origin),
  734. "origin_url"_a = QString_To_Py_String(gemInfo.m_originURL),
  735. "user_tags"_a = QString_To_Py_String(gemInfo.m_features.join(",")),
  736. "icon_path"_a = QString_To_Py_Path(gemInfo.m_iconPath),
  737. "documentation_url"_a = QString_To_Py_String(gemInfo.m_documentationLink),
  738. "repo_uri"_a = QString_To_Py_String(gemInfo.m_repoUri),
  739. "no_register"_a = !registerGem)
  740. ;
  741. if (createGemResult.cast<int>() == 0)
  742. {
  743. gemInfoResult = GemInfoFromPath(gemPath, pybind11::none());
  744. }
  745. });
  746. if (!result || !gemInfoResult.IsValid())
  747. {
  748. return AZ::Failure();
  749. }
  750. else
  751. {
  752. //Make sure directory link is a normalized path that can be rendered in "View Directory" dialog
  753. gemInfoResult.m_directoryLink = QDir::cleanPath(gemInfoResult.m_directoryLink);
  754. return AZ::Success(AZStd::move(gemInfoResult));
  755. }
  756. }
  757. AZ::Outcome<GemInfo> PythonBindings::EditGem(const GemInfo& oldGemInfo, const GemInfo& newGemInfo)
  758. {
  759. using namespace pybind11::literals;
  760. QStringList newList;
  761. for(auto feature : newGemInfo.m_features)
  762. {
  763. if(!oldGemInfo.m_features.contains(feature))
  764. {
  765. //this must have been added by the user
  766. newList << feature;
  767. }
  768. }
  769. QStringList removeList;
  770. for (auto feature : oldGemInfo.m_features)
  771. {
  772. if(!newGemInfo.m_features.contains(feature))
  773. {
  774. //this must have been removed by the user
  775. removeList << feature;
  776. }
  777. }
  778. GemInfo gemInfoResult;
  779. bool result = ExecuteWithLock(
  780. [&]
  781. {
  782. auto gemPath = QString_To_Py_Path(oldGemInfo.m_path);
  783. auto editGemResult = m_gemProperties.attr("edit_gem_props")(
  784. "gem_path"_a = gemPath,
  785. "gem_name"_a = QString_To_Py_String(oldGemInfo.m_name),
  786. "new_name"_a = QString_To_Py_String(newGemInfo.m_name),
  787. "new_display"_a = QString_To_Py_String(newGemInfo.m_displayName),
  788. "new_origin"_a = QString_To_Py_String(newGemInfo.m_origin),
  789. "new_type"_a = pybind11::none(), //For the Project manager, it does not make sense to change the type of a gem once it's created
  790. "new_summary"_a = QString_To_Py_String(newGemInfo.m_summary),
  791. "new_icon"_a = QString_To_Py_String(newGemInfo.m_iconPath),
  792. "new_requirements"_a = QString_To_Py_String(newGemInfo.m_requirement),
  793. "new_documentation_url"_a = QString_To_Py_String(newGemInfo.m_documentationLink),
  794. "new_license"_a = QString_To_Py_String(newGemInfo.m_licenseText),
  795. "new_license_url"_a = QString_To_Py_String(newGemInfo.m_licenseLink),
  796. "new_tags"_a = QString_To_Py_String(newList.join(" ")), //the python code seems to interpret these lists as space separated
  797. "remove_tags"_a = QString_To_Py_String(removeList.join(" ")),
  798. "replace_tags"_a = pybind11::none())
  799. ;
  800. if (editGemResult.cast<int>() == 0)
  801. {
  802. gemInfoResult = GemInfoFromPath(gemPath, pybind11::none());
  803. }
  804. });
  805. if(!result || !gemInfoResult.IsValid())
  806. {
  807. return AZ::Failure();
  808. }
  809. else
  810. {
  811. //Make sure directory link is a normalized path that can be rendered in "View Directory" dialog
  812. gemInfoResult.m_directoryLink = QDir::cleanPath(gemInfoResult.m_directoryLink);
  813. return AZ::Success(AZStd::move(gemInfoResult));
  814. }
  815. }
  816. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  817. {
  818. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  819. if (projectInfo.IsValid())
  820. {
  821. return AZ::Success(AZStd::move(projectInfo));
  822. }
  823. else
  824. {
  825. return AZ::Failure();
  826. }
  827. }
  828. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  829. {
  830. GemInfo gemInfo;
  831. gemInfo.m_path = Py_To_String(path);
  832. gemInfo.m_directoryLink = gemInfo.m_path;
  833. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  834. if (pybind11::isinstance<pybind11::dict>(data))
  835. {
  836. try
  837. {
  838. // required
  839. gemInfo.m_name = Py_To_String(data["gem_name"]);
  840. // optional
  841. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  842. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  843. gemInfo.m_version = Py_To_String_Optional(data, "version", gemInfo.m_version);
  844. gemInfo.m_lastUpdatedDate = Py_To_String_Optional(data, "last_updated", gemInfo.m_lastUpdatedDate);
  845. gemInfo.m_binarySizeInKB = Py_To_Int_Optional(data, "binary_size", gemInfo.m_binarySizeInKB);
  846. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  847. gemInfo.m_origin = Py_To_String_Optional(data, "origin", "");
  848. gemInfo.m_originURL = Py_To_String_Optional(data, "origin_url", "");
  849. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  850. gemInfo.m_iconPath = Py_To_String_Optional(data, "icon_path", "preview.png");
  851. gemInfo.m_licenseText = Py_To_String_Optional(data, "license", "Unspecified License");
  852. gemInfo.m_licenseLink = Py_To_String_Optional(data, "license_url", "");
  853. gemInfo.m_repoUri = Py_To_String_Optional(data, "repo_uri", "");
  854. if (gemInfo.m_origin.contains("Open 3D Engine"))
  855. {
  856. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEngine;
  857. }
  858. else if (data.contains("origin"))
  859. {
  860. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Remote;
  861. }
  862. // If no origin was provided this cannot be remote and would be specified if O3DE so it should be local
  863. else
  864. {
  865. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  866. }
  867. // As long Base Open3DEngine gems are installed before first startup non-remote gems will be downloaded
  868. if (gemInfo.m_gemOrigin != GemInfo::GemOrigin::Remote)
  869. {
  870. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  871. }
  872. if (data.contains("user_tags"))
  873. {
  874. for (auto tag : data["user_tags"])
  875. {
  876. gemInfo.m_features.push_back(Py_To_String(tag));
  877. }
  878. }
  879. if (data.contains("dependencies"))
  880. {
  881. for (auto dependency : data["dependencies"])
  882. {
  883. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  884. }
  885. }
  886. QString gemType = Py_To_String_Optional(data, "type", "");
  887. if (gemType == "Asset")
  888. {
  889. gemInfo.m_types |= GemInfo::Type::Asset;
  890. }
  891. if (gemType == "Code")
  892. {
  893. gemInfo.m_types |= GemInfo::Type::Code;
  894. }
  895. if (gemType == "Tool")
  896. {
  897. gemInfo.m_types |= GemInfo::Type::Tool;
  898. }
  899. }
  900. catch ([[maybe_unused]] const std::exception& e)
  901. {
  902. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  903. }
  904. }
  905. return gemInfo;
  906. }
  907. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  908. {
  909. ProjectInfo projectInfo;
  910. projectInfo.m_path = Py_To_String(path);
  911. projectInfo.m_needsBuild = false;
  912. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  913. if (pybind11::isinstance<pybind11::dict>(projectData))
  914. {
  915. try
  916. {
  917. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  918. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  919. projectInfo.m_id = Py_To_String_Optional(projectData, "project_id", projectInfo.m_id);
  920. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  921. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  922. projectInfo.m_requirements = Py_To_String_Optional(projectData, "requirements", projectInfo.m_requirements);
  923. projectInfo.m_license = Py_To_String_Optional(projectData, "license", projectInfo.m_license);
  924. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  925. projectInfo.m_engineName = Py_To_String_Optional(projectData, "engine", projectInfo.m_engineName);
  926. if (projectData.contains("user_tags"))
  927. {
  928. for (auto tag : projectData["user_tags"])
  929. {
  930. projectInfo.m_userTags.append(Py_To_String(tag));
  931. }
  932. }
  933. auto enginePathResult = m_manifest.attr("get_project_engine_path")(path);
  934. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  935. {
  936. // request a posix path so it looks like what is in o3de_manifest.json
  937. projectInfo.m_enginePath = Py_To_String(enginePathResult.attr("as_posix")());
  938. }
  939. }
  940. catch ([[maybe_unused]] const std::exception& e)
  941. {
  942. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  943. }
  944. }
  945. return projectInfo;
  946. }
  947. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  948. {
  949. QVector<ProjectInfo> projects;
  950. bool result = ExecuteWithLock([&] {
  951. // external projects
  952. for (auto path : m_manifest.attr("get_manifest_projects")())
  953. {
  954. projects.push_back(ProjectInfoFromPath(path));
  955. }
  956. // projects from the engine
  957. for (auto path : m_manifest.attr("get_engine_projects")())
  958. {
  959. projects.push_back(ProjectInfoFromPath(path));
  960. }
  961. });
  962. if (!result)
  963. {
  964. return AZ::Failure();
  965. }
  966. else
  967. {
  968. return AZ::Success(AZStd::move(projects));
  969. }
  970. }
  971. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForRepo(const QString& repoUri)
  972. {
  973. QVector<ProjectInfo> projects;
  974. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  975. [&]
  976. {
  977. auto pyUri = QString_To_Py_String(repoUri);
  978. auto projectPaths = m_repo.attr("get_project_json_paths_from_cached_repo")(pyUri);
  979. if (pybind11::isinstance<pybind11::set>(projectPaths))
  980. {
  981. for (auto path : projectPaths)
  982. {
  983. ProjectInfo projectInfo = ProjectInfoFromPath(path);
  984. projectInfo.m_remote = true;
  985. projects.push_back(projectInfo);
  986. }
  987. }
  988. });
  989. if (!result.IsSuccess())
  990. {
  991. return AZ::Failure(result.GetError());
  992. }
  993. return AZ::Success(AZStd::move(projects));
  994. }
  995. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForAllRepos()
  996. {
  997. QVector<ProjectInfo> projectInfos;
  998. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  999. [&]
  1000. {
  1001. auto projectPaths = m_repo.attr("get_project_json_paths_from_all_cached_repos")();
  1002. if (pybind11::isinstance<pybind11::set>(projectPaths))
  1003. {
  1004. for (auto path : projectPaths)
  1005. {
  1006. ProjectInfo projectInfo = ProjectInfoFromPath(path);
  1007. projectInfo.m_remote = true;
  1008. projectInfos.push_back(projectInfo);
  1009. }
  1010. }
  1011. });
  1012. if (!result.IsSuccess())
  1013. {
  1014. return AZ::Failure(result.GetError());
  1015. }
  1016. return AZ::Success(AZStd::move(projectInfos));
  1017. }
  1018. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  1019. {
  1020. return ExecuteWithLockErrorHandling([&]
  1021. {
  1022. m_enableGemProject.attr("enable_gem_in_project")(
  1023. pybind11::none(), // gem name not needed as path is provided
  1024. QString_To_Py_Path(gemPath),
  1025. pybind11::none(), // project name not needed as path is provided
  1026. QString_To_Py_Path(projectPath)
  1027. );
  1028. });
  1029. }
  1030. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  1031. {
  1032. return ExecuteWithLockErrorHandling([&]
  1033. {
  1034. m_disableGemProject.attr("disable_gem_in_project")(
  1035. pybind11::none(), // gem name not needed as path is provided
  1036. QString_To_Py_Path(gemPath),
  1037. pybind11::none(), // project name not needed as path is provided
  1038. QString_To_Py_Path(projectPath)
  1039. );
  1040. });
  1041. }
  1042. bool PythonBindings::RemoveInvalidProjects()
  1043. {
  1044. bool removalResult = false;
  1045. bool result = ExecuteWithLock(
  1046. [&]
  1047. {
  1048. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  1049. // Returns an exit code so boolify it then invert result
  1050. removalResult = !pythonRemovalResult.cast<bool>();
  1051. });
  1052. return result && removalResult;
  1053. }
  1054. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  1055. {
  1056. bool updateProjectSucceeded = false;
  1057. auto result = ExecuteWithLockErrorHandling([&]
  1058. {
  1059. using namespace pybind11::literals;
  1060. std::list<std::string> newTags;
  1061. for (const auto& i : projectInfo.m_userTags)
  1062. {
  1063. newTags.push_back(i.toStdString());
  1064. }
  1065. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  1066. "proj_path"_a = QString_To_Py_Path(projectInfo.m_path),
  1067. "new_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  1068. "new_id"_a = QString_To_Py_String(projectInfo.m_id),
  1069. "new_origin"_a = QString_To_Py_String(projectInfo.m_origin),
  1070. "new_display"_a = QString_To_Py_String(projectInfo.m_displayName),
  1071. "new_summary"_a = QString_To_Py_String(projectInfo.m_summary),
  1072. "new_icon"_a = QString_To_Py_String(projectInfo.m_iconPath),
  1073. "replace_tags"_a = pybind11::list(pybind11::cast(newTags)),
  1074. "new_engine_name"_a = QString_To_Py_String(projectInfo.m_engineName)
  1075. );
  1076. updateProjectSucceeded = (editResult.cast<int>() == 0);
  1077. });
  1078. if (!result.IsSuccess())
  1079. {
  1080. return result;
  1081. }
  1082. else if (!updateProjectSucceeded)
  1083. {
  1084. return AZ::Failure<AZStd::string>("Failed to update project.");
  1085. }
  1086. return AZ::Success();
  1087. }
  1088. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path) const
  1089. {
  1090. ProjectTemplateInfo templateInfo(TemplateInfoFromPath(path));
  1091. if (templateInfo.IsValid())
  1092. {
  1093. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  1094. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  1095. if (enabledGemNames)
  1096. {
  1097. for (auto gem : enabledGemNames.GetValue())
  1098. {
  1099. // Exclude the template ${Name} placeholder for the list of included gems
  1100. // That Gem gets created with the project
  1101. if (!gem.contains("${Name}"))
  1102. {
  1103. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  1104. }
  1105. }
  1106. }
  1107. }
  1108. return templateInfo;
  1109. }
  1110. TemplateInfo PythonBindings::TemplateInfoFromPath(pybind11::handle path) const
  1111. {
  1112. TemplateInfo templateInfo;
  1113. templateInfo.m_path = Py_To_String(path);
  1114. using namespace pybind11::literals;
  1115. // no project path is needed when a template path is provided
  1116. auto data = m_manifest.attr("get_template_json_data")("template_path"_a = path);
  1117. if (pybind11::isinstance<pybind11::dict>(data))
  1118. {
  1119. try
  1120. {
  1121. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  1122. templateInfo.m_name = Py_To_String(data["template_name"]);
  1123. templateInfo.m_summary = Py_To_String(data["summary"]);
  1124. if (data.contains("canonical_tags"))
  1125. {
  1126. for (auto tag : data["canonical_tags"])
  1127. {
  1128. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  1129. }
  1130. }
  1131. if (data.contains("user_tags"))
  1132. {
  1133. for (auto tag : data["user_tags"])
  1134. {
  1135. templateInfo.m_userTags.push_back(Py_To_String(tag));
  1136. }
  1137. }
  1138. templateInfo.m_requirements = Py_To_String_Optional(data, "requirements", "");
  1139. templateInfo.m_license = Py_To_String_Optional(data, "license", "");
  1140. }
  1141. catch ([[maybe_unused]] const std::exception& e)
  1142. {
  1143. AZ_Warning("PythonBindings", false, "Failed to get TemplateInfo for %s", Py_To_String(path));
  1144. }
  1145. }
  1146. return templateInfo;
  1147. }
  1148. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates()
  1149. {
  1150. QVector<ProjectTemplateInfo> templates;
  1151. bool result = ExecuteWithLock([&] {
  1152. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  1153. {
  1154. templates.push_back(ProjectTemplateInfoFromPath(path));
  1155. }
  1156. });
  1157. if (!result)
  1158. {
  1159. return AZ::Failure();
  1160. }
  1161. else
  1162. {
  1163. return AZ::Success(AZStd::move(templates));
  1164. }
  1165. }
  1166. AZ::Outcome<QVector<TemplateInfo>> PythonBindings::GetGemTemplates()
  1167. {
  1168. QVector<TemplateInfo> templates;
  1169. bool result = ExecuteWithLock(
  1170. [&]
  1171. {
  1172. for (auto path : m_manifest.attr("get_templates_for_gem_creation")())
  1173. {
  1174. templates.push_back(TemplateInfoFromPath(path));
  1175. }
  1176. });
  1177. if (!result)
  1178. {
  1179. return AZ::Failure();
  1180. }
  1181. else
  1182. {
  1183. return AZ::Success(AZStd::move(templates));
  1184. }
  1185. }
  1186. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplatesForRepo(const QString& repoUri) const
  1187. {
  1188. QVector<ProjectTemplateInfo> templates;
  1189. bool result = ExecuteWithLock(
  1190. [&]
  1191. {
  1192. using namespace pybind11::literals;
  1193. auto templatePaths = m_repo.attr("get_template_json_paths_from_cached_repo")(
  1194. "repo_uri"_a = QString_To_Py_String(repoUri)
  1195. );
  1196. if (pybind11::isinstance<pybind11::set>(templatePaths))
  1197. {
  1198. for (auto path : templatePaths)
  1199. {
  1200. ProjectTemplateInfo remoteTemplate = ProjectTemplateInfoFromPath(path);
  1201. remoteTemplate.m_isRemote = true;
  1202. templates.push_back(remoteTemplate);
  1203. }
  1204. }
  1205. });
  1206. if (!result)
  1207. {
  1208. return AZ::Failure();
  1209. }
  1210. else
  1211. {
  1212. return AZ::Success(AZStd::move(templates));
  1213. }
  1214. }
  1215. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplatesForAllRepos() const
  1216. {
  1217. QVector<ProjectTemplateInfo> templates;
  1218. bool result = ExecuteWithLock(
  1219. [&]
  1220. {
  1221. auto templatePaths = m_repo.attr("get_template_json_paths_from_all_cached_repos")();
  1222. if (pybind11::isinstance<pybind11::set>(templatePaths))
  1223. {
  1224. for (auto path : templatePaths)
  1225. {
  1226. ProjectTemplateInfo remoteTemplate = ProjectTemplateInfoFromPath(path);
  1227. remoteTemplate.m_isRemote = true;
  1228. templates.push_back(remoteTemplate);
  1229. }
  1230. }
  1231. });
  1232. if (!result)
  1233. {
  1234. return AZ::Failure();
  1235. }
  1236. else
  1237. {
  1238. return AZ::Success(AZStd::move(templates));
  1239. }
  1240. }
  1241. AZ::Outcome<void, AZStd::string> PythonBindings::RefreshGemRepo(const QString& repoUri)
  1242. {
  1243. bool refreshResult = false;
  1244. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1245. [&]
  1246. {
  1247. auto pyUri = QString_To_Py_String(repoUri);
  1248. auto pythonRefreshResult = m_repo.attr("refresh_repo")(pyUri);
  1249. // Returns an exit code so boolify it then invert result
  1250. refreshResult = !pythonRefreshResult.cast<bool>();
  1251. });
  1252. if (!result.IsSuccess())
  1253. {
  1254. return result;
  1255. }
  1256. else if (!refreshResult)
  1257. {
  1258. return AZ::Failure<AZStd::string>("Failed to refresh repo.");
  1259. }
  1260. return AZ::Success();
  1261. }
  1262. bool PythonBindings::RefreshAllGemRepos()
  1263. {
  1264. bool refreshResult = false;
  1265. bool result = ExecuteWithLock(
  1266. [&]
  1267. {
  1268. auto pythonRefreshResult = m_repo.attr("refresh_repos")();
  1269. // Returns an exit code so boolify it then invert result
  1270. refreshResult = !pythonRefreshResult.cast<bool>();
  1271. });
  1272. return result && refreshResult;
  1273. }
  1274. IPythonBindings::DetailedOutcome PythonBindings::AddGemRepo(const QString& repoUri)
  1275. {
  1276. bool registrationResult = false;
  1277. bool result = ExecuteWithLock(
  1278. [&]
  1279. {
  1280. auto pyUri = QString_To_Py_String(repoUri);
  1281. auto pythonRegistrationResult = m_register.attr("register")(
  1282. pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pyUri);
  1283. // Returns an exit code so boolify it then invert result
  1284. registrationResult = !pythonRegistrationResult.cast<bool>();
  1285. });
  1286. if (!result || !registrationResult)
  1287. {
  1288. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1289. }
  1290. return AZ::Success();
  1291. }
  1292. bool PythonBindings::RemoveGemRepo(const QString& repoUri)
  1293. {
  1294. bool registrationResult = false;
  1295. bool result = ExecuteWithLock(
  1296. [&]
  1297. {
  1298. using namespace pybind11::literals;
  1299. auto pythonRegistrationResult = m_register.attr("register")(
  1300. "engine_path"_a = pybind11::none(),
  1301. "project_path"_a = pybind11::none(),
  1302. "gem_path"_a = pybind11::none(),
  1303. "external_subdir_path"_a = pybind11::none(),
  1304. "template_path"_a = pybind11::none(),
  1305. "restricted_path"_a = pybind11::none(),
  1306. "repo_uri"_a = QString_To_Py_String(repoUri),
  1307. "default_engines_folder"_a = pybind11::none(),
  1308. "default_projects_folder"_a = pybind11::none(),
  1309. "default_gems_folder"_a = pybind11::none(),
  1310. "default_templates_folder"_a = pybind11::none(),
  1311. "default_restricted_folder"_a = pybind11::none(),
  1312. "default_third_party_folder"_a = pybind11::none(),
  1313. "external_subdir_engine_path"_a = pybind11::none(),
  1314. "external_subdir_project_path"_a = pybind11::none(),
  1315. "external_subdir_gem_path"_a = pybind11::none(),
  1316. "remove"_a = true,
  1317. "force"_a = false
  1318. );
  1319. // Returns an exit code so boolify it then invert result
  1320. registrationResult = !pythonRegistrationResult.cast<bool>();
  1321. });
  1322. return result && registrationResult;
  1323. }
  1324. GemRepoInfo PythonBindings::GetGemRepoInfo(pybind11::handle repoUri)
  1325. {
  1326. GemRepoInfo gemRepoInfo;
  1327. gemRepoInfo.m_repoUri = Py_To_String(repoUri);
  1328. auto data = m_manifest.attr("get_repo_json_data")(repoUri);
  1329. if (pybind11::isinstance<pybind11::dict>(data))
  1330. {
  1331. try
  1332. {
  1333. // required
  1334. gemRepoInfo.m_name = Py_To_String(data["repo_name"]);
  1335. gemRepoInfo.m_origin = Py_To_String(data["origin"]);
  1336. // optional
  1337. gemRepoInfo.m_summary = Py_To_String_Optional(data, "summary", "No summary provided.");
  1338. gemRepoInfo.m_additionalInfo = Py_To_String_Optional(data, "additional_info", "");
  1339. auto repoPath = m_manifest.attr("get_repo_path")(repoUri);
  1340. gemRepoInfo.m_path = gemRepoInfo.m_directoryLink = Py_To_String(repoPath);
  1341. QString lastUpdated = Py_To_String_Optional(data, "last_updated", "");
  1342. gemRepoInfo.m_lastUpdated = QDateTime::fromString(lastUpdated, RepoTimeFormat);
  1343. if (data.contains("enabled"))
  1344. {
  1345. gemRepoInfo.m_isEnabled = data["enabled"].cast<bool>();
  1346. }
  1347. else
  1348. {
  1349. gemRepoInfo.m_isEnabled = false;
  1350. }
  1351. if (data.contains("gems"))
  1352. {
  1353. for (auto gemPath : data["gems"])
  1354. {
  1355. gemRepoInfo.m_includedGemUris.push_back(Py_To_String(gemPath));
  1356. }
  1357. }
  1358. }
  1359. catch ([[maybe_unused]] const std::exception& e)
  1360. {
  1361. AZ_Warning("PythonBindings", false, "Failed to get GemRepoInfo for repo %s", Py_To_String(repoUri));
  1362. }
  1363. }
  1364. return gemRepoInfo;
  1365. }
  1366. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  1367. {
  1368. QVector<GemRepoInfo> gemRepos;
  1369. auto result = ExecuteWithLockErrorHandling(
  1370. [&]
  1371. {
  1372. for (auto repoUri : m_manifest.attr("get_manifest_repos")())
  1373. {
  1374. gemRepos.push_back(GetGemRepoInfo(repoUri));
  1375. }
  1376. });
  1377. if (!result.IsSuccess())
  1378. {
  1379. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  1380. }
  1381. AZStd::sort(gemRepos.begin(), gemRepos.end());
  1382. return AZ::Success(AZStd::move(gemRepos));
  1383. }
  1384. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForRepo(const QString& repoUri)
  1385. {
  1386. QVector<GemInfo> gemInfos;
  1387. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1388. [&]
  1389. {
  1390. auto pyUri = QString_To_Py_String(repoUri);
  1391. auto gemPaths = m_repo.attr("get_gem_json_paths_from_cached_repo")(pyUri);
  1392. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1393. {
  1394. for (auto path : gemPaths)
  1395. {
  1396. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1397. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1398. gemInfos.push_back(gemInfo);
  1399. }
  1400. }
  1401. });
  1402. if (!result.IsSuccess())
  1403. {
  1404. return AZ::Failure(result.GetError());
  1405. }
  1406. return AZ::Success(AZStd::move(gemInfos));
  1407. }
  1408. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForAllRepos()
  1409. {
  1410. QVector<GemInfo> gemInfos;
  1411. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1412. [&]
  1413. {
  1414. auto gemPaths = m_repo.attr("get_gem_json_paths_from_all_cached_repos")();
  1415. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1416. {
  1417. for (auto path : gemPaths)
  1418. {
  1419. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1420. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1421. gemInfos.push_back(gemInfo);
  1422. }
  1423. }
  1424. });
  1425. if (!result.IsSuccess())
  1426. {
  1427. return AZ::Failure(result.GetError());
  1428. }
  1429. return AZ::Success(AZStd::move(gemInfos));
  1430. }
  1431. IPythonBindings::DetailedOutcome PythonBindings::DownloadGem(
  1432. const QString& gemName, const QString& path, std::function<void(int, int)> gemProgressCallback, bool force)
  1433. {
  1434. // This process is currently limited to download a single object at a time.
  1435. bool downloadSucceeded = false;
  1436. m_requestCancelDownload = false;
  1437. auto result = ExecuteWithLockErrorHandling(
  1438. [&]
  1439. {
  1440. auto downloadResult = m_download.attr("download_gem")(
  1441. QString_To_Py_String(gemName), // gem name
  1442. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1443. false, // skip auto register
  1444. force, // force overwrite
  1445. pybind11::cpp_function(
  1446. [this, gemProgressCallback](int bytesDownloaded, int totalBytes)
  1447. {
  1448. gemProgressCallback(bytesDownloaded, totalBytes);
  1449. return m_requestCancelDownload;
  1450. }) // Callback for download progress and cancelling
  1451. );
  1452. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1453. });
  1454. if (!result.IsSuccess())
  1455. {
  1456. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1457. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1458. }
  1459. else if (!downloadSucceeded)
  1460. {
  1461. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1462. }
  1463. return AZ::Success();
  1464. }
  1465. IPythonBindings::DetailedOutcome PythonBindings::DownloadProject(
  1466. const QString& projectName, const QString& path, std::function<void(int, int)> projectProgressCallback, bool force)
  1467. {
  1468. // This process is currently limited to download a single object at a time.
  1469. bool downloadSucceeded = false;
  1470. m_requestCancelDownload = false;
  1471. auto result = ExecuteWithLockErrorHandling(
  1472. [&]
  1473. {
  1474. auto downloadResult = m_download.attr("download_project")(
  1475. QString_To_Py_String(projectName), // gem name
  1476. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1477. false, // skip auto register
  1478. force, // force overwrite
  1479. pybind11::cpp_function(
  1480. [this, projectProgressCallback](int bytesDownloaded, int totalBytes)
  1481. {
  1482. projectProgressCallback(bytesDownloaded, totalBytes);
  1483. return m_requestCancelDownload;
  1484. }) // Callback for download progress and cancelling
  1485. );
  1486. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1487. });
  1488. if (!result.IsSuccess())
  1489. {
  1490. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1491. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1492. }
  1493. else if (!downloadSucceeded)
  1494. {
  1495. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1496. }
  1497. return AZ::Success();
  1498. }
  1499. IPythonBindings::DetailedOutcome PythonBindings::DownloadTemplate(
  1500. const QString& templateName, const QString& path, std::function<void(int, int)> templateProgressCallback, bool force)
  1501. {
  1502. // This process is currently limited to download a single object at a time.
  1503. bool downloadSucceeded = false;
  1504. m_requestCancelDownload = false;
  1505. auto result = ExecuteWithLockErrorHandling(
  1506. [&]
  1507. {
  1508. auto downloadResult = m_download.attr("download_template")(
  1509. QString_To_Py_String(templateName), // gem name
  1510. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1511. false, // skip auto register
  1512. force, // force overwrite
  1513. pybind11::cpp_function(
  1514. [this, templateProgressCallback](int bytesDownloaded, int totalBytes)
  1515. {
  1516. templateProgressCallback(bytesDownloaded, totalBytes);
  1517. return m_requestCancelDownload;
  1518. }) // Callback for download progress and cancelling
  1519. );
  1520. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1521. });
  1522. if (!result.IsSuccess())
  1523. {
  1524. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1525. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1526. }
  1527. else if (!downloadSucceeded)
  1528. {
  1529. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1530. }
  1531. return AZ::Success();
  1532. }
  1533. void PythonBindings::CancelDownload()
  1534. {
  1535. m_requestCancelDownload = true;
  1536. }
  1537. bool PythonBindings::IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated)
  1538. {
  1539. bool updateAvaliableResult = false;
  1540. bool result = ExecuteWithLock(
  1541. [&]
  1542. {
  1543. auto pyGemName = QString_To_Py_String(gemName);
  1544. auto pyLastUpdated = QString_To_Py_String(lastUpdated);
  1545. auto pythonUpdateAvaliableResult = m_download.attr("is_o3de_gem_update_available")(pyGemName, pyLastUpdated);
  1546. updateAvaliableResult = pythonUpdateAvaliableResult.cast<bool>();
  1547. });
  1548. return result && updateAvaliableResult;
  1549. }
  1550. IPythonBindings::ErrorPair PythonBindings::GetErrorPair()
  1551. {
  1552. if (const size_t errorSize = m_pythonErrorStrings.size())
  1553. {
  1554. AZStd::string detailedString =
  1555. errorSize == 1 ? "" : AZStd::accumulate(m_pythonErrorStrings.begin(), m_pythonErrorStrings.end(), AZStd::string(""));
  1556. return IPythonBindings::ErrorPair(m_pythonErrorStrings.front(), detailedString);
  1557. }
  1558. // If no error was found
  1559. else
  1560. {
  1561. return IPythonBindings::ErrorPair(AZStd::string("Unknown Python Bindings Error"), AZStd::string(""));
  1562. }
  1563. }
  1564. void PythonBindings::AddErrorString(AZStd::string errorString)
  1565. {
  1566. m_pythonErrorStrings.push_back(errorString);
  1567. }
  1568. } // namespace O3DE::ProjectManager