PythonBindings.cpp 69 KB

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