PythonBindings.cpp 78 KB

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