PythonBindings.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  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_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<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath) const
  586. {
  587. // Retrieve the path to the cmake file that lists the enabled gems.
  588. pybind11::str enabledGemsFilename;
  589. auto result = ExecuteWithLockErrorHandling([&]
  590. {
  591. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  592. pybind11::none(), // project_name
  593. QString_To_Py_Path(projectPath)); // project_path
  594. });
  595. if (!result.IsSuccess())
  596. {
  597. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  598. }
  599. // Retrieve the actual list of names from the cmake file.
  600. QVector<AZStd::string> gemNames;
  601. result = ExecuteWithLockErrorHandling([&]
  602. {
  603. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  604. for (auto gemName : pyGemNames)
  605. {
  606. gemNames.push_back(Py_To_String(gemName));
  607. }
  608. });
  609. if (!result.IsSuccess())
  610. {
  611. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  612. }
  613. return AZ::Success(AZStd::move(gemNames));
  614. }
  615. AZ::Outcome<void, AZStd::string> PythonBindings::GemRegistration(const QString& gemPath, const QString& projectPath, bool remove)
  616. {
  617. using namespace pybind11::literals;
  618. bool registrationResult = false;
  619. auto result = ExecuteWithLockErrorHandling(
  620. [&]
  621. {
  622. auto externalProjectPath = projectPath.isEmpty() ? pybind11::none() : QString_To_Py_Path(projectPath);
  623. auto pythonRegistrationResult = m_register.attr("register")(
  624. "engine_path"_a = pybind11::none(),
  625. "project_path"_a = pybind11::none(),
  626. "gem_path"_a = QString_To_Py_Path(gemPath),
  627. "external_subdir_path"_a = pybind11::none(),
  628. "template_path"_a = pybind11::none(),
  629. "restricted_path"_a = pybind11::none(),
  630. "repo_uri"_a = pybind11::none(),
  631. "default_engines_folder"_a = pybind11::none(),
  632. "default_projects_folder"_a = pybind11::none(),
  633. "default_gems_folder"_a = pybind11::none(),
  634. "default_templates_folder"_a = pybind11::none(),
  635. "default_restricted_folder"_a = pybind11::none(),
  636. "default_third_party_folder"_a = pybind11::none(),
  637. "external_subdir_engine_path"_a = pybind11::none(),
  638. "external_subdir_project_path"_a = externalProjectPath,
  639. "external_subdir_gem_path"_a = pybind11::none(),
  640. "remove"_a = remove
  641. );
  642. // Returns an exit code so boolify it then invert result
  643. registrationResult = !pythonRegistrationResult.cast<bool>();
  644. });
  645. if (!result.IsSuccess())
  646. {
  647. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  648. }
  649. else if (!registrationResult)
  650. {
  651. return AZ::Failure<AZStd::string>(AZStd::string::format(
  652. "Failed to %s gem path %s", remove ? "unregister" : "register", gemPath.toUtf8().constData()));
  653. }
  654. return AZ::Success();
  655. }
  656. AZ::Outcome<void, AZStd::string> PythonBindings::RegisterGem(const QString& gemPath, const QString& projectPath)
  657. {
  658. return GemRegistration(gemPath, projectPath);
  659. }
  660. AZ::Outcome<void, AZStd::string> PythonBindings::UnregisterGem(const QString& gemPath, const QString& projectPath)
  661. {
  662. return GemRegistration(gemPath, projectPath, /*remove*/true);
  663. }
  664. bool PythonBindings::AddProject(const QString& path)
  665. {
  666. bool registrationResult = false;
  667. bool result = ExecuteWithLock(
  668. [&]
  669. {
  670. auto projectPath = QString_To_Py_Path(path);
  671. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  672. // Returns an exit code so boolify it then invert result
  673. registrationResult = !pythonRegistrationResult.cast<bool>();
  674. });
  675. return result && registrationResult;
  676. }
  677. bool PythonBindings::RemoveProject(const QString& path)
  678. {
  679. using namespace pybind11::literals;
  680. bool registrationResult = false;
  681. bool result = ExecuteWithLock(
  682. [&]
  683. {
  684. auto pythonRegistrationResult = m_register.attr("register")(
  685. "engine_path"_a = pybind11::none(),
  686. "project_path"_a = QString_To_Py_Path(path),
  687. "gem_path"_a = pybind11::none(),
  688. "external_subdir_path"_a = pybind11::none(),
  689. "template_path"_a = pybind11::none(),
  690. "restricted_path"_a = pybind11::none(),
  691. "repo_uri"_a = pybind11::none(),
  692. "default_engines_folder"_a = pybind11::none(),
  693. "default_projects_folder"_a = pybind11::none(),
  694. "default_gems_folder"_a = pybind11::none(),
  695. "default_templates_folder"_a = pybind11::none(),
  696. "default_restricted_folder"_a = pybind11::none(),
  697. "default_third_party_folder"_a = pybind11::none(),
  698. "external_subdir_engine_path"_a = pybind11::none(),
  699. "external_subdir_project_path"_a = pybind11::none(),
  700. "external_subdir_gem_path"_a = pybind11::none(),
  701. "remove"_a = true,
  702. "force"_a = false
  703. );
  704. // Returns an exit code so boolify it then invert result
  705. registrationResult = !pythonRegistrationResult.cast<bool>();
  706. });
  707. return result && registrationResult;
  708. }
  709. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo, bool registerProject)
  710. {
  711. using namespace pybind11::literals;
  712. ProjectInfo createdProjectInfo;
  713. bool result = ExecuteWithLock([&] {
  714. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  715. auto createProjectResult = m_engineTemplate.attr("create_project")(
  716. "project_path"_a = projectPath,
  717. "project_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  718. "template_path"_a = QString_To_Py_Path(projectTemplatePath),
  719. "no_register"_a = !registerProject
  720. );
  721. if (createProjectResult.cast<int>() == 0)
  722. {
  723. createdProjectInfo = ProjectInfoFromPath(projectPath);
  724. }
  725. });
  726. if (!result || !createdProjectInfo.IsValid())
  727. {
  728. return AZ::Failure();
  729. }
  730. else
  731. {
  732. return AZ::Success(AZStd::move(createdProjectInfo));
  733. }
  734. }
  735. AZ::Outcome<GemInfo> PythonBindings::CreateGem(const QString& templatePath, const GemInfo& gemInfo, bool registerGem/*=true*/)
  736. {
  737. using namespace pybind11::literals;
  738. GemInfo gemInfoResult;
  739. bool result = ExecuteWithLock(
  740. [&]
  741. {
  742. auto gemPath = QString_To_Py_Path(gemInfo.m_path);
  743. auto createGemResult = m_engineTemplate.attr("create_gem")(
  744. "gem_path"_a = gemPath,
  745. "template_path"_a = QString_To_Py_Path(templatePath),
  746. "gem_name"_a = QString_To_Py_String(gemInfo.m_name),
  747. "display_name"_a = QString_To_Py_String(gemInfo.m_displayName),
  748. "summary"_a = QString_To_Py_String(gemInfo.m_summary),
  749. "requirements"_a = QString_To_Py_String(gemInfo.m_requirement),
  750. "license"_a = QString_To_Py_String(gemInfo.m_licenseText),
  751. "license_url"_a = QString_To_Py_String(gemInfo.m_licenseLink),
  752. "origin"_a = QString_To_Py_String(gemInfo.m_origin),
  753. "origin_url"_a = QString_To_Py_String(gemInfo.m_originURL),
  754. "user_tags"_a = QString_To_Py_String(gemInfo.m_features.join(",")),
  755. "platforms"_a = QStringList_To_Py_List(gemInfo.GetPlatformsAsStringList()),
  756. "icon_path"_a = QString_To_Py_Path(gemInfo.m_iconPath),
  757. "documentation_url"_a = QString_To_Py_String(gemInfo.m_documentationLink),
  758. "repo_uri"_a = QString_To_Py_String(gemInfo.m_repoUri),
  759. "no_register"_a = !registerGem)
  760. ;
  761. if (createGemResult.cast<int>() == 0)
  762. {
  763. gemInfoResult = GemInfoFromPath(gemPath, pybind11::none());
  764. }
  765. });
  766. if (!result || !gemInfoResult.IsValid())
  767. {
  768. return AZ::Failure();
  769. }
  770. else
  771. {
  772. //Make sure directory link is a normalized path that can be rendered in "View Directory" dialog
  773. gemInfoResult.m_directoryLink = QDir::cleanPath(gemInfoResult.m_directoryLink);
  774. return AZ::Success(AZStd::move(gemInfoResult));
  775. }
  776. }
  777. AZ::Outcome<GemInfo> PythonBindings::EditGem(const QString& oldGemName, const GemInfo& newGemInfo)
  778. {
  779. using namespace pybind11::literals;
  780. GemInfo gemInfoResult;
  781. bool result = ExecuteWithLock(
  782. [&]
  783. {
  784. auto gemPath = QString_To_Py_Path(newGemInfo.m_path);
  785. auto editGemResult = m_gemProperties.attr("edit_gem_props")(
  786. "gem_path"_a = gemPath,
  787. "gem_name"_a = QString_To_Py_String(oldGemName),
  788. "new_name"_a = QString_To_Py_String(newGemInfo.m_name),
  789. "new_display"_a = QString_To_Py_String(newGemInfo.m_displayName),
  790. "new_origin"_a = QString_To_Py_String(newGemInfo.m_origin),
  791. "new_summary"_a = QString_To_Py_String(newGemInfo.m_summary),
  792. "new_icon"_a = QString_To_Py_String(newGemInfo.m_iconPath),
  793. "new_requirements"_a = QString_To_Py_String(newGemInfo.m_requirement),
  794. "new_documentation_url"_a = QString_To_Py_String(newGemInfo.m_documentationLink),
  795. "new_license"_a = QString_To_Py_String(newGemInfo.m_licenseText),
  796. "new_license_url"_a = QString_To_Py_String(newGemInfo.m_licenseLink),
  797. "new_repo_uri"_a = QString_To_Py_String(newGemInfo.m_repoUri),
  798. "replace_tags"_a = QStringList_To_Py_List(newGemInfo.m_features), //the python code seems to interpret these lists as space separated
  799. "replace_platforms"_a = QStringList_To_Py_List(newGemInfo.GetPlatformsAsStringList()))
  800. ;
  801. if (editGemResult.cast<int>() == 0)
  802. {
  803. gemInfoResult = GemInfoFromPath(gemPath, pybind11::none());
  804. }
  805. });
  806. if(!result || !gemInfoResult.IsValid())
  807. {
  808. return AZ::Failure();
  809. }
  810. else
  811. {
  812. //Make sure directory link is a normalized path that can be rendered in "View Directory" dialog
  813. gemInfoResult.m_directoryLink = QDir::cleanPath(gemInfoResult.m_directoryLink);
  814. return AZ::Success(AZStd::move(gemInfoResult));
  815. }
  816. }
  817. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  818. {
  819. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  820. if (projectInfo.IsValid())
  821. {
  822. return AZ::Success(AZStd::move(projectInfo));
  823. }
  824. else
  825. {
  826. return AZ::Failure();
  827. }
  828. }
  829. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  830. {
  831. GemInfo gemInfo;
  832. gemInfo.m_path = Py_To_String(path);
  833. gemInfo.m_directoryLink = gemInfo.m_path;
  834. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  835. if (pybind11::isinstance<pybind11::dict>(data))
  836. {
  837. try
  838. {
  839. // required
  840. gemInfo.m_name = Py_To_String(data["gem_name"]);
  841. // optional
  842. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  843. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  844. gemInfo.m_version = Py_To_String_Optional(data, "version", gemInfo.m_version);
  845. gemInfo.m_lastUpdatedDate = Py_To_String_Optional(data, "last_updated", gemInfo.m_lastUpdatedDate);
  846. gemInfo.m_binarySizeInKB = Py_To_Int_Optional(data, "binary_size", gemInfo.m_binarySizeInKB);
  847. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  848. gemInfo.m_origin = Py_To_String_Optional(data, "origin", "");
  849. gemInfo.m_originURL = Py_To_String_Optional(data, "origin_url", "");
  850. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  851. gemInfo.m_iconPath = Py_To_String_Optional(data, "icon_path", "preview.png");
  852. gemInfo.m_licenseText = Py_To_String_Optional(data, "license", "Unspecified License");
  853. gemInfo.m_licenseLink = Py_To_String_Optional(data, "license_url", "");
  854. gemInfo.m_repoUri = Py_To_String_Optional(data, "repo_uri", "");
  855. if (gemInfo.m_origin.contains("Open 3D Engine"))
  856. {
  857. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEngine;
  858. }
  859. else if (data.contains("origin"))
  860. {
  861. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Remote;
  862. }
  863. // If no origin was provided this cannot be remote and would be specified if O3DE so it should be local
  864. else
  865. {
  866. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  867. }
  868. // As long Base Open3DEngine gems are installed before first startup non-remote gems will be downloaded
  869. if (gemInfo.m_gemOrigin != GemInfo::GemOrigin::Remote)
  870. {
  871. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  872. }
  873. if (data.contains("user_tags"))
  874. {
  875. for (auto tag : data["user_tags"])
  876. {
  877. gemInfo.m_features.push_back(Py_To_String(tag));
  878. }
  879. }
  880. if (data.contains("platforms"))
  881. {
  882. for (auto platform : data["platforms"])
  883. {
  884. gemInfo.m_platforms |= GemInfo::GetPlatformFromString(Py_To_String(platform));
  885. }
  886. }
  887. if (data.contains("dependencies"))
  888. {
  889. for (auto dependency : data["dependencies"])
  890. {
  891. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  892. }
  893. }
  894. QString gemType = Py_To_String_Optional(data, "type", "");
  895. if (gemType == "Asset")
  896. {
  897. gemInfo.m_types |= GemInfo::Type::Asset;
  898. }
  899. if (gemType == "Code")
  900. {
  901. gemInfo.m_types |= GemInfo::Type::Code;
  902. }
  903. if (gemType == "Tool")
  904. {
  905. gemInfo.m_types |= GemInfo::Type::Tool;
  906. }
  907. }
  908. catch ([[maybe_unused]] const std::exception& e)
  909. {
  910. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  911. }
  912. }
  913. return gemInfo;
  914. }
  915. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  916. {
  917. ProjectInfo projectInfo;
  918. projectInfo.m_path = Py_To_String(path);
  919. projectInfo.m_needsBuild = false;
  920. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  921. if (pybind11::isinstance<pybind11::dict>(projectData))
  922. {
  923. try
  924. {
  925. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  926. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  927. projectInfo.m_id = Py_To_String_Optional(projectData, "project_id", projectInfo.m_id);
  928. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  929. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  930. projectInfo.m_requirements = Py_To_String_Optional(projectData, "requirements", projectInfo.m_requirements);
  931. projectInfo.m_license = Py_To_String_Optional(projectData, "license", projectInfo.m_license);
  932. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  933. projectInfo.m_engineName = Py_To_String_Optional(projectData, "engine", projectInfo.m_engineName);
  934. if (projectData.contains("user_tags"))
  935. {
  936. for (auto tag : projectData["user_tags"])
  937. {
  938. projectInfo.m_userTags.append(Py_To_String(tag));
  939. }
  940. }
  941. auto enginePathResult = m_manifest.attr("get_project_engine_path")(path);
  942. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  943. {
  944. // request a posix path so it looks like what is in o3de_manifest.json
  945. projectInfo.m_enginePath = Py_To_String(enginePathResult.attr("as_posix")());
  946. }
  947. }
  948. catch ([[maybe_unused]] const std::exception& e)
  949. {
  950. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  951. }
  952. }
  953. return projectInfo;
  954. }
  955. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  956. {
  957. QVector<ProjectInfo> projects;
  958. bool result = ExecuteWithLock([&] {
  959. // external projects
  960. for (auto path : m_manifest.attr("get_manifest_projects")())
  961. {
  962. projects.push_back(ProjectInfoFromPath(path));
  963. }
  964. // projects from the engine
  965. for (auto path : m_manifest.attr("get_engine_projects")())
  966. {
  967. projects.push_back(ProjectInfoFromPath(path));
  968. }
  969. });
  970. if (!result)
  971. {
  972. return AZ::Failure();
  973. }
  974. else
  975. {
  976. return AZ::Success(AZStd::move(projects));
  977. }
  978. }
  979. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForRepo(const QString& repoUri)
  980. {
  981. QVector<ProjectInfo> projects;
  982. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  983. [&]
  984. {
  985. auto pyUri = QString_To_Py_String(repoUri);
  986. auto projectPaths = m_repo.attr("get_project_json_paths_from_cached_repo")(pyUri);
  987. if (pybind11::isinstance<pybind11::set>(projectPaths))
  988. {
  989. for (auto path : projectPaths)
  990. {
  991. ProjectInfo projectInfo = ProjectInfoFromPath(path);
  992. projectInfo.m_remote = true;
  993. projects.push_back(projectInfo);
  994. }
  995. }
  996. });
  997. if (!result.IsSuccess())
  998. {
  999. return AZ::Failure(result.GetError());
  1000. }
  1001. return AZ::Success(AZStd::move(projects));
  1002. }
  1003. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForAllRepos()
  1004. {
  1005. QVector<ProjectInfo> projectInfos;
  1006. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1007. [&]
  1008. {
  1009. auto projectPaths = m_repo.attr("get_project_json_paths_from_all_cached_repos")();
  1010. if (pybind11::isinstance<pybind11::set>(projectPaths))
  1011. {
  1012. for (auto path : projectPaths)
  1013. {
  1014. ProjectInfo projectInfo = ProjectInfoFromPath(path);
  1015. projectInfo.m_remote = true;
  1016. projectInfos.push_back(projectInfo);
  1017. }
  1018. }
  1019. });
  1020. if (!result.IsSuccess())
  1021. {
  1022. return AZ::Failure(result.GetError());
  1023. }
  1024. return AZ::Success(AZStd::move(projectInfos));
  1025. }
  1026. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  1027. {
  1028. return ExecuteWithLockErrorHandling([&]
  1029. {
  1030. m_enableGemProject.attr("enable_gem_in_project")(
  1031. pybind11::none(), // gem name not needed as path is provided
  1032. QString_To_Py_Path(gemPath),
  1033. pybind11::none(), // project name not needed as path is provided
  1034. QString_To_Py_Path(projectPath)
  1035. );
  1036. });
  1037. }
  1038. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  1039. {
  1040. return ExecuteWithLockErrorHandling([&]
  1041. {
  1042. m_disableGemProject.attr("disable_gem_in_project")(
  1043. pybind11::none(), // gem name not needed as path is provided
  1044. QString_To_Py_Path(gemPath),
  1045. pybind11::none(), // project name not needed as path is provided
  1046. QString_To_Py_Path(projectPath)
  1047. );
  1048. });
  1049. }
  1050. bool PythonBindings::RemoveInvalidProjects()
  1051. {
  1052. bool removalResult = false;
  1053. bool result = ExecuteWithLock(
  1054. [&]
  1055. {
  1056. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  1057. // Returns an exit code so boolify it then invert result
  1058. removalResult = !pythonRemovalResult.cast<bool>();
  1059. });
  1060. return result && removalResult;
  1061. }
  1062. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  1063. {
  1064. bool updateProjectSucceeded = false;
  1065. auto result = ExecuteWithLockErrorHandling([&]
  1066. {
  1067. using namespace pybind11::literals;
  1068. std::list<std::string> newTags;
  1069. for (const auto& i : projectInfo.m_userTags)
  1070. {
  1071. newTags.push_back(i.toStdString());
  1072. }
  1073. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  1074. "proj_path"_a = QString_To_Py_Path(projectInfo.m_path),
  1075. "new_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  1076. "new_id"_a = QString_To_Py_String(projectInfo.m_id),
  1077. "new_origin"_a = QString_To_Py_String(projectInfo.m_origin),
  1078. "new_display"_a = QString_To_Py_String(projectInfo.m_displayName),
  1079. "new_summary"_a = QString_To_Py_String(projectInfo.m_summary),
  1080. "new_icon"_a = QString_To_Py_String(projectInfo.m_iconPath),
  1081. "replace_tags"_a = pybind11::list(pybind11::cast(newTags)),
  1082. "new_engine_name"_a = QString_To_Py_String(projectInfo.m_engineName)
  1083. );
  1084. updateProjectSucceeded = (editResult.cast<int>() == 0);
  1085. });
  1086. if (!result.IsSuccess())
  1087. {
  1088. return result;
  1089. }
  1090. else if (!updateProjectSucceeded)
  1091. {
  1092. return AZ::Failure<AZStd::string>("Failed to update project.");
  1093. }
  1094. return AZ::Success();
  1095. }
  1096. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path) const
  1097. {
  1098. ProjectTemplateInfo templateInfo(TemplateInfoFromPath(path));
  1099. if (templateInfo.IsValid())
  1100. {
  1101. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  1102. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  1103. if (enabledGemNames)
  1104. {
  1105. for (auto gem : enabledGemNames.GetValue())
  1106. {
  1107. // Exclude the template ${Name} placeholder for the list of included gems
  1108. // That Gem gets created with the project
  1109. if (!gem.contains("${Name}"))
  1110. {
  1111. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  1112. }
  1113. }
  1114. }
  1115. }
  1116. return templateInfo;
  1117. }
  1118. TemplateInfo PythonBindings::TemplateInfoFromPath(pybind11::handle path) const
  1119. {
  1120. TemplateInfo templateInfo;
  1121. templateInfo.m_path = Py_To_String(path);
  1122. using namespace pybind11::literals;
  1123. // no project path is needed when a template path is provided
  1124. auto data = m_manifest.attr("get_template_json_data")("template_path"_a = path);
  1125. if (pybind11::isinstance<pybind11::dict>(data))
  1126. {
  1127. try
  1128. {
  1129. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  1130. templateInfo.m_name = Py_To_String(data["template_name"]);
  1131. templateInfo.m_summary = Py_To_String(data["summary"]);
  1132. if (data.contains("canonical_tags"))
  1133. {
  1134. for (auto tag : data["canonical_tags"])
  1135. {
  1136. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  1137. }
  1138. }
  1139. if (data.contains("user_tags"))
  1140. {
  1141. for (auto tag : data["user_tags"])
  1142. {
  1143. templateInfo.m_userTags.push_back(Py_To_String(tag));
  1144. }
  1145. }
  1146. templateInfo.m_requirements = Py_To_String_Optional(data, "requirements", "");
  1147. templateInfo.m_license = Py_To_String_Optional(data, "license", "");
  1148. }
  1149. catch ([[maybe_unused]] const std::exception& e)
  1150. {
  1151. AZ_Warning("PythonBindings", false, "Failed to get TemplateInfo for %s", Py_To_String(path));
  1152. }
  1153. }
  1154. return templateInfo;
  1155. }
  1156. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates()
  1157. {
  1158. QVector<ProjectTemplateInfo> templates;
  1159. bool result = ExecuteWithLock([&] {
  1160. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  1161. {
  1162. templates.push_back(ProjectTemplateInfoFromPath(path));
  1163. }
  1164. });
  1165. if (!result)
  1166. {
  1167. return AZ::Failure();
  1168. }
  1169. else
  1170. {
  1171. return AZ::Success(AZStd::move(templates));
  1172. }
  1173. }
  1174. AZ::Outcome<QVector<TemplateInfo>> PythonBindings::GetGemTemplates()
  1175. {
  1176. QVector<TemplateInfo> templates;
  1177. bool result = ExecuteWithLock(
  1178. [&]
  1179. {
  1180. for (auto path : m_manifest.attr("get_templates_for_gem_creation")())
  1181. {
  1182. templates.push_back(TemplateInfoFromPath(path));
  1183. }
  1184. });
  1185. if (!result)
  1186. {
  1187. return AZ::Failure();
  1188. }
  1189. else
  1190. {
  1191. return AZ::Success(AZStd::move(templates));
  1192. }
  1193. }
  1194. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplatesForRepo(const QString& repoUri) const
  1195. {
  1196. QVector<ProjectTemplateInfo> templates;
  1197. bool result = ExecuteWithLock(
  1198. [&]
  1199. {
  1200. using namespace pybind11::literals;
  1201. auto templatePaths = m_repo.attr("get_template_json_paths_from_cached_repo")(
  1202. "repo_uri"_a = QString_To_Py_String(repoUri)
  1203. );
  1204. if (pybind11::isinstance<pybind11::set>(templatePaths))
  1205. {
  1206. for (auto path : templatePaths)
  1207. {
  1208. ProjectTemplateInfo remoteTemplate = ProjectTemplateInfoFromPath(path);
  1209. remoteTemplate.m_isRemote = true;
  1210. templates.push_back(remoteTemplate);
  1211. }
  1212. }
  1213. });
  1214. if (!result)
  1215. {
  1216. return AZ::Failure();
  1217. }
  1218. else
  1219. {
  1220. return AZ::Success(AZStd::move(templates));
  1221. }
  1222. }
  1223. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplatesForAllRepos() const
  1224. {
  1225. QVector<ProjectTemplateInfo> templates;
  1226. bool result = ExecuteWithLock(
  1227. [&]
  1228. {
  1229. auto templatePaths = m_repo.attr("get_template_json_paths_from_all_cached_repos")();
  1230. if (pybind11::isinstance<pybind11::set>(templatePaths))
  1231. {
  1232. for (auto path : templatePaths)
  1233. {
  1234. ProjectTemplateInfo remoteTemplate = ProjectTemplateInfoFromPath(path);
  1235. remoteTemplate.m_isRemote = true;
  1236. templates.push_back(remoteTemplate);
  1237. }
  1238. }
  1239. });
  1240. if (!result)
  1241. {
  1242. return AZ::Failure();
  1243. }
  1244. else
  1245. {
  1246. return AZ::Success(AZStd::move(templates));
  1247. }
  1248. }
  1249. AZ::Outcome<void, AZStd::string> PythonBindings::RefreshGemRepo(const QString& repoUri)
  1250. {
  1251. bool refreshResult = false;
  1252. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1253. [&]
  1254. {
  1255. auto pyUri = QString_To_Py_String(repoUri);
  1256. auto pythonRefreshResult = m_repo.attr("refresh_repo")(pyUri);
  1257. // Returns an exit code so boolify it then invert result
  1258. refreshResult = !pythonRefreshResult.cast<bool>();
  1259. });
  1260. if (!result.IsSuccess())
  1261. {
  1262. return result;
  1263. }
  1264. else if (!refreshResult)
  1265. {
  1266. return AZ::Failure<AZStd::string>("Failed to refresh repo.");
  1267. }
  1268. return AZ::Success();
  1269. }
  1270. bool PythonBindings::RefreshAllGemRepos()
  1271. {
  1272. bool refreshResult = false;
  1273. bool result = ExecuteWithLock(
  1274. [&]
  1275. {
  1276. auto pythonRefreshResult = m_repo.attr("refresh_repos")();
  1277. // Returns an exit code so boolify it then invert result
  1278. refreshResult = !pythonRefreshResult.cast<bool>();
  1279. });
  1280. return result && refreshResult;
  1281. }
  1282. IPythonBindings::DetailedOutcome PythonBindings::AddGemRepo(const QString& repoUri)
  1283. {
  1284. bool registrationResult = false;
  1285. bool result = ExecuteWithLock(
  1286. [&]
  1287. {
  1288. auto pyUri = QString_To_Py_String(repoUri);
  1289. auto pythonRegistrationResult = m_register.attr("register")(
  1290. pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pyUri);
  1291. // Returns an exit code so boolify it then invert result
  1292. registrationResult = !pythonRegistrationResult.cast<bool>();
  1293. });
  1294. if (!result || !registrationResult)
  1295. {
  1296. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1297. }
  1298. return AZ::Success();
  1299. }
  1300. bool PythonBindings::RemoveGemRepo(const QString& repoUri)
  1301. {
  1302. bool registrationResult = false;
  1303. bool result = ExecuteWithLock(
  1304. [&]
  1305. {
  1306. using namespace pybind11::literals;
  1307. auto pythonRegistrationResult = m_register.attr("register")(
  1308. "engine_path"_a = pybind11::none(),
  1309. "project_path"_a = pybind11::none(),
  1310. "gem_path"_a = pybind11::none(),
  1311. "external_subdir_path"_a = pybind11::none(),
  1312. "template_path"_a = pybind11::none(),
  1313. "restricted_path"_a = pybind11::none(),
  1314. "repo_uri"_a = QString_To_Py_String(repoUri),
  1315. "default_engines_folder"_a = pybind11::none(),
  1316. "default_projects_folder"_a = pybind11::none(),
  1317. "default_gems_folder"_a = pybind11::none(),
  1318. "default_templates_folder"_a = pybind11::none(),
  1319. "default_restricted_folder"_a = pybind11::none(),
  1320. "default_third_party_folder"_a = pybind11::none(),
  1321. "external_subdir_engine_path"_a = pybind11::none(),
  1322. "external_subdir_project_path"_a = pybind11::none(),
  1323. "external_subdir_gem_path"_a = pybind11::none(),
  1324. "remove"_a = true,
  1325. "force"_a = false
  1326. );
  1327. // Returns an exit code so boolify it then invert result
  1328. registrationResult = !pythonRegistrationResult.cast<bool>();
  1329. });
  1330. return result && registrationResult;
  1331. }
  1332. GemRepoInfo PythonBindings::GetGemRepoInfo(pybind11::handle repoUri)
  1333. {
  1334. GemRepoInfo gemRepoInfo;
  1335. gemRepoInfo.m_repoUri = Py_To_String(repoUri);
  1336. auto data = m_manifest.attr("get_repo_json_data")(repoUri);
  1337. if (pybind11::isinstance<pybind11::dict>(data))
  1338. {
  1339. try
  1340. {
  1341. // required
  1342. gemRepoInfo.m_name = Py_To_String(data["repo_name"]);
  1343. gemRepoInfo.m_origin = Py_To_String(data["origin"]);
  1344. // optional
  1345. gemRepoInfo.m_summary = Py_To_String_Optional(data, "summary", "No summary provided.");
  1346. gemRepoInfo.m_additionalInfo = Py_To_String_Optional(data, "additional_info", "");
  1347. auto repoPath = m_manifest.attr("get_repo_path")(repoUri);
  1348. gemRepoInfo.m_path = gemRepoInfo.m_directoryLink = Py_To_String(repoPath);
  1349. QString lastUpdated = Py_To_String_Optional(data, "last_updated", "");
  1350. gemRepoInfo.m_lastUpdated = QDateTime::fromString(lastUpdated, RepoTimeFormat);
  1351. if (data.contains("enabled"))
  1352. {
  1353. gemRepoInfo.m_isEnabled = data["enabled"].cast<bool>();
  1354. }
  1355. else
  1356. {
  1357. gemRepoInfo.m_isEnabled = false;
  1358. }
  1359. if (data.contains("gems"))
  1360. {
  1361. for (auto gemPath : data["gems"])
  1362. {
  1363. gemRepoInfo.m_includedGemUris.push_back(Py_To_String(gemPath));
  1364. }
  1365. }
  1366. }
  1367. catch ([[maybe_unused]] const std::exception& e)
  1368. {
  1369. AZ_Warning("PythonBindings", false, "Failed to get GemRepoInfo for repo %s", Py_To_String(repoUri));
  1370. }
  1371. }
  1372. return gemRepoInfo;
  1373. }
  1374. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  1375. {
  1376. QVector<GemRepoInfo> gemRepos;
  1377. auto result = ExecuteWithLockErrorHandling(
  1378. [&]
  1379. {
  1380. for (auto repoUri : m_manifest.attr("get_manifest_repos")())
  1381. {
  1382. gemRepos.push_back(GetGemRepoInfo(repoUri));
  1383. }
  1384. });
  1385. if (!result.IsSuccess())
  1386. {
  1387. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  1388. }
  1389. AZStd::sort(gemRepos.begin(), gemRepos.end());
  1390. return AZ::Success(AZStd::move(gemRepos));
  1391. }
  1392. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForRepo(const QString& repoUri)
  1393. {
  1394. QVector<GemInfo> gemInfos;
  1395. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1396. [&]
  1397. {
  1398. auto pyUri = QString_To_Py_String(repoUri);
  1399. auto gemPaths = m_repo.attr("get_gem_json_paths_from_cached_repo")(pyUri);
  1400. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1401. {
  1402. for (auto path : gemPaths)
  1403. {
  1404. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1405. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1406. gemInfos.push_back(gemInfo);
  1407. }
  1408. }
  1409. });
  1410. if (!result.IsSuccess())
  1411. {
  1412. return AZ::Failure(result.GetError());
  1413. }
  1414. return AZ::Success(AZStd::move(gemInfos));
  1415. }
  1416. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForAllRepos()
  1417. {
  1418. QVector<GemInfo> gemInfos;
  1419. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1420. [&]
  1421. {
  1422. auto gemPaths = m_repo.attr("get_gem_json_paths_from_all_cached_repos")();
  1423. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1424. {
  1425. for (auto path : gemPaths)
  1426. {
  1427. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1428. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1429. gemInfos.push_back(gemInfo);
  1430. }
  1431. }
  1432. });
  1433. if (!result.IsSuccess())
  1434. {
  1435. return AZ::Failure(result.GetError());
  1436. }
  1437. return AZ::Success(AZStd::move(gemInfos));
  1438. }
  1439. IPythonBindings::DetailedOutcome PythonBindings::DownloadGem(
  1440. const QString& gemName, const QString& path, std::function<void(int, int)> gemProgressCallback, bool force)
  1441. {
  1442. // This process is currently limited to download a single object at a time.
  1443. bool downloadSucceeded = false;
  1444. m_requestCancelDownload = false;
  1445. auto result = ExecuteWithLockErrorHandling(
  1446. [&]
  1447. {
  1448. auto downloadResult = m_download.attr("download_gem")(
  1449. QString_To_Py_String(gemName), // gem name
  1450. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1451. false, // skip auto register
  1452. force, // force overwrite
  1453. pybind11::cpp_function(
  1454. [this, gemProgressCallback](int bytesDownloaded, int totalBytes)
  1455. {
  1456. gemProgressCallback(bytesDownloaded, totalBytes);
  1457. return m_requestCancelDownload;
  1458. }) // Callback for download progress and cancelling
  1459. );
  1460. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1461. });
  1462. if (!result.IsSuccess())
  1463. {
  1464. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1465. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1466. }
  1467. else if (!downloadSucceeded)
  1468. {
  1469. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1470. }
  1471. return AZ::Success();
  1472. }
  1473. IPythonBindings::DetailedOutcome PythonBindings::DownloadProject(
  1474. const QString& projectName, const QString& path, std::function<void(int, int)> projectProgressCallback, bool force)
  1475. {
  1476. // This process is currently limited to download a single object at a time.
  1477. bool downloadSucceeded = false;
  1478. m_requestCancelDownload = false;
  1479. auto result = ExecuteWithLockErrorHandling(
  1480. [&]
  1481. {
  1482. auto downloadResult = m_download.attr("download_project")(
  1483. QString_To_Py_String(projectName), // gem name
  1484. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1485. false, // skip auto register
  1486. force, // force overwrite
  1487. pybind11::cpp_function(
  1488. [this, projectProgressCallback](int bytesDownloaded, int totalBytes)
  1489. {
  1490. projectProgressCallback(bytesDownloaded, totalBytes);
  1491. return m_requestCancelDownload;
  1492. }) // Callback for download progress and cancelling
  1493. );
  1494. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1495. });
  1496. if (!result.IsSuccess())
  1497. {
  1498. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1499. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1500. }
  1501. else if (!downloadSucceeded)
  1502. {
  1503. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1504. }
  1505. return AZ::Success();
  1506. }
  1507. IPythonBindings::DetailedOutcome PythonBindings::DownloadTemplate(
  1508. const QString& templateName, const QString& path, std::function<void(int, int)> templateProgressCallback, bool force)
  1509. {
  1510. // This process is currently limited to download a single object at a time.
  1511. bool downloadSucceeded = false;
  1512. m_requestCancelDownload = false;
  1513. auto result = ExecuteWithLockErrorHandling(
  1514. [&]
  1515. {
  1516. auto downloadResult = m_download.attr("download_template")(
  1517. QString_To_Py_String(templateName), // gem name
  1518. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1519. false, // skip auto register
  1520. force, // force overwrite
  1521. pybind11::cpp_function(
  1522. [this, templateProgressCallback](int bytesDownloaded, int totalBytes)
  1523. {
  1524. templateProgressCallback(bytesDownloaded, totalBytes);
  1525. return m_requestCancelDownload;
  1526. }) // Callback for download progress and cancelling
  1527. );
  1528. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1529. });
  1530. if (!result.IsSuccess())
  1531. {
  1532. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1533. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1534. }
  1535. else if (!downloadSucceeded)
  1536. {
  1537. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1538. }
  1539. return AZ::Success();
  1540. }
  1541. void PythonBindings::CancelDownload()
  1542. {
  1543. m_requestCancelDownload = true;
  1544. }
  1545. bool PythonBindings::IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated)
  1546. {
  1547. bool updateAvaliableResult = false;
  1548. bool result = ExecuteWithLock(
  1549. [&]
  1550. {
  1551. auto pyGemName = QString_To_Py_String(gemName);
  1552. auto pyLastUpdated = QString_To_Py_String(lastUpdated);
  1553. auto pythonUpdateAvaliableResult = m_download.attr("is_o3de_gem_update_available")(pyGemName, pyLastUpdated);
  1554. updateAvaliableResult = pythonUpdateAvaliableResult.cast<bool>();
  1555. });
  1556. return result && updateAvaliableResult;
  1557. }
  1558. IPythonBindings::ErrorPair PythonBindings::GetErrorPair()
  1559. {
  1560. if (const size_t errorSize = m_pythonErrorStrings.size())
  1561. {
  1562. AZStd::string detailedString =
  1563. errorSize == 1 ? "" : AZStd::accumulate(m_pythonErrorStrings.begin(), m_pythonErrorStrings.end(), AZStd::string(""));
  1564. return IPythonBindings::ErrorPair(m_pythonErrorStrings.front(), detailedString);
  1565. }
  1566. // If no error was found
  1567. else
  1568. {
  1569. return IPythonBindings::ErrorPair(AZStd::string("Unknown Python Bindings Error"), AZStd::string(""));
  1570. }
  1571. }
  1572. void PythonBindings::AddErrorString(AZStd::string errorString)
  1573. {
  1574. m_pythonErrorStrings.push_back(errorString);
  1575. }
  1576. } // namespace O3DE::ProjectManager