PythonBindings.cpp 70 KB

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