PythonBindings.cpp 78 KB

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