3
0

PythonBindings.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  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. projectInfo.m_restricted = Py_To_String_Optional(projectData, "restricted", projectInfo.m_restricted);
  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