PythonBindings.cpp 70 KB

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