PythonBindings.cpp 76 KB

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