PythonBindings.cpp 78 KB

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