PythonBindings.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <PythonBindings.h>
  9. #include <ProjectManagerDefs.h>
  10. // Qt defines slots, which interferes with the use here.
  11. #pragma push_macro("slots")
  12. #undef slots
  13. #include <pybind11/functional.h>
  14. #include <pybind11/embed.h>
  15. #include <pybind11/eval.h>
  16. #include <pybind11/stl.h>
  17. #pragma pop_macro("slots")
  18. #include <AzCore/IO/FileIO.h>
  19. #include <AzCore/IO/SystemFile.h>
  20. #include <AzCore/std/containers/unordered_set.h>
  21. #include <AzCore/std/string/conversions.h>
  22. #include <AzCore/std/numeric.h>
  23. #include <AzCore/StringFunc/StringFunc.h>
  24. #include <AzCore/std/sort.h>
  25. #include <QDir>
  26. namespace Platform
  27. {
  28. bool InsertPythonLibraryPath(
  29. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  30. {
  31. // append lib path to Python paths
  32. AZ::IO::FixedMaxPath libPath = engineRoot;
  33. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  34. libPath = libPath.LexicallyNormal();
  35. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  36. {
  37. paths.insert(libPath.c_str());
  38. return true;
  39. }
  40. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  41. return false;
  42. }
  43. // Implemented in each different platform's PAL implementation files, as it differs per platform.
  44. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  45. } // namespace Platform
  46. #define Py_To_String(obj) pybind11::str(obj).cast<std::string>().c_str()
  47. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  48. #define Py_To_Int(obj) obj.cast<int>()
  49. #define Py_To_Int_Optional(dict, key, default_int) dict.contains(key) ? Py_To_Int(dict[key]) : default_int
  50. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  51. #define QString_To_Py_Path(value) value.isEmpty() ? pybind11::none() : m_pathlib.attr("Path")(value.toStdString())
  52. pybind11::list QStringList_To_Py_List(const QStringList& values)
  53. {
  54. std::list<std::string> newValues;
  55. for (const auto& i : values)
  56. {
  57. newValues.push_back(i.toStdString());
  58. }
  59. return pybind11::list(pybind11::cast(newValues));
  60. };
  61. namespace RedirectOutput
  62. {
  63. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  64. struct RedirectOutput
  65. {
  66. PyObject_HEAD RedirectOutputFunc write;
  67. };
  68. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  69. {
  70. std::size_t written(0);
  71. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  72. if (selfimpl->write)
  73. {
  74. char* data;
  75. if (!PyArg_ParseTuple(args, "s", &data))
  76. {
  77. return PyLong_FromSize_t(0);
  78. }
  79. selfimpl->write(data);
  80. written = strlen(data);
  81. }
  82. return PyLong_FromSize_t(written);
  83. }
  84. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  85. {
  86. // no-op
  87. return Py_BuildValue("");
  88. }
  89. PyMethodDef RedirectMethods[] = {
  90. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  91. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  92. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  93. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  94. {0, 0, 0, 0} // sentinel
  95. };
  96. PyTypeObject RedirectOutputType = {
  97. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  98. sizeof(RedirectOutput), /* tp_basicsize */
  99. 0, /* tp_itemsize */
  100. 0, /* tp_dealloc */
  101. 0, /* tp_print */
  102. 0, /* tp_getattr */
  103. 0, /* tp_setattr */
  104. 0, /* tp_reserved */
  105. 0, /* tp_repr */
  106. 0, /* tp_as_number */
  107. 0, /* tp_as_sequence */
  108. 0, /* tp_as_mapping */
  109. 0, /* tp_hash */
  110. 0, /* tp_call */
  111. 0, /* tp_str */
  112. 0, /* tp_getattro */
  113. 0, /* tp_setattro */
  114. 0, /* tp_as_buffer */
  115. Py_TPFLAGS_DEFAULT, /* tp_flags */
  116. "azlmbr_redirect objects", /* tp_doc */
  117. 0, /* tp_traverse */
  118. 0, /* tp_clear */
  119. 0, /* tp_richcompare */
  120. 0, /* tp_weaklistoffset */
  121. 0, /* tp_iter */
  122. 0, /* tp_iternext */
  123. RedirectMethods, /* tp_methods */
  124. 0, /* tp_members */
  125. 0, /* tp_getset */
  126. 0, /* tp_base */
  127. 0, /* tp_dict */
  128. 0, /* tp_descr_get */
  129. 0, /* tp_descr_set */
  130. 0, /* tp_dictoffset */
  131. 0, /* tp_init */
  132. 0, /* tp_alloc */
  133. 0 /* tp_new */
  134. };
  135. PyModuleDef RedirectOutputModule = {
  136. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  137. };
  138. // Internal state
  139. PyObject* g_redirect_stdout = nullptr;
  140. PyObject* g_redirect_stdout_saved = nullptr;
  141. PyObject* g_redirect_stderr = nullptr;
  142. PyObject* g_redirect_stderr_saved = nullptr;
  143. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  144. {
  145. g_redirect_stdout = nullptr;
  146. g_redirect_stdout_saved = nullptr;
  147. g_redirect_stderr = nullptr;
  148. g_redirect_stderr_saved = nullptr;
  149. RedirectOutputType.tp_new = PyType_GenericNew;
  150. if (PyType_Ready(&RedirectOutputType) < 0)
  151. {
  152. return 0;
  153. }
  154. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  155. if (redirectModule)
  156. {
  157. Py_INCREF(&RedirectOutputType);
  158. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  159. }
  160. return redirectModule;
  161. }
  162. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  163. {
  164. if (PyType_Ready(&RedirectOutputType) < 0)
  165. {
  166. AZ_Warning("python", false, "RedirectOutputType not ready!");
  167. return;
  168. }
  169. if (!current)
  170. {
  171. saved = PySys_GetObject(funcname); // borrowed
  172. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  173. }
  174. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  175. redirectOutput->write = func;
  176. PySys_SetObject(funcname, current);
  177. }
  178. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  179. {
  180. if (current)
  181. {
  182. PySys_SetObject(funcname, saved);
  183. }
  184. Py_XDECREF(current);
  185. current = nullptr;
  186. }
  187. PyObject* s_RedirectModule = nullptr;
  188. void Intialize(PyObject* module, RedirectOutputFunc stdoutFunction, RedirectOutputFunc stderrFunction)
  189. {
  190. s_RedirectModule = module;
  191. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, stdoutFunction);
  192. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, stderrFunction);
  193. PySys_WriteStdout("RedirectOutput installed\n");
  194. }
  195. void Shutdown()
  196. {
  197. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  198. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  199. Py_XDECREF(s_RedirectModule);
  200. s_RedirectModule = nullptr;
  201. }
  202. } // namespace RedirectOutput
  203. namespace O3DE::ProjectManager
  204. {
  205. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  206. : m_enginePath(enginePath)
  207. {
  208. m_pythonStarted = StartPython();
  209. }
  210. PythonBindings::~PythonBindings()
  211. {
  212. if (m_pythonStarted)
  213. {
  214. StopPython();
  215. }
  216. }
  217. void PythonBindings::OnStdOut(const char* msg)
  218. {
  219. AZ::Debug::Trace::Instance().Output("Python", msg);
  220. }
  221. void PythonBindings::OnStdError(const char* msg)
  222. {
  223. AZStd::string_view lastPythonError{ msg };
  224. if (constexpr AZStd::string_view pythonErrorPrefix = "ERROR:root:";
  225. lastPythonError.starts_with(pythonErrorPrefix))
  226. {
  227. lastPythonError = lastPythonError.substr(pythonErrorPrefix.size());
  228. }
  229. PythonBindingsInterface::Get()->AddErrorString(lastPythonError);
  230. AZ::Debug::Trace::Instance().Output("Python", msg);
  231. }
  232. bool PythonBindings::PythonStarted()
  233. {
  234. return m_pythonStarted && Py_IsInitialized();
  235. }
  236. bool PythonBindings::StartPython()
  237. {
  238. if (Py_IsInitialized())
  239. {
  240. AZ_Warning("python", false, "Python is already active");
  241. return m_pythonStarted;
  242. }
  243. m_pythonStarted = false;
  244. // set PYTHON_HOME
  245. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  246. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  247. {
  248. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  249. return false;
  250. }
  251. AZStd::wstring pyHomePath;
  252. AZStd::to_wstring(pyHomePath, pyBasePath);
  253. Py_SetPythonHome(pyHomePath.c_str());
  254. // display basic Python information
  255. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  256. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  257. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  258. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  259. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  260. try
  261. {
  262. // ignore system location for sites site-packages
  263. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  264. Py_IgnoreEnvironmentFlag = 1; // -E
  265. const bool initializeSignalHandlers = true;
  266. pybind11::initialize_interpreter(initializeSignalHandlers);
  267. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"), &PythonBindings::OnStdOut, &PythonBindings::OnStdError);
  268. // Acquire GIL before calling Python code
  269. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  270. pybind11::gil_scoped_acquire acquire;
  271. // sanity import check
  272. if (PyRun_SimpleString("import sys") != 0)
  273. {
  274. AZ_Assert(false, "Import sys failed");
  275. return false;
  276. }
  277. // import required modules
  278. m_register = pybind11::module::import("o3de.register");
  279. m_manifest = pybind11::module::import("o3de.manifest");
  280. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  281. m_gemProperties = pybind11::module::import("o3de.gem_properties");
  282. m_engineProperties = pybind11::module::import("o3de.engine_properties");
  283. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  284. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  285. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  286. m_projectManagerInterface = pybind11::module::import("o3de.project_manager_interface");
  287. m_download = pybind11::module::import("o3de.download");
  288. m_repo = pybind11::module::import("o3de.repo");
  289. m_pathlib = pybind11::module::import("pathlib");
  290. m_pythonStarted = !PyErr_Occurred();
  291. return m_pythonStarted;
  292. }
  293. catch ([[maybe_unused]] const std::exception& e)
  294. {
  295. AZ_Assert(false, "Py_Initialize() failed with %s", e.what());
  296. return false;
  297. }
  298. }
  299. bool PythonBindings::StopPython()
  300. {
  301. if (Py_IsInitialized())
  302. {
  303. RedirectOutput::Shutdown();
  304. pybind11::finalize_interpreter();
  305. }
  306. return Py_IsInitialized() == 0;
  307. }
  308. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback) const
  309. {
  310. if (!Py_IsInitialized())
  311. {
  312. return AZ::Failure("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(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(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. void GetGemInfoFromPyDict(GemInfo& gemInfo, pybind11::dict data)
  536. {
  537. // required
  538. gemInfo.m_name = Py_To_String(data["gem_name"]);
  539. // optional
  540. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  541. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  542. gemInfo.m_version = Py_To_String_Optional(data, "version", gemInfo.m_version);
  543. gemInfo.m_lastUpdatedDate = Py_To_String_Optional(data, "last_updated", gemInfo.m_lastUpdatedDate);
  544. gemInfo.m_binarySizeInKB = Py_To_Int_Optional(data, "binary_size", gemInfo.m_binarySizeInKB);
  545. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  546. gemInfo.m_origin = Py_To_String_Optional(data, "origin", "");
  547. gemInfo.m_originURL = Py_To_String_Optional(data, "origin_url", "");
  548. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  549. gemInfo.m_iconPath = Py_To_String_Optional(data, "icon_path", "preview.png");
  550. gemInfo.m_licenseText = Py_To_String_Optional(data, "license", "Unspecified License");
  551. gemInfo.m_licenseLink = Py_To_String_Optional(data, "license_url", "");
  552. gemInfo.m_repoUri = Py_To_String_Optional(data, "repo_uri", "");
  553. gemInfo.m_path = Py_To_String_Optional(data, "path", gemInfo.m_path);
  554. gemInfo.m_directoryLink = QDir::cleanPath(gemInfo.m_path);
  555. gemInfo.m_isEngineGem = Py_To_Int_Optional(data, "engine_gem", 0);
  556. gemInfo.m_isProjectGem = Py_To_Int_Optional(data, "project_gem", 0);
  557. if (gemInfo.m_isEngineGem || gemInfo.m_origin.contains("Open 3D Engine"))
  558. {
  559. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEngine;
  560. }
  561. else if (QUrl(gemInfo.m_repoUri, QUrl::StrictMode).isValid())
  562. {
  563. // this gem has a valid remote repo
  564. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Remote;
  565. }
  566. else
  567. {
  568. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  569. }
  570. // As long Base Open3DEngine gems are installed before first startup non-remote gems will be downloaded
  571. if (gemInfo.m_gemOrigin != GemInfo::GemOrigin::Remote)
  572. {
  573. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  574. }
  575. if (data.contains("user_tags"))
  576. {
  577. for (auto tag : data["user_tags"])
  578. {
  579. gemInfo.m_features.push_back(Py_To_String(tag));
  580. }
  581. }
  582. if (data.contains("platforms"))
  583. {
  584. for (auto platform : data["platforms"])
  585. {
  586. gemInfo.m_platforms |= GemInfo::GetPlatformFromString(Py_To_String(platform));
  587. }
  588. }
  589. if (data.contains("dependencies"))
  590. {
  591. for (auto dependency : data["dependencies"])
  592. {
  593. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  594. }
  595. }
  596. QString gemType = Py_To_String_Optional(data, "type", "");
  597. if (gemType == "Asset")
  598. {
  599. gemInfo.m_types |= GemInfo::Type::Asset;
  600. }
  601. if (gemType == "Code")
  602. {
  603. gemInfo.m_types |= GemInfo::Type::Code;
  604. }
  605. if (gemType == "Tool")
  606. {
  607. gemInfo.m_types |= GemInfo::Type::Tool;
  608. }
  609. if (data.contains("compatible_engines"))
  610. {
  611. for (auto compatible_engine : data["compatible_engines"])
  612. {
  613. gemInfo.m_compatibleEngines.push_back(Py_To_String(compatible_engine));
  614. }
  615. }
  616. }
  617. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  618. {
  619. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  620. if (gemInfo.IsValid())
  621. {
  622. return AZ::Success(AZStd::move(gemInfo));
  623. }
  624. else
  625. {
  626. return AZ::Failure();
  627. }
  628. }
  629. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  630. {
  631. QVector<GemInfo> gems;
  632. auto result = ExecuteWithLockErrorHandling([&]
  633. {
  634. auto pyProjectPath = QString_To_Py_Path(projectPath);
  635. for (pybind11::handle pyGemJsonData : m_projectManagerInterface.attr("get_all_gem_infos")(pyProjectPath))
  636. {
  637. GemInfo gemInfo;
  638. GetGemInfoFromPyDict(gemInfo, pyGemJsonData.cast<pybind11::dict>());
  639. // Mark as downloaded because this gem was registered with an existing directory
  640. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  641. gems.push_back(AZStd::move(gemInfo));
  642. }
  643. });
  644. if (!result.IsSuccess())
  645. {
  646. return AZ::Failure(result.GetError().c_str());
  647. }
  648. // this sorts by gem name and version
  649. AZStd::sort(gems.begin(), gems.end());
  650. return AZ::Success(AZStd::move(gems));
  651. }
  652. AZ::Outcome<QHash<QString, QString>, AZStd::string> PythonBindings::GetEnabledGems(const QString& projectPath, bool includeDependencies) const
  653. {
  654. QHash<QString, QString> enabledGems;
  655. auto result = ExecuteWithLockErrorHandling([&]
  656. {
  657. auto enabledGemsData = m_projectManagerInterface.attr("get_enabled_gems")(QString_To_Py_Path(projectPath), includeDependencies);
  658. if (pybind11::isinstance<pybind11::dict>(enabledGemsData))
  659. {
  660. for (auto item : pybind11::dict(enabledGemsData))
  661. {
  662. enabledGems.insert(Py_To_String(item.first), Py_To_String(item.second));
  663. }
  664. }
  665. });
  666. if (!result.IsSuccess())
  667. {
  668. return AZ::Failure(result.GetError().c_str());
  669. }
  670. else
  671. {
  672. return AZ::Success(AZStd::move(enabledGems));
  673. }
  674. }
  675. AZ::Outcome<void, AZStd::string> PythonBindings::GemRegistration(const QString& gemPath, const QString& projectPath, bool remove)
  676. {
  677. using namespace pybind11::literals;
  678. bool registrationResult = false;
  679. auto result = ExecuteWithLockErrorHandling(
  680. [&]
  681. {
  682. auto externalProjectPath = projectPath.isEmpty() ? pybind11::none() : QString_To_Py_Path(projectPath);
  683. auto pythonRegistrationResult = m_register.attr("register")(
  684. "engine_path"_a = pybind11::none(),
  685. "project_path"_a = pybind11::none(),
  686. "gem_path"_a = QString_To_Py_Path(gemPath),
  687. "external_subdir_path"_a = pybind11::none(),
  688. "template_path"_a = pybind11::none(),
  689. "restricted_path"_a = pybind11::none(),
  690. "repo_uri"_a = pybind11::none(),
  691. "default_engines_folder"_a = pybind11::none(),
  692. "default_projects_folder"_a = pybind11::none(),
  693. "default_gems_folder"_a = pybind11::none(),
  694. "default_templates_folder"_a = pybind11::none(),
  695. "default_restricted_folder"_a = pybind11::none(),
  696. "default_third_party_folder"_a = pybind11::none(),
  697. "external_subdir_engine_path"_a = pybind11::none(),
  698. "external_subdir_project_path"_a = externalProjectPath,
  699. "external_subdir_gem_path"_a = pybind11::none(),
  700. "remove"_a = remove
  701. );
  702. // Returns an exit code so boolify it then invert result
  703. registrationResult = !pythonRegistrationResult.cast<bool>();
  704. });
  705. if (!result.IsSuccess())
  706. {
  707. return AZ::Failure(result.GetError().c_str());
  708. }
  709. else if (!registrationResult)
  710. {
  711. return AZ::Failure(AZStd::string::format(
  712. "Failed to %s gem path %s", remove ? "unregister" : "register", gemPath.toUtf8().constData()));
  713. }
  714. return AZ::Success();
  715. }
  716. AZ::Outcome<void, AZStd::string> PythonBindings::RegisterGem(const QString& gemPath, const QString& projectPath)
  717. {
  718. return GemRegistration(gemPath, projectPath);
  719. }
  720. AZ::Outcome<void, AZStd::string> PythonBindings::UnregisterGem(const QString& gemPath, const QString& projectPath)
  721. {
  722. return GemRegistration(gemPath, projectPath, /*remove*/true);
  723. }
  724. IPythonBindings::DetailedOutcome PythonBindings::AddProject(const QString& path)
  725. {
  726. using namespace pybind11::literals;
  727. bool registrationResult = false;
  728. bool result = ExecuteWithLock([&] {
  729. auto pythonRegistrationResult = m_register.attr("register")(
  730. "project_path"_a = QString_To_Py_Path(path));
  731. // Returns an exit code so boolify it then invert result
  732. registrationResult = !pythonRegistrationResult.cast<bool>();
  733. });
  734. if (!result || !registrationResult)
  735. {
  736. return AZ::Failure(GetErrorPair());
  737. }
  738. return AZ::Success();
  739. }
  740. IPythonBindings::DetailedOutcome PythonBindings::RemoveProject(const QString& path)
  741. {
  742. using namespace pybind11::literals;
  743. bool registrationResult = false;
  744. bool result = ExecuteWithLock([&] {
  745. auto pythonRegistrationResult = m_register.attr("register")(
  746. "project_path"_a = QString_To_Py_Path(path),
  747. "remove"_a = true
  748. );
  749. // Returns an exit code so boolify it then invert result
  750. registrationResult = !pythonRegistrationResult.cast<bool>();
  751. });
  752. if (!result || !registrationResult)
  753. {
  754. return AZ::Failure(GetErrorPair());
  755. }
  756. return AZ::Success();
  757. }
  758. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo, bool registerProject)
  759. {
  760. using namespace pybind11::literals;
  761. ProjectInfo createdProjectInfo;
  762. bool result = ExecuteWithLock([&] {
  763. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  764. auto createProjectResult = m_engineTemplate.attr("create_project")(
  765. "project_path"_a = projectPath,
  766. "project_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  767. "template_path"_a = QString_To_Py_Path(projectTemplatePath),
  768. "version"_a = QString_To_Py_String(projectInfo.m_version),
  769. "no_register"_a = !registerProject
  770. );
  771. if (createProjectResult.cast<int>() == 0)
  772. {
  773. createdProjectInfo = ProjectInfoFromPath(projectPath);
  774. }
  775. });
  776. if (!result || !createdProjectInfo.IsValid())
  777. {
  778. return AZ::Failure();
  779. }
  780. else
  781. {
  782. return AZ::Success(AZStd::move(createdProjectInfo));
  783. }
  784. }
  785. AZ::Outcome<GemInfo> PythonBindings::CreateGem(const QString& templatePath, const GemInfo& gemInfo, bool registerGem/*=true*/)
  786. {
  787. using namespace pybind11::literals;
  788. GemInfo gemInfoResult;
  789. bool result = ExecuteWithLock(
  790. [&]
  791. {
  792. auto gemPath = QString_To_Py_Path(gemInfo.m_path);
  793. auto createGemResult = m_engineTemplate.attr("create_gem")(
  794. "gem_path"_a = gemPath,
  795. "template_path"_a = QString_To_Py_Path(templatePath),
  796. "gem_name"_a = QString_To_Py_String(gemInfo.m_name),
  797. "display_name"_a = QString_To_Py_String(gemInfo.m_displayName),
  798. "summary"_a = QString_To_Py_String(gemInfo.m_summary),
  799. "requirements"_a = QString_To_Py_String(gemInfo.m_requirement),
  800. "license"_a = QString_To_Py_String(gemInfo.m_licenseText),
  801. "license_url"_a = QString_To_Py_String(gemInfo.m_licenseLink),
  802. "origin"_a = QString_To_Py_String(gemInfo.m_origin),
  803. "origin_url"_a = QString_To_Py_String(gemInfo.m_originURL),
  804. "user_tags"_a = QString_To_Py_String(gemInfo.m_features.join(",")),
  805. "platforms"_a = QStringList_To_Py_List(gemInfo.GetPlatformsAsStringList()),
  806. "icon_path"_a = QString_To_Py_Path(gemInfo.m_iconPath),
  807. "documentation_url"_a = QString_To_Py_String(gemInfo.m_documentationLink),
  808. "repo_uri"_a = QString_To_Py_String(gemInfo.m_repoUri),
  809. "no_register"_a = !registerGem)
  810. ;
  811. if (createGemResult.cast<int>() == 0)
  812. {
  813. gemInfoResult = GemInfoFromPath(gemPath, pybind11::none());
  814. }
  815. });
  816. if (!result || !gemInfoResult.IsValid())
  817. {
  818. return AZ::Failure();
  819. }
  820. else
  821. {
  822. return AZ::Success(AZStd::move(gemInfoResult));
  823. }
  824. }
  825. AZ::Outcome<GemInfo> PythonBindings::EditGem(const QString& oldGemName, const GemInfo& newGemInfo)
  826. {
  827. using namespace pybind11::literals;
  828. GemInfo gemInfoResult;
  829. bool result = ExecuteWithLock(
  830. [&]
  831. {
  832. auto gemPath = QString_To_Py_Path(newGemInfo.m_path);
  833. auto editGemResult = m_gemProperties.attr("edit_gem_props")(
  834. "gem_path"_a = gemPath,
  835. "gem_name"_a = QString_To_Py_String(oldGemName),
  836. "new_name"_a = QString_To_Py_String(newGemInfo.m_name),
  837. "new_display"_a = QString_To_Py_String(newGemInfo.m_displayName),
  838. "new_origin"_a = QString_To_Py_String(newGemInfo.m_origin),
  839. "new_summary"_a = QString_To_Py_String(newGemInfo.m_summary),
  840. "new_icon"_a = QString_To_Py_String(newGemInfo.m_iconPath),
  841. "new_requirements"_a = QString_To_Py_String(newGemInfo.m_requirement),
  842. "new_documentation_url"_a = QString_To_Py_String(newGemInfo.m_documentationLink),
  843. "new_license"_a = QString_To_Py_String(newGemInfo.m_licenseText),
  844. "new_license_url"_a = QString_To_Py_String(newGemInfo.m_licenseLink),
  845. "new_repo_uri"_a = QString_To_Py_String(newGemInfo.m_repoUri),
  846. "replace_tags"_a = QStringList_To_Py_List(newGemInfo.m_features), //the python code seems to interpret these lists as space separated
  847. "replace_platforms"_a = QStringList_To_Py_List(newGemInfo.GetPlatformsAsStringList()))
  848. ;
  849. if (editGemResult.cast<int>() == 0)
  850. {
  851. gemInfoResult = GemInfoFromPath(gemPath, pybind11::none());
  852. }
  853. });
  854. if(!result || !gemInfoResult.IsValid())
  855. {
  856. return AZ::Failure();
  857. }
  858. else
  859. {
  860. return AZ::Success(AZStd::move(gemInfoResult));
  861. }
  862. }
  863. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  864. {
  865. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  866. if (projectInfo.IsValid())
  867. {
  868. return AZ::Success(AZStd::move(projectInfo));
  869. }
  870. else
  871. {
  872. return AZ::Failure();
  873. }
  874. }
  875. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  876. {
  877. GemInfo gemInfo;
  878. gemInfo.m_path = Py_To_String(path);
  879. gemInfo.m_directoryLink = QDir::cleanPath(gemInfo.m_path);
  880. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  881. if (pybind11::isinstance<pybind11::dict>(data))
  882. {
  883. try
  884. {
  885. GetGemInfoFromPyDict(gemInfo, data);
  886. }
  887. catch ([[maybe_unused]] const std::exception& e)
  888. {
  889. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  890. }
  891. }
  892. return gemInfo;
  893. }
  894. ProjectInfo PythonBindings::ProjectInfoFromDict(pybind11::handle projectData, const QString& path)
  895. {
  896. ProjectInfo projectInfo;
  897. projectInfo.m_needsBuild = false;
  898. if (!path.isEmpty())
  899. {
  900. projectInfo.m_path = path;
  901. }
  902. else
  903. {
  904. projectInfo.m_path = Py_To_String_Optional(projectData, "path", projectInfo.m_path);
  905. }
  906. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  907. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  908. projectInfo.m_version = Py_To_String_Optional(projectData, "version", projectInfo.m_version);
  909. projectInfo.m_id = Py_To_String_Optional(projectData, "project_id", projectInfo.m_id);
  910. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  911. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  912. projectInfo.m_requirements = Py_To_String_Optional(projectData, "requirements", projectInfo.m_requirements);
  913. projectInfo.m_license = Py_To_String_Optional(projectData, "license", projectInfo.m_license);
  914. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  915. projectInfo.m_engineName = Py_To_String_Optional(projectData, "engine", projectInfo.m_engineName);
  916. if (projectData.contains("user_tags"))
  917. {
  918. for (auto tag : projectData["user_tags"])
  919. {
  920. projectInfo.m_userTags.append(Py_To_String(tag));
  921. }
  922. }
  923. if (projectData.contains("gem_names"))
  924. {
  925. for (auto gem : projectData["gem_names"])
  926. {
  927. if (pybind11::isinstance<pybind11::dict>(gem))
  928. {
  929. if (gem["optional"].cast<bool>())
  930. {
  931. projectInfo.m_optionalGemDependencies.append(Py_To_String(gem["name"]));
  932. }
  933. else
  934. {
  935. projectInfo.m_requiredGemDependencies.append(Py_To_String(gem["name"]));
  936. }
  937. }
  938. else
  939. {
  940. projectInfo.m_requiredGemDependencies.append(Py_To_String(gem));
  941. }
  942. }
  943. }
  944. if (projectData.contains("engine_path"))
  945. {
  946. // Python looked for an engine path so we don't need to, but be careful
  947. // not to add 'None' in case no path was found
  948. if (!pybind11::isinstance<pybind11::none>(projectData["engine_path"]))
  949. {
  950. projectInfo.m_enginePath = Py_To_String(projectData["engine_path"]);
  951. }
  952. }
  953. else if (!projectInfo.m_path.isEmpty())
  954. {
  955. auto enginePathResult = m_manifest.attr("get_project_engine_path")(QString_To_Py_Path(projectInfo.m_path));
  956. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  957. {
  958. // request a posix path so it looks like what is in o3de_manifest.json
  959. projectInfo.m_enginePath = Py_To_String(enginePathResult.attr("as_posix")());
  960. }
  961. }
  962. return projectInfo;
  963. }
  964. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  965. {
  966. ProjectInfo projectInfo;
  967. projectInfo.m_path = Py_To_String(path);
  968. projectInfo.m_needsBuild = false;
  969. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  970. if (pybind11::isinstance<pybind11::dict>(projectData))
  971. {
  972. try
  973. {
  974. projectInfo = ProjectInfoFromDict(projectData, projectInfo.m_path);
  975. }
  976. catch ([[maybe_unused]] const std::exception& e)
  977. {
  978. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  979. }
  980. }
  981. return projectInfo;
  982. }
  983. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  984. {
  985. QVector<ProjectInfo> projects;
  986. bool result = ExecuteWithLock([&] {
  987. for (auto projectData : m_projectManagerInterface.attr("get_all_project_infos")())
  988. {
  989. if (pybind11::isinstance<pybind11::dict>(projectData))
  990. {
  991. projects.push_back(ProjectInfoFromDict(projectData));
  992. }
  993. }
  994. });
  995. if (!result)
  996. {
  997. return AZ::Failure();
  998. }
  999. else
  1000. {
  1001. return AZ::Success(AZStd::move(projects));
  1002. }
  1003. }
  1004. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForRepo(const QString& repoUri)
  1005. {
  1006. QVector<ProjectInfo> projects;
  1007. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1008. [&]
  1009. {
  1010. auto pyUri = QString_To_Py_String(repoUri);
  1011. auto pyProjects = m_repo.attr("get_project_json_data_from_cached_repo")(pyUri);
  1012. if (pybind11::isinstance<pybind11::list>(pyProjects))
  1013. {
  1014. for (auto pyProjectJsonData : pyProjects)
  1015. {
  1016. ProjectInfo projectInfo = ProjectInfoFromDict(pyProjectJsonData);
  1017. projectInfo.m_remote = true;
  1018. projects.push_back(projectInfo);
  1019. }
  1020. }
  1021. });
  1022. if (!result.IsSuccess())
  1023. {
  1024. return AZ::Failure(result.GetError());
  1025. }
  1026. return AZ::Success(AZStd::move(projects));
  1027. }
  1028. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForAllRepos()
  1029. {
  1030. QVector<ProjectInfo> projects;
  1031. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1032. [&]
  1033. {
  1034. auto pyProjects = m_repo.attr("get_project_json_data_from_all_cached_repos")();
  1035. if (pybind11::isinstance<pybind11::list>(pyProjects))
  1036. {
  1037. for (auto pyProjectJsonData : pyProjects)
  1038. {
  1039. ProjectInfo projectInfo = ProjectInfoFromDict(pyProjectJsonData);
  1040. projectInfo.m_remote = true;
  1041. projects.push_back(projectInfo);
  1042. }
  1043. }
  1044. });
  1045. if (!result.IsSuccess())
  1046. {
  1047. return AZ::Failure(result.GetError());
  1048. }
  1049. return AZ::Success(AZStd::move(projects));
  1050. }
  1051. IPythonBindings::DetailedOutcome PythonBindings::AddGemsToProject(const QStringList& gemPaths, const QStringList& gemNames, const QString& projectPath, bool force)
  1052. {
  1053. bool activateResult = false;
  1054. bool result = ExecuteWithLock(
  1055. [&]
  1056. {
  1057. using namespace pybind11::literals;
  1058. auto pythonActivateResult = m_projectManagerInterface.attr("add_gems_to_project")(
  1059. "gem_paths"_a = QStringList_To_Py_List(gemPaths),
  1060. "gem_names"_a = QStringList_To_Py_List(gemNames),
  1061. "project_path"_a = QString_To_Py_Path(projectPath),
  1062. "force"_a = force
  1063. );
  1064. // Returns an exit code so boolify it then invert result
  1065. activateResult = !pythonActivateResult.cast<bool>();
  1066. });
  1067. if (!result || !activateResult)
  1068. {
  1069. return AZ::Failure(GetErrorPair());
  1070. }
  1071. return AZ::Success();
  1072. }
  1073. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemName, const QString& projectPath)
  1074. {
  1075. return ExecuteWithLockErrorHandling(
  1076. [&]
  1077. {
  1078. using namespace pybind11::literals;
  1079. auto result = m_disableGemProject.attr("disable_gem_in_project")(
  1080. "gem_name"_a = QString_To_Py_String(gemName),
  1081. "project_path"_a = QString_To_Py_Path(projectPath)
  1082. );
  1083. // an error code of 1 indicates an error, error code 2 means the gem was not active to begin with
  1084. if (result.cast<int>() == 1)
  1085. {
  1086. throw std::runtime_error("Failed to remove gem");
  1087. }
  1088. });
  1089. }
  1090. bool PythonBindings::RemoveInvalidProjects()
  1091. {
  1092. bool removalResult = false;
  1093. bool result = ExecuteWithLock(
  1094. [&]
  1095. {
  1096. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  1097. // Returns an exit code so boolify it then invert result
  1098. removalResult = !pythonRemovalResult.cast<bool>();
  1099. });
  1100. return result && removalResult;
  1101. }
  1102. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  1103. {
  1104. bool updateProjectSucceeded = false;
  1105. auto result = ExecuteWithLockErrorHandling([&]
  1106. {
  1107. using namespace pybind11::literals;
  1108. std::list<std::string> newTags;
  1109. for (const auto& i : projectInfo.m_userTags)
  1110. {
  1111. newTags.push_back(i.toStdString());
  1112. }
  1113. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  1114. "proj_path"_a = QString_To_Py_Path(projectInfo.m_path),
  1115. "new_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  1116. "new_id"_a = QString_To_Py_String(projectInfo.m_id),
  1117. "new_origin"_a = QString_To_Py_String(projectInfo.m_origin),
  1118. "new_display"_a = QString_To_Py_String(projectInfo.m_displayName),
  1119. "new_summary"_a = QString_To_Py_String(projectInfo.m_summary),
  1120. "new_icon"_a = QString_To_Py_String(projectInfo.m_iconPath),
  1121. "replace_tags"_a = pybind11::list(pybind11::cast(newTags)),
  1122. "new_engine_name"_a = QString_To_Py_String(projectInfo.m_engineName),
  1123. "new_version"_a = QString_To_Py_String(projectInfo.m_version)
  1124. );
  1125. updateProjectSucceeded = (editResult.cast<int>() == 0);
  1126. // use the specific path locally until we have a UX for specifying the engine version
  1127. auto userEditResult = m_editProjectProperties.attr("edit_project_props")(
  1128. "proj_path"_a = QString_To_Py_Path(projectInfo.m_path),
  1129. "new_engine_path"_a = QString_To_Py_Path(projectInfo.m_enginePath),
  1130. "user"_a = true
  1131. );
  1132. updateProjectSucceeded &= (userEditResult.cast<int>() == 0);
  1133. });
  1134. if (!result.IsSuccess())
  1135. {
  1136. return result;
  1137. }
  1138. else if (!updateProjectSucceeded)
  1139. {
  1140. return AZ::Failure("Failed to update project.");
  1141. }
  1142. return AZ::Success();
  1143. }
  1144. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromDict(pybind11::handle templateData, const QString& path) const
  1145. {
  1146. ProjectTemplateInfo templateInfo(TemplateInfoFromDict(templateData, path));
  1147. if (templateInfo.IsValid())
  1148. {
  1149. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  1150. constexpr bool includeDependencies = false;
  1151. auto enabledGems = GetEnabledGems(templateProjectPath, includeDependencies);
  1152. if (enabledGems)
  1153. {
  1154. for (auto gemName : enabledGems.GetValue().keys())
  1155. {
  1156. // Exclude the template ${Name} placeholder for the list of included gems
  1157. // That Gem gets created with the project
  1158. if (!gemName.contains("${Name}"))
  1159. {
  1160. templateInfo.m_includedGems.push_back(gemName);
  1161. }
  1162. }
  1163. }
  1164. }
  1165. return templateInfo;
  1166. }
  1167. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path) const
  1168. {
  1169. ProjectTemplateInfo templateInfo(TemplateInfoFromPath(path));
  1170. if (templateInfo.IsValid())
  1171. {
  1172. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  1173. constexpr bool includeDependencies = false;
  1174. auto enabledGems = GetEnabledGems(templateProjectPath, includeDependencies);
  1175. if (enabledGems)
  1176. {
  1177. for (auto gemName : enabledGems.GetValue().keys())
  1178. {
  1179. // Exclude the template ${Name} placeholder for the list of included gems
  1180. // That Gem gets created with the project
  1181. if (!gemName.contains("${Name}"))
  1182. {
  1183. templateInfo.m_includedGems.push_back(gemName);
  1184. }
  1185. }
  1186. }
  1187. }
  1188. return templateInfo;
  1189. }
  1190. TemplateInfo PythonBindings::TemplateInfoFromDict(pybind11::handle data, const QString& path) const
  1191. {
  1192. TemplateInfo templateInfo;
  1193. if (!path.isEmpty())
  1194. {
  1195. templateInfo.m_path = path;
  1196. }
  1197. else
  1198. {
  1199. templateInfo.m_path = Py_To_String_Optional(data, "path", templateInfo.m_path);
  1200. }
  1201. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  1202. templateInfo.m_name = Py_To_String(data["template_name"]);
  1203. templateInfo.m_summary = Py_To_String(data["summary"]);
  1204. if (data.contains("canonical_tags"))
  1205. {
  1206. for (auto tag : data["canonical_tags"])
  1207. {
  1208. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  1209. }
  1210. }
  1211. if (data.contains("user_tags"))
  1212. {
  1213. for (auto tag : data["user_tags"])
  1214. {
  1215. templateInfo.m_userTags.push_back(Py_To_String(tag));
  1216. }
  1217. }
  1218. templateInfo.m_requirements = Py_To_String_Optional(data, "requirements", "");
  1219. templateInfo.m_license = Py_To_String_Optional(data, "license", "");
  1220. return templateInfo;
  1221. }
  1222. TemplateInfo PythonBindings::TemplateInfoFromPath(pybind11::handle path) const
  1223. {
  1224. TemplateInfo templateInfo;
  1225. templateInfo.m_path = Py_To_String(path);
  1226. using namespace pybind11::literals;
  1227. // no project path is needed when a template path is provided
  1228. auto data = m_manifest.attr("get_template_json_data")("template_path"_a = path);
  1229. if (pybind11::isinstance<pybind11::dict>(data))
  1230. {
  1231. try
  1232. {
  1233. templateInfo = TemplateInfoFromDict(data, Py_To_String(path));
  1234. }
  1235. catch ([[maybe_unused]] const std::exception& e)
  1236. {
  1237. AZ_Warning("PythonBindings", false, "Failed to get TemplateInfo for %s", Py_To_String(path));
  1238. }
  1239. }
  1240. return templateInfo;
  1241. }
  1242. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates()
  1243. {
  1244. QVector<ProjectTemplateInfo> templates;
  1245. bool result = ExecuteWithLock([&] {
  1246. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  1247. {
  1248. templates.push_back(ProjectTemplateInfoFromPath(path));
  1249. }
  1250. });
  1251. if (!result)
  1252. {
  1253. return AZ::Failure();
  1254. }
  1255. else
  1256. {
  1257. return AZ::Success(AZStd::move(templates));
  1258. }
  1259. }
  1260. AZ::Outcome<QVector<TemplateInfo>> PythonBindings::GetGemTemplates()
  1261. {
  1262. QVector<TemplateInfo> templates;
  1263. bool result = ExecuteWithLock(
  1264. [&]
  1265. {
  1266. for (auto path : m_manifest.attr("get_templates_for_gem_creation")())
  1267. {
  1268. templates.push_back(TemplateInfoFromPath(path));
  1269. }
  1270. });
  1271. if (!result)
  1272. {
  1273. return AZ::Failure();
  1274. }
  1275. else
  1276. {
  1277. return AZ::Success(AZStd::move(templates));
  1278. }
  1279. }
  1280. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplatesForRepo(const QString& repoUri) const
  1281. {
  1282. QVector<ProjectTemplateInfo> templates;
  1283. bool result = ExecuteWithLock(
  1284. [&]
  1285. {
  1286. using namespace pybind11::literals;
  1287. auto pyTemplates = m_repo.attr("get_template_json_data_from_cached_repo")(
  1288. "repo_uri"_a = QString_To_Py_String(repoUri)
  1289. );
  1290. if (pybind11::isinstance<pybind11::set>(pyTemplates))
  1291. {
  1292. for (auto pyTemplateJsonData : pyTemplates)
  1293. {
  1294. ProjectTemplateInfo remoteTemplate = TemplateInfoFromDict(pyTemplateJsonData);
  1295. remoteTemplate.m_isRemote = true;
  1296. templates.push_back(remoteTemplate);
  1297. }
  1298. }
  1299. });
  1300. if (!result)
  1301. {
  1302. return AZ::Failure();
  1303. }
  1304. else
  1305. {
  1306. return AZ::Success(AZStd::move(templates));
  1307. }
  1308. }
  1309. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplatesForAllRepos() const
  1310. {
  1311. QVector<ProjectTemplateInfo> templates;
  1312. bool result = ExecuteWithLock(
  1313. [&]
  1314. {
  1315. auto pyTemplates = m_repo.attr("get_template_json_data_from_all_cached_repos")();
  1316. if (pybind11::isinstance<pybind11::list>(pyTemplates))
  1317. {
  1318. for (auto pyTemplateJsonData : pyTemplates)
  1319. {
  1320. ProjectTemplateInfo remoteTemplate = ProjectTemplateInfoFromDict(pyTemplateJsonData);
  1321. remoteTemplate.m_isRemote = true;
  1322. templates.push_back(remoteTemplate);
  1323. }
  1324. }
  1325. });
  1326. if (!result)
  1327. {
  1328. return AZ::Failure();
  1329. }
  1330. else
  1331. {
  1332. return AZ::Success(AZStd::move(templates));
  1333. }
  1334. }
  1335. AZ::Outcome<void, AZStd::string> PythonBindings::RefreshGemRepo(const QString& repoUri)
  1336. {
  1337. bool refreshResult = false;
  1338. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1339. [&]
  1340. {
  1341. auto pyUri = QString_To_Py_String(repoUri);
  1342. auto pythonRefreshResult = m_repo.attr("refresh_repo")(pyUri);
  1343. // Returns an exit code so boolify it then invert result
  1344. refreshResult = !pythonRefreshResult.cast<bool>();
  1345. });
  1346. if (!result.IsSuccess())
  1347. {
  1348. return result;
  1349. }
  1350. else if (!refreshResult)
  1351. {
  1352. return AZ::Failure("Failed to refresh repo.");
  1353. }
  1354. return AZ::Success();
  1355. }
  1356. bool PythonBindings::RefreshAllGemRepos()
  1357. {
  1358. bool refreshResult = false;
  1359. bool result = ExecuteWithLock(
  1360. [&]
  1361. {
  1362. auto pythonRefreshResult = m_repo.attr("refresh_repos")();
  1363. // Returns an exit code so boolify it then invert result
  1364. refreshResult = !pythonRefreshResult.cast<bool>();
  1365. });
  1366. return result && refreshResult;
  1367. }
  1368. AZ::Outcome<QStringList, AZStd::string> PythonBindings::GetIncompatibleProjectGems(
  1369. const QStringList& gemPaths, const QStringList& gemNames, const QString& projectPath)
  1370. {
  1371. QStringList incompatibleGems;
  1372. bool result = ExecuteWithLock(
  1373. [&]
  1374. {
  1375. using namespace pybind11::literals;
  1376. auto incompatibleGemSet =
  1377. m_projectManagerInterface.attr("get_incompatible_project_gems")(
  1378. "gem_paths"_a = QStringList_To_Py_List(gemPaths),
  1379. "gem_names"_a = QStringList_To_Py_List(gemNames),
  1380. "project_path"_a = QString_To_Py_String(projectPath)
  1381. );
  1382. // We don't use a const ref here because pybind11 iterator
  1383. // returns a temp pybind11::handle so using a reference will cause
  1384. // a warning/error, and copying the handle is what we want to do
  1385. for (auto incompatibleGem : incompatibleGemSet)
  1386. {
  1387. incompatibleGems.push_back(Py_To_String(incompatibleGem));
  1388. }
  1389. });
  1390. if (!result)
  1391. {
  1392. return AZ::Failure("Failed to get incompatible gems for project");
  1393. }
  1394. return AZ::Success(incompatibleGems);
  1395. }
  1396. IPythonBindings::DetailedOutcome PythonBindings::AddGemRepo(const QString& repoUri)
  1397. {
  1398. bool registrationResult = false;
  1399. bool result = ExecuteWithLock(
  1400. [&]
  1401. {
  1402. using namespace pybind11::literals;
  1403. auto pythonRegistrationResult = m_register.attr("register")("repo_uri"_a = QString_To_Py_String(repoUri));
  1404. // Returns an exit code so boolify it then invert result
  1405. registrationResult = !pythonRegistrationResult.cast<bool>();
  1406. });
  1407. if (!result || !registrationResult)
  1408. {
  1409. return AZ::Failure(GetErrorPair());
  1410. }
  1411. return AZ::Success();
  1412. }
  1413. bool PythonBindings::RemoveGemRepo(const QString& repoUri)
  1414. {
  1415. bool registrationResult = false;
  1416. bool result = ExecuteWithLock(
  1417. [&]
  1418. {
  1419. using namespace pybind11::literals;
  1420. auto pythonRegistrationResult = m_register.attr("register")(
  1421. "engine_path"_a = pybind11::none(),
  1422. "project_path"_a = pybind11::none(),
  1423. "gem_path"_a = pybind11::none(),
  1424. "external_subdir_path"_a = pybind11::none(),
  1425. "template_path"_a = pybind11::none(),
  1426. "restricted_path"_a = pybind11::none(),
  1427. "repo_uri"_a = QString_To_Py_String(repoUri),
  1428. "default_engines_folder"_a = pybind11::none(),
  1429. "default_projects_folder"_a = pybind11::none(),
  1430. "default_gems_folder"_a = pybind11::none(),
  1431. "default_templates_folder"_a = pybind11::none(),
  1432. "default_restricted_folder"_a = pybind11::none(),
  1433. "default_third_party_folder"_a = pybind11::none(),
  1434. "external_subdir_engine_path"_a = pybind11::none(),
  1435. "external_subdir_project_path"_a = pybind11::none(),
  1436. "external_subdir_gem_path"_a = pybind11::none(),
  1437. "remove"_a = true,
  1438. "force"_a = false
  1439. );
  1440. // Returns an exit code so boolify it then invert result
  1441. registrationResult = !pythonRegistrationResult.cast<bool>();
  1442. });
  1443. return result && registrationResult;
  1444. }
  1445. GemRepoInfo PythonBindings::GetGemRepoInfo(pybind11::handle repoUri)
  1446. {
  1447. GemRepoInfo gemRepoInfo;
  1448. gemRepoInfo.m_repoUri = Py_To_String(repoUri);
  1449. auto data = m_manifest.attr("get_repo_json_data")(repoUri);
  1450. if (pybind11::isinstance<pybind11::dict>(data))
  1451. {
  1452. try
  1453. {
  1454. // required
  1455. gemRepoInfo.m_name = Py_To_String(data["repo_name"]);
  1456. gemRepoInfo.m_origin = Py_To_String(data["origin"]);
  1457. // optional
  1458. gemRepoInfo.m_summary = Py_To_String_Optional(data, "summary", "No summary provided.");
  1459. gemRepoInfo.m_additionalInfo = Py_To_String_Optional(data, "additional_info", "");
  1460. auto repoPath = m_manifest.attr("get_repo_path")(repoUri);
  1461. gemRepoInfo.m_path = gemRepoInfo.m_directoryLink = Py_To_String(repoPath);
  1462. QString lastUpdated = Py_To_String_Optional(data, "last_updated", "");
  1463. gemRepoInfo.m_lastUpdated = QDateTime::fromString(lastUpdated, RepoTimeFormat);
  1464. if (data.contains("enabled"))
  1465. {
  1466. gemRepoInfo.m_isEnabled = data["enabled"].cast<bool>();
  1467. }
  1468. else
  1469. {
  1470. gemRepoInfo.m_isEnabled = false;
  1471. }
  1472. if (data.contains("gems"))
  1473. {
  1474. for (auto gemPath : data["gems"])
  1475. {
  1476. gemRepoInfo.m_includedGemUris.push_back(Py_To_String(gemPath));
  1477. }
  1478. }
  1479. }
  1480. catch ([[maybe_unused]] const std::exception& e)
  1481. {
  1482. AZ_Warning("PythonBindings", false, "Failed to get GemRepoInfo for repo %s", Py_To_String(repoUri));
  1483. }
  1484. }
  1485. return gemRepoInfo;
  1486. }
  1487. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  1488. {
  1489. QVector<GemRepoInfo> gemRepos;
  1490. auto result = ExecuteWithLockErrorHandling(
  1491. [&]
  1492. {
  1493. for (auto repoUri : m_manifest.attr("get_manifest_repos")())
  1494. {
  1495. gemRepos.push_back(GetGemRepoInfo(repoUri));
  1496. }
  1497. });
  1498. if (!result.IsSuccess())
  1499. {
  1500. return AZ::Failure(result.GetError().c_str());
  1501. }
  1502. AZStd::sort(gemRepos.begin(), gemRepos.end());
  1503. return AZ::Success(AZStd::move(gemRepos));
  1504. }
  1505. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForRepo(const QString& repoUri)
  1506. {
  1507. QVector<GemInfo> gemInfos;
  1508. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1509. [&]
  1510. {
  1511. auto pyUri = QString_To_Py_String(repoUri);
  1512. auto pyGems = m_repo.attr("get_gem_json_data_from_cached_repo")(pyUri);
  1513. if (pybind11::isinstance<pybind11::list>(pyGems))
  1514. {
  1515. for (auto pyGemJsonData : pyGems)
  1516. {
  1517. GemInfo gemInfo;
  1518. GetGemInfoFromPyDict(gemInfo, pyGemJsonData.cast<pybind11::dict>());
  1519. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1520. gemInfo.m_gemOrigin = GemInfo::Remote;
  1521. gemInfos.push_back(AZStd::move(gemInfo));
  1522. }
  1523. }
  1524. });
  1525. if (!result.IsSuccess())
  1526. {
  1527. return AZ::Failure(result.GetError());
  1528. }
  1529. return AZ::Success(AZStd::move(gemInfos));
  1530. }
  1531. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForAllRepos(const QString& projectPath)
  1532. {
  1533. QVector<GemInfo> gems;
  1534. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1535. [&]
  1536. {
  1537. const auto pyProjectPath = QString_To_Py_Path(projectPath);
  1538. const auto gemInfos = m_projectManagerInterface.attr("get_gem_infos_from_all_repos")(pyProjectPath);
  1539. for (pybind11::handle pyGemJsonData : gemInfos)
  1540. {
  1541. GemInfo gemInfo;
  1542. GetGemInfoFromPyDict(gemInfo, pyGemJsonData.cast<pybind11::dict>());
  1543. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1544. gemInfo.m_gemOrigin = GemInfo::Remote;
  1545. gems.push_back(AZStd::move(gemInfo));
  1546. }
  1547. });
  1548. if (!result.IsSuccess())
  1549. {
  1550. return AZ::Failure(result.GetError());
  1551. }
  1552. return AZ::Success(AZStd::move(gems));
  1553. }
  1554. IPythonBindings::DetailedOutcome PythonBindings::DownloadGem(
  1555. const QString& gemName, const QString& path, std::function<void(int, int)> gemProgressCallback, bool force)
  1556. {
  1557. // This process is currently limited to download a single object at a time.
  1558. bool downloadSucceeded = false;
  1559. m_requestCancelDownload = false;
  1560. auto result = ExecuteWithLockErrorHandling(
  1561. [&]
  1562. {
  1563. auto downloadResult = m_download.attr("download_gem")(
  1564. QString_To_Py_String(gemName), // gem name
  1565. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1566. false, // skip auto register
  1567. force, // force overwrite
  1568. pybind11::cpp_function(
  1569. [this, gemProgressCallback](int bytesDownloaded, int totalBytes)
  1570. {
  1571. gemProgressCallback(bytesDownloaded, totalBytes);
  1572. return m_requestCancelDownload;
  1573. }) // Callback for download progress and cancelling
  1574. );
  1575. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1576. });
  1577. if (!result.IsSuccess())
  1578. {
  1579. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1580. return AZ::Failure(AZStd::move(pythonRunError));
  1581. }
  1582. else if (!downloadSucceeded)
  1583. {
  1584. return AZ::Failure(GetErrorPair());
  1585. }
  1586. return AZ::Success();
  1587. }
  1588. IPythonBindings::DetailedOutcome PythonBindings::DownloadProject(
  1589. const QString& projectName, const QString& path, std::function<void(int, int)> projectProgressCallback, bool force)
  1590. {
  1591. // This process is currently limited to download a single object at a time.
  1592. bool downloadSucceeded = false;
  1593. m_requestCancelDownload = false;
  1594. auto result = ExecuteWithLockErrorHandling(
  1595. [&]
  1596. {
  1597. auto downloadResult = m_download.attr("download_project")(
  1598. QString_To_Py_String(projectName), // gem name
  1599. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1600. false, // skip auto register
  1601. force, // force overwrite
  1602. pybind11::cpp_function(
  1603. [this, projectProgressCallback](int bytesDownloaded, int totalBytes)
  1604. {
  1605. projectProgressCallback(bytesDownloaded, totalBytes);
  1606. return m_requestCancelDownload;
  1607. }) // Callback for download progress and cancelling
  1608. );
  1609. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1610. });
  1611. if (!result.IsSuccess())
  1612. {
  1613. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1614. return AZ::Failure(AZStd::move(pythonRunError));
  1615. }
  1616. else if (!downloadSucceeded)
  1617. {
  1618. return AZ::Failure(GetErrorPair());
  1619. }
  1620. return AZ::Success();
  1621. }
  1622. IPythonBindings::DetailedOutcome PythonBindings::DownloadTemplate(
  1623. const QString& templateName, const QString& path, std::function<void(int, int)> templateProgressCallback, bool force)
  1624. {
  1625. // This process is currently limited to download a single object at a time.
  1626. bool downloadSucceeded = false;
  1627. m_requestCancelDownload = false;
  1628. auto result = ExecuteWithLockErrorHandling(
  1629. [&]
  1630. {
  1631. auto downloadResult = m_download.attr("download_template")(
  1632. QString_To_Py_String(templateName), // gem name
  1633. path.isEmpty() ? pybind11::none() : QString_To_Py_Path(path), // destination path
  1634. false, // skip auto register
  1635. force, // force overwrite
  1636. pybind11::cpp_function(
  1637. [this, templateProgressCallback](int bytesDownloaded, int totalBytes)
  1638. {
  1639. templateProgressCallback(bytesDownloaded, totalBytes);
  1640. return m_requestCancelDownload;
  1641. }) // Callback for download progress and cancelling
  1642. );
  1643. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1644. });
  1645. if (!result.IsSuccess())
  1646. {
  1647. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1648. return AZ::Failure(AZStd::move(pythonRunError));
  1649. }
  1650. else if (!downloadSucceeded)
  1651. {
  1652. return AZ::Failure(GetErrorPair());
  1653. }
  1654. return AZ::Success();
  1655. }
  1656. void PythonBindings::CancelDownload()
  1657. {
  1658. m_requestCancelDownload = true;
  1659. }
  1660. bool PythonBindings::IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated)
  1661. {
  1662. bool updateAvaliableResult = false;
  1663. bool result = ExecuteWithLock(
  1664. [&]
  1665. {
  1666. auto pyGemName = QString_To_Py_String(gemName);
  1667. auto pyLastUpdated = QString_To_Py_String(lastUpdated);
  1668. auto pythonUpdateAvaliableResult = m_download.attr("is_o3de_gem_update_available")(pyGemName, pyLastUpdated);
  1669. updateAvaliableResult = pythonUpdateAvaliableResult.cast<bool>();
  1670. });
  1671. return result && updateAvaliableResult;
  1672. }
  1673. IPythonBindings::ErrorPair PythonBindings::GetErrorPair()
  1674. {
  1675. if (const size_t errorSize = m_pythonErrorStrings.size())
  1676. {
  1677. AZStd::string detailedString =
  1678. errorSize == 1 ? "" : AZStd::accumulate(m_pythonErrorStrings.begin(), m_pythonErrorStrings.end(), AZStd::string(""));
  1679. return IPythonBindings::ErrorPair(m_pythonErrorStrings.front(), detailedString);
  1680. }
  1681. // If no error was found
  1682. else
  1683. {
  1684. return IPythonBindings::ErrorPair(AZStd::string("Unknown Python Bindings Error"), AZStd::string(""));
  1685. }
  1686. }
  1687. void PythonBindings::AddErrorString(AZStd::string errorString)
  1688. {
  1689. m_pythonErrorStrings.push_back(errorString);
  1690. }
  1691. } // namespace O3DE::ProjectManager