PythonBindings.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <PythonBindings.h>
  9. #include <ProjectManagerDefs.h>
  10. // Qt defines slots, which interferes with the use here.
  11. #pragma push_macro("slots")
  12. #undef slots
  13. #include <pybind11/functional.h>
  14. #include <pybind11/embed.h>
  15. #include <pybind11/eval.h>
  16. #include <pybind11/stl.h>
  17. #pragma pop_macro("slots")
  18. #include <AzCore/IO/FileIO.h>
  19. #include <AzCore/IO/SystemFile.h>
  20. #include <AzCore/std/containers/unordered_set.h>
  21. #include <AzCore/std/string/conversions.h>
  22. #include <AzCore/StringFunc/StringFunc.h>
  23. #include <QDir>
  24. namespace Platform
  25. {
  26. bool InsertPythonLibraryPath(
  27. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  28. {
  29. // append lib path to Python paths
  30. AZ::IO::FixedMaxPath libPath = engineRoot;
  31. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  32. libPath = libPath.LexicallyNormal();
  33. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  34. {
  35. paths.insert(libPath.c_str());
  36. return true;
  37. }
  38. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  39. return false;
  40. }
  41. // Implemented in each different platform's PAL implementation files, as it differs per platform.
  42. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  43. } // namespace Platform
  44. #define Py_To_String(obj) pybind11::str(obj).cast<std::string>().c_str()
  45. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  46. #define Py_To_Int(obj) obj.cast<int>()
  47. #define Py_To_Int_Optional(dict, key, default_int) dict.contains(key) ? Py_To_Int(dict[key]) : default_int
  48. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  49. #define QString_To_Py_Path(value) m_pathlib.attr("Path")(value.toStdString())
  50. namespace RedirectOutput
  51. {
  52. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  53. AZStd::string lastPythonError;
  54. struct RedirectOutput
  55. {
  56. PyObject_HEAD RedirectOutputFunc write;
  57. };
  58. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  59. {
  60. std::size_t written(0);
  61. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  62. if (selfimpl->write)
  63. {
  64. char* data;
  65. if (!PyArg_ParseTuple(args, "s", &data))
  66. {
  67. return PyLong_FromSize_t(0);
  68. }
  69. selfimpl->write(data);
  70. written = strlen(data);
  71. }
  72. return PyLong_FromSize_t(written);
  73. }
  74. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  75. {
  76. // no-op
  77. return Py_BuildValue("");
  78. }
  79. PyMethodDef RedirectMethods[] = {
  80. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  81. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  82. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  83. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  84. {0, 0, 0, 0} // sentinel
  85. };
  86. PyTypeObject RedirectOutputType = {
  87. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  88. sizeof(RedirectOutput), /* tp_basicsize */
  89. 0, /* tp_itemsize */
  90. 0, /* tp_dealloc */
  91. 0, /* tp_print */
  92. 0, /* tp_getattr */
  93. 0, /* tp_setattr */
  94. 0, /* tp_reserved */
  95. 0, /* tp_repr */
  96. 0, /* tp_as_number */
  97. 0, /* tp_as_sequence */
  98. 0, /* tp_as_mapping */
  99. 0, /* tp_hash */
  100. 0, /* tp_call */
  101. 0, /* tp_str */
  102. 0, /* tp_getattro */
  103. 0, /* tp_setattro */
  104. 0, /* tp_as_buffer */
  105. Py_TPFLAGS_DEFAULT, /* tp_flags */
  106. "azlmbr_redirect objects", /* tp_doc */
  107. 0, /* tp_traverse */
  108. 0, /* tp_clear */
  109. 0, /* tp_richcompare */
  110. 0, /* tp_weaklistoffset */
  111. 0, /* tp_iter */
  112. 0, /* tp_iternext */
  113. RedirectMethods, /* tp_methods */
  114. 0, /* tp_members */
  115. 0, /* tp_getset */
  116. 0, /* tp_base */
  117. 0, /* tp_dict */
  118. 0, /* tp_descr_get */
  119. 0, /* tp_descr_set */
  120. 0, /* tp_dictoffset */
  121. 0, /* tp_init */
  122. 0, /* tp_alloc */
  123. 0 /* tp_new */
  124. };
  125. PyModuleDef RedirectOutputModule = {
  126. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  127. };
  128. // Internal state
  129. PyObject* g_redirect_stdout = nullptr;
  130. PyObject* g_redirect_stdout_saved = nullptr;
  131. PyObject* g_redirect_stderr = nullptr;
  132. PyObject* g_redirect_stderr_saved = nullptr;
  133. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  134. {
  135. g_redirect_stdout = nullptr;
  136. g_redirect_stdout_saved = nullptr;
  137. g_redirect_stderr = nullptr;
  138. g_redirect_stderr_saved = nullptr;
  139. RedirectOutputType.tp_new = PyType_GenericNew;
  140. if (PyType_Ready(&RedirectOutputType) < 0)
  141. {
  142. return 0;
  143. }
  144. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  145. if (redirectModule)
  146. {
  147. Py_INCREF(&RedirectOutputType);
  148. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  149. }
  150. return redirectModule;
  151. }
  152. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  153. {
  154. if (PyType_Ready(&RedirectOutputType) < 0)
  155. {
  156. AZ_Warning("python", false, "RedirectOutputType not ready!");
  157. return;
  158. }
  159. if (!current)
  160. {
  161. saved = PySys_GetObject(funcname); // borrowed
  162. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  163. }
  164. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  165. redirectOutput->write = func;
  166. PySys_SetObject(funcname, current);
  167. }
  168. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  169. {
  170. if (current)
  171. {
  172. PySys_SetObject(funcname, saved);
  173. }
  174. Py_XDECREF(current);
  175. current = nullptr;
  176. }
  177. PyObject* s_RedirectModule = nullptr;
  178. void Intialize(PyObject* module)
  179. {
  180. s_RedirectModule = module;
  181. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, []([[maybe_unused]] const char* msg) {
  182. AZ_TracePrintf("Python", msg);
  183. });
  184. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) {
  185. if (lastPythonError.empty())
  186. {
  187. lastPythonError = msg;
  188. const int lengthOfErrorPrefix = 11;
  189. auto errorPrefix = lastPythonError.find("ERROR:root:");
  190. if (errorPrefix != AZStd::string::npos)
  191. {
  192. lastPythonError.erase(errorPrefix, lengthOfErrorPrefix);
  193. }
  194. }
  195. AZ_TracePrintf("Python", msg);
  196. });
  197. PySys_WriteStdout("RedirectOutput installed");
  198. }
  199. void Shutdown()
  200. {
  201. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  202. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  203. Py_XDECREF(s_RedirectModule);
  204. s_RedirectModule = nullptr;
  205. }
  206. } // namespace RedirectOutput
  207. namespace O3DE::ProjectManager
  208. {
  209. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  210. : m_enginePath(enginePath)
  211. {
  212. m_pythonStarted = StartPython();
  213. }
  214. PythonBindings::~PythonBindings()
  215. {
  216. StopPython();
  217. }
  218. bool PythonBindings::PythonStarted()
  219. {
  220. return m_pythonStarted && Py_IsInitialized();
  221. }
  222. bool PythonBindings::StartPython()
  223. {
  224. if (Py_IsInitialized())
  225. {
  226. AZ_Warning("python", false, "Python is already active");
  227. return m_pythonStarted;
  228. }
  229. m_pythonStarted = false;
  230. // set PYTHON_HOME
  231. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  232. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  233. {
  234. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  235. return false;
  236. }
  237. AZStd::wstring pyHomePath;
  238. AZStd::to_wstring(pyHomePath, pyBasePath);
  239. Py_SetPythonHome(pyHomePath.c_str());
  240. // display basic Python information
  241. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  242. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  243. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  244. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  245. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  246. try
  247. {
  248. // ignore system location for sites site-packages
  249. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  250. Py_IgnoreEnvironmentFlag = 1; // -E
  251. const bool initializeSignalHandlers = true;
  252. pybind11::initialize_interpreter(initializeSignalHandlers);
  253. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  254. // Acquire GIL before calling Python code
  255. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  256. pybind11::gil_scoped_acquire acquire;
  257. // sanity import check
  258. if (PyRun_SimpleString("import sys") != 0)
  259. {
  260. AZ_Assert(false, "Import sys failed");
  261. return false;
  262. }
  263. // import required modules
  264. m_cmake = pybind11::module::import("o3de.cmake");
  265. m_register = pybind11::module::import("o3de.register");
  266. m_manifest = pybind11::module::import("o3de.manifest");
  267. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  268. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  269. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  270. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  271. m_download = pybind11::module::import("o3de.download");
  272. m_repo = pybind11::module::import("o3de.repo");
  273. m_pathlib = pybind11::module::import("pathlib");
  274. // make sure the engine is registered
  275. RegisterThisEngine();
  276. m_pythonStarted = !PyErr_Occurred();
  277. return m_pythonStarted;
  278. }
  279. catch ([[maybe_unused]] const std::exception& e)
  280. {
  281. AZ_Assert(false, "Py_Initialize() failed with %s", e.what());
  282. return false;
  283. }
  284. }
  285. bool PythonBindings::StopPython()
  286. {
  287. if (Py_IsInitialized())
  288. {
  289. RedirectOutput::Shutdown();
  290. pybind11::finalize_interpreter();
  291. }
  292. else
  293. {
  294. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  295. }
  296. return !PyErr_Occurred();
  297. }
  298. bool PythonBindings::RegisterThisEngine()
  299. {
  300. bool registrationResult = true; // already registered is considered successful
  301. bool pythonResult = ExecuteWithLock(
  302. [&]
  303. {
  304. // check current engine path against all other registered engines
  305. // to see if we are already registered
  306. auto allEngines = m_manifest.attr("get_engines")();
  307. if (pybind11::isinstance<pybind11::list>(allEngines))
  308. {
  309. for (auto engine : allEngines)
  310. {
  311. AZ::IO::FixedMaxPath enginePath(Py_To_String(engine));
  312. if (enginePath.Compare(m_enginePath) == 0)
  313. {
  314. return;
  315. }
  316. }
  317. }
  318. auto result = m_register.attr("register")(QString_To_Py_Path(QString(m_enginePath.c_str())));
  319. registrationResult = (result.cast<int>() == 0);
  320. });
  321. bool finalResult = (registrationResult && pythonResult);
  322. AZ_Assert(finalResult, "Registration of this engine failed!");
  323. return finalResult;
  324. }
  325. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback)
  326. {
  327. if (!Py_IsInitialized())
  328. {
  329. return AZ::Failure<AZStd::string>("Python is not initialized");
  330. }
  331. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  332. pybind11::gil_scoped_release release;
  333. pybind11::gil_scoped_acquire acquire;
  334. try
  335. {
  336. executionCallback();
  337. }
  338. catch ([[maybe_unused]] const std::exception& e)
  339. {
  340. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  341. return AZ::Failure<AZStd::string>(e.what());
  342. }
  343. return AZ::Success();
  344. }
  345. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  346. {
  347. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  348. }
  349. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  350. {
  351. EngineInfo engineInfo;
  352. bool result = ExecuteWithLock([&] {
  353. auto enginePath = m_manifest.attr("get_this_engine_path")();
  354. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  355. if (pybind11::isinstance<pybind11::dict>(o3deData))
  356. {
  357. engineInfo.m_path = Py_To_String(enginePath);
  358. auto defaultGemsFolder = m_manifest.attr("get_o3de_gems_folder")();
  359. engineInfo.m_defaultGemsFolder = Py_To_String_Optional(o3deData, "default_gems_folder", Py_To_String(defaultGemsFolder));
  360. auto defaultProjectsFolder = m_manifest.attr("get_o3de_projects_folder")();
  361. engineInfo.m_defaultProjectsFolder = Py_To_String_Optional(o3deData, "default_projects_folder", Py_To_String(defaultProjectsFolder));
  362. auto defaultRestrictedFolder = m_manifest.attr("get_o3de_restricted_folder")();
  363. engineInfo.m_defaultRestrictedFolder = Py_To_String_Optional(o3deData, "default_restricted_folder", Py_To_String(defaultRestrictedFolder));
  364. auto defaultTemplatesFolder = m_manifest.attr("get_o3de_templates_folder")();
  365. engineInfo.m_defaultTemplatesFolder = Py_To_String_Optional(o3deData, "default_templates_folder", Py_To_String(defaultTemplatesFolder));
  366. auto defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")();
  367. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData, "default_third_party_folder", Py_To_String(defaultThirdPartyFolder));
  368. }
  369. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  370. if (pybind11::isinstance<pybind11::dict>(engineData))
  371. {
  372. try
  373. {
  374. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  375. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  376. }
  377. catch ([[maybe_unused]] const std::exception& e)
  378. {
  379. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  380. }
  381. }
  382. });
  383. if (!result || !engineInfo.IsValid())
  384. {
  385. return AZ::Failure();
  386. }
  387. else
  388. {
  389. return AZ::Success(AZStd::move(engineInfo));
  390. }
  391. }
  392. bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo)
  393. {
  394. bool result = ExecuteWithLock([&] {
  395. auto registrationResult = m_register.attr("register")(
  396. QString_To_Py_Path(engineInfo.m_path),
  397. pybind11::none(), // project_path
  398. pybind11::none(), // gem_path
  399. pybind11::none(), // external_subdir_path
  400. pybind11::none(), // template_path
  401. pybind11::none(), // restricted_path
  402. pybind11::none(), // repo_uri
  403. pybind11::none(), // default_engines_folder
  404. QString_To_Py_Path(engineInfo.m_defaultProjectsFolder),
  405. QString_To_Py_Path(engineInfo.m_defaultGemsFolder),
  406. QString_To_Py_Path(engineInfo.m_defaultTemplatesFolder),
  407. pybind11::none(), // default_restricted_folder
  408. QString_To_Py_Path(engineInfo.m_thirdPartyPath)
  409. );
  410. if (registrationResult.cast<int>() != 0)
  411. {
  412. result = false;
  413. }
  414. });
  415. return result;
  416. }
  417. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  418. {
  419. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  420. if (gemInfo.IsValid())
  421. {
  422. return AZ::Success(AZStd::move(gemInfo));
  423. }
  424. else
  425. {
  426. return AZ::Failure();
  427. }
  428. }
  429. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  430. {
  431. QVector<GemInfo> gems;
  432. auto result = ExecuteWithLockErrorHandling([&]
  433. {
  434. for (auto path : m_manifest.attr("get_engine_gems")())
  435. {
  436. gems.push_back(GemInfoFromPath(path, pybind11::none()));
  437. }
  438. });
  439. if (!result.IsSuccess())
  440. {
  441. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  442. }
  443. std::sort(gems.begin(), gems.end());
  444. return AZ::Success(AZStd::move(gems));
  445. }
  446. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  447. {
  448. QVector<GemInfo> gems;
  449. auto result = ExecuteWithLockErrorHandling([&]
  450. {
  451. auto pyProjectPath = QString_To_Py_Path(projectPath);
  452. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  453. {
  454. GemInfo gemInfo = GemInfoFromPath(path, pyProjectPath);
  455. // Mark as downloaded because this gem was registered with an existing directory
  456. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  457. gems.push_back(AZStd::move(gemInfo));
  458. }
  459. });
  460. if (!result.IsSuccess())
  461. {
  462. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  463. }
  464. std::sort(gems.begin(), gems.end());
  465. return AZ::Success(AZStd::move(gems));
  466. }
  467. AZ::Outcome<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath)
  468. {
  469. // Retrieve the path to the cmake file that lists the enabled gems.
  470. pybind11::str enabledGemsFilename;
  471. auto result = ExecuteWithLockErrorHandling([&]
  472. {
  473. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  474. pybind11::none(), // project_name
  475. QString_To_Py_Path(projectPath)); // project_path
  476. });
  477. if (!result.IsSuccess())
  478. {
  479. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  480. }
  481. // Retrieve the actual list of names from the cmake file.
  482. QVector<AZStd::string> gemNames;
  483. result = ExecuteWithLockErrorHandling([&]
  484. {
  485. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  486. for (auto gemName : pyGemNames)
  487. {
  488. gemNames.push_back(Py_To_String(gemName));
  489. }
  490. });
  491. if (!result.IsSuccess())
  492. {
  493. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  494. }
  495. return AZ::Success(AZStd::move(gemNames));
  496. }
  497. AZ::Outcome<void, AZStd::string> PythonBindings::GemRegistration(const QString& gemPath, const QString& projectPath, bool remove)
  498. {
  499. bool registrationResult = false;
  500. auto result = ExecuteWithLockErrorHandling(
  501. [&]
  502. {
  503. auto externalProjectPath = projectPath.isEmpty() ? pybind11::none() : QString_To_Py_Path(projectPath);
  504. auto pythonRegistrationResult = m_register.attr("register")(
  505. pybind11::none(), // engine_path
  506. pybind11::none(), // project_path
  507. QString_To_Py_Path(gemPath), // gem folder
  508. pybind11::none(), // external subdirectory
  509. pybind11::none(), // template_path
  510. pybind11::none(), // restricted folder
  511. pybind11::none(), // repo uri
  512. pybind11::none(), // default_engines_folder
  513. pybind11::none(), // default_projects_folder
  514. pybind11::none(), // default_gems_folder
  515. pybind11::none(), // default_templates_folder
  516. pybind11::none(), // default_restricted_folder
  517. pybind11::none(), // default_third_party_folder
  518. pybind11::none(), // external_subdir_engine_path
  519. externalProjectPath, // external_subdir_project_path
  520. remove // remove
  521. );
  522. // Returns an exit code so boolify it then invert result
  523. registrationResult = !pythonRegistrationResult.cast<bool>();
  524. });
  525. if (!result.IsSuccess())
  526. {
  527. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  528. }
  529. else if (!registrationResult)
  530. {
  531. return AZ::Failure<AZStd::string>(AZStd::string::format(
  532. "Failed to %s gem path %s", remove ? "unregister" : "register", gemPath.toUtf8().constData()));
  533. }
  534. return AZ::Success();
  535. }
  536. AZ::Outcome<void, AZStd::string> PythonBindings::RegisterGem(const QString& gemPath, const QString& projectPath)
  537. {
  538. return GemRegistration(gemPath, projectPath);
  539. }
  540. AZ::Outcome<void, AZStd::string> PythonBindings::UnregisterGem(const QString& gemPath, const QString& projectPath)
  541. {
  542. return GemRegistration(gemPath, projectPath, /*remove*/true);
  543. }
  544. bool PythonBindings::AddProject(const QString& path)
  545. {
  546. bool registrationResult = false;
  547. bool result = ExecuteWithLock(
  548. [&]
  549. {
  550. auto projectPath = QString_To_Py_Path(path);
  551. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  552. // Returns an exit code so boolify it then invert result
  553. registrationResult = !pythonRegistrationResult.cast<bool>();
  554. });
  555. return result && registrationResult;
  556. }
  557. bool PythonBindings::RemoveProject(const QString& path)
  558. {
  559. bool registrationResult = false;
  560. bool result = ExecuteWithLock(
  561. [&]
  562. {
  563. auto pythonRegistrationResult = m_register.attr("register")(
  564. pybind11::none(), // engine_path
  565. QString_To_Py_Path(path), // project_path
  566. pybind11::none(), // gem_path
  567. pybind11::none(), // external_subdir_path
  568. pybind11::none(), // template_path
  569. pybind11::none(), // restricted_path
  570. pybind11::none(), // repo_uri
  571. pybind11::none(), // default_engines_folder
  572. pybind11::none(), // default_projects_folder
  573. pybind11::none(), // default_gems_folder
  574. pybind11::none(), // default_templates_folder
  575. pybind11::none(), // default_restricted_folder
  576. pybind11::none(), // default_third_party_folder
  577. pybind11::none(), // external_subdir_engine_path
  578. pybind11::none(), // external_subdir_project_path
  579. true, // remove
  580. false // force
  581. );
  582. // Returns an exit code so boolify it then invert result
  583. registrationResult = !pythonRegistrationResult.cast<bool>();
  584. });
  585. return result && registrationResult;
  586. }
  587. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  588. {
  589. ProjectInfo createdProjectInfo;
  590. bool result = ExecuteWithLock([&] {
  591. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  592. auto createProjectResult = m_engineTemplate.attr("create_project")(
  593. projectPath,
  594. QString_To_Py_String(projectInfo.m_projectName),
  595. QString_To_Py_Path(projectTemplatePath)
  596. );
  597. if (createProjectResult.cast<int>() == 0)
  598. {
  599. createdProjectInfo = ProjectInfoFromPath(projectPath);
  600. }
  601. });
  602. if (!result || !createdProjectInfo.IsValid())
  603. {
  604. return AZ::Failure();
  605. }
  606. else
  607. {
  608. return AZ::Success(AZStd::move(createdProjectInfo));
  609. }
  610. }
  611. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  612. {
  613. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  614. if (projectInfo.IsValid())
  615. {
  616. return AZ::Success(AZStd::move(projectInfo));
  617. }
  618. else
  619. {
  620. return AZ::Failure();
  621. }
  622. }
  623. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  624. {
  625. GemInfo gemInfo;
  626. gemInfo.m_path = Py_To_String(path);
  627. gemInfo.m_directoryLink = gemInfo.m_path;
  628. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  629. if (pybind11::isinstance<pybind11::dict>(data))
  630. {
  631. try
  632. {
  633. // required
  634. gemInfo.m_name = Py_To_String(data["gem_name"]);
  635. // optional
  636. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  637. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  638. gemInfo.m_version = Py_To_String_Optional(data, "version", gemInfo.m_version);
  639. gemInfo.m_lastUpdatedDate = Py_To_String_Optional(data, "last_updated", gemInfo.m_lastUpdatedDate);
  640. gemInfo.m_binarySizeInKB = Py_To_Int_Optional(data, "binary_size", gemInfo.m_binarySizeInKB);
  641. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  642. gemInfo.m_creator = Py_To_String_Optional(data, "origin", "");
  643. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  644. gemInfo.m_licenseText = Py_To_String_Optional(data, "license", "Unspecified License");
  645. gemInfo.m_licenseLink = Py_To_String_Optional(data, "license_url", "");
  646. gemInfo.m_repoUri = Py_To_String_Optional(data, "repo_uri", "");
  647. if (gemInfo.m_creator.contains("Open 3D Engine"))
  648. {
  649. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEngine;
  650. }
  651. else if (gemInfo.m_creator.contains("Amazon Web Services"))
  652. {
  653. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  654. }
  655. else if (data.contains("origin"))
  656. {
  657. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Remote;
  658. }
  659. // If no origin was provided this cannot be remote and would be specified if O3DE so it should be local
  660. else
  661. {
  662. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  663. }
  664. // As long Base Open3DEngine gems are installed before first startup non-remote gems will be downloaded
  665. if (gemInfo.m_gemOrigin != GemInfo::GemOrigin::Remote)
  666. {
  667. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  668. }
  669. if (data.contains("user_tags"))
  670. {
  671. for (auto tag : data["user_tags"])
  672. {
  673. gemInfo.m_features.push_back(Py_To_String(tag));
  674. }
  675. }
  676. if (data.contains("dependencies"))
  677. {
  678. for (auto dependency : data["dependencies"])
  679. {
  680. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  681. }
  682. }
  683. QString gemType = Py_To_String_Optional(data, "type", "");
  684. if (gemType == "Asset")
  685. {
  686. gemInfo.m_types |= GemInfo::Type::Asset;
  687. }
  688. if (gemType == "Code")
  689. {
  690. gemInfo.m_types |= GemInfo::Type::Code;
  691. }
  692. if (gemType == "Tool")
  693. {
  694. gemInfo.m_types |= GemInfo::Type::Tool;
  695. }
  696. }
  697. catch ([[maybe_unused]] const std::exception& e)
  698. {
  699. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  700. }
  701. }
  702. return gemInfo;
  703. }
  704. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  705. {
  706. ProjectInfo projectInfo;
  707. projectInfo.m_path = Py_To_String(path);
  708. projectInfo.m_needsBuild = false;
  709. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  710. if (pybind11::isinstance<pybind11::dict>(projectData))
  711. {
  712. try
  713. {
  714. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  715. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  716. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  717. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  718. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  719. if (projectData.contains("user_tags"))
  720. {
  721. for (auto tag : projectData["user_tags"])
  722. {
  723. projectInfo.m_userTags.append(Py_To_String(tag));
  724. }
  725. }
  726. }
  727. catch ([[maybe_unused]] const std::exception& e)
  728. {
  729. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  730. }
  731. }
  732. return projectInfo;
  733. }
  734. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  735. {
  736. QVector<ProjectInfo> projects;
  737. bool result = ExecuteWithLock([&] {
  738. // external projects
  739. for (auto path : m_manifest.attr("get_projects")())
  740. {
  741. projects.push_back(ProjectInfoFromPath(path));
  742. }
  743. // projects from the engine
  744. for (auto path : m_manifest.attr("get_engine_projects")())
  745. {
  746. projects.push_back(ProjectInfoFromPath(path));
  747. }
  748. });
  749. if (!result)
  750. {
  751. return AZ::Failure();
  752. }
  753. else
  754. {
  755. return AZ::Success(AZStd::move(projects));
  756. }
  757. }
  758. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  759. {
  760. return ExecuteWithLockErrorHandling([&]
  761. {
  762. m_enableGemProject.attr("enable_gem_in_project")(
  763. pybind11::none(), // gem name not needed as path is provided
  764. QString_To_Py_Path(gemPath),
  765. pybind11::none(), // project name not needed as path is provided
  766. QString_To_Py_Path(projectPath)
  767. );
  768. });
  769. }
  770. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  771. {
  772. return ExecuteWithLockErrorHandling([&]
  773. {
  774. m_disableGemProject.attr("disable_gem_in_project")(
  775. pybind11::none(), // gem name not needed as path is provided
  776. QString_To_Py_Path(gemPath),
  777. pybind11::none(), // project name not needed as path is provided
  778. QString_To_Py_Path(projectPath)
  779. );
  780. });
  781. }
  782. bool PythonBindings::RemoveInvalidProjects()
  783. {
  784. bool removalResult = false;
  785. bool result = ExecuteWithLock(
  786. [&]
  787. {
  788. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  789. // Returns an exit code so boolify it then invert result
  790. removalResult = !pythonRemovalResult.cast<bool>();
  791. });
  792. return result && removalResult;
  793. }
  794. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  795. {
  796. bool updateProjectSucceeded = false;
  797. auto result = ExecuteWithLockErrorHandling([&]
  798. {
  799. std::list<std::string> newTags;
  800. for (const auto& i : projectInfo.m_userTags)
  801. {
  802. newTags.push_back(i.toStdString());
  803. }
  804. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  805. QString_To_Py_Path(projectInfo.m_path),
  806. pybind11::none(), // proj_name not used
  807. QString_To_Py_String(projectInfo.m_projectName),
  808. QString_To_Py_String(projectInfo.m_origin),
  809. QString_To_Py_String(projectInfo.m_displayName),
  810. QString_To_Py_String(projectInfo.m_summary),
  811. QString_To_Py_String(projectInfo.m_iconPath), // new_icon
  812. pybind11::none(), // add_tags not used
  813. pybind11::none(), // remove_tags not used
  814. pybind11::list(pybind11::cast(newTags)));
  815. updateProjectSucceeded = (editResult.cast<int>() == 0);
  816. });
  817. if (!result.IsSuccess())
  818. {
  819. return result;
  820. }
  821. else if (!updateProjectSucceeded)
  822. {
  823. return AZ::Failure<AZStd::string>("Failed to update project.");
  824. }
  825. return AZ::Success();
  826. }
  827. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  828. {
  829. ProjectTemplateInfo templateInfo;
  830. templateInfo.m_path = Py_To_String(path);
  831. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path, pyProjectPath);
  832. if (pybind11::isinstance<pybind11::dict>(data))
  833. {
  834. try
  835. {
  836. // required
  837. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  838. templateInfo.m_name = Py_To_String(data["template_name"]);
  839. templateInfo.m_summary = Py_To_String(data["summary"]);
  840. // optional
  841. if (data.contains("canonical_tags"))
  842. {
  843. for (auto tag : data["canonical_tags"])
  844. {
  845. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  846. }
  847. }
  848. if (data.contains("user_tags"))
  849. {
  850. for (auto tag : data["user_tags"])
  851. {
  852. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  853. }
  854. }
  855. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  856. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  857. if (enabledGemNames)
  858. {
  859. for (auto gem : enabledGemNames.GetValue())
  860. {
  861. // Exclude the template ${Name} placeholder for the list of included gems
  862. // That Gem gets created with the project
  863. if (!gem.contains("${Name}"))
  864. {
  865. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  866. }
  867. }
  868. }
  869. }
  870. catch ([[maybe_unused]] const std::exception& e)
  871. {
  872. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  873. }
  874. }
  875. return templateInfo;
  876. }
  877. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates(const QString& projectPath)
  878. {
  879. QVector<ProjectTemplateInfo> templates;
  880. bool result = ExecuteWithLock([&] {
  881. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  882. {
  883. templates.push_back(ProjectTemplateInfoFromPath(path, QString_To_Py_Path(projectPath)));
  884. }
  885. });
  886. if (!result)
  887. {
  888. return AZ::Failure();
  889. }
  890. else
  891. {
  892. return AZ::Success(AZStd::move(templates));
  893. }
  894. }
  895. AZ::Outcome<void, AZStd::string> PythonBindings::RefreshGemRepo(const QString& repoUri)
  896. {
  897. bool refreshResult = false;
  898. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  899. [&]
  900. {
  901. auto pyUri = QString_To_Py_String(repoUri);
  902. auto pythonRefreshResult = m_repo.attr("refresh_repo")(pyUri);
  903. // Returns an exit code so boolify it then invert result
  904. refreshResult = !pythonRefreshResult.cast<bool>();
  905. });
  906. if (!result.IsSuccess())
  907. {
  908. return result;
  909. }
  910. else if (!refreshResult)
  911. {
  912. return AZ::Failure<AZStd::string>("Failed to refresh repo.");
  913. }
  914. return AZ::Success();
  915. }
  916. bool PythonBindings::RefreshAllGemRepos()
  917. {
  918. bool refreshResult = false;
  919. bool result = ExecuteWithLock(
  920. [&]
  921. {
  922. auto pythonRefreshResult = m_repo.attr("refresh_repos")();
  923. // Returns an exit code so boolify it then invert result
  924. refreshResult = !pythonRefreshResult.cast<bool>();
  925. });
  926. return result && refreshResult;
  927. }
  928. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemRepo(const QString& repoUri)
  929. {
  930. bool registrationResult = false;
  931. bool result = ExecuteWithLock(
  932. [&]
  933. {
  934. RedirectOutput::lastPythonError.clear();
  935. auto pyUri = QString_To_Py_String(repoUri);
  936. auto pythonRegistrationResult = m_register.attr("register")(
  937. pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pyUri);
  938. // Returns an exit code so boolify it then invert result
  939. registrationResult = !pythonRegistrationResult.cast<bool>();
  940. });
  941. if (!result || !registrationResult)
  942. {
  943. return AZ::Failure<AZStd::string>(AZStd::move(RedirectOutput::lastPythonError));
  944. }
  945. return AZ::Success();
  946. }
  947. bool PythonBindings::RemoveGemRepo(const QString& repoUri)
  948. {
  949. bool registrationResult = false;
  950. bool result = ExecuteWithLock(
  951. [&]
  952. {
  953. auto pythonRegistrationResult = m_register.attr("register")(
  954. pybind11::none(), // engine_path
  955. pybind11::none(), // project_path
  956. pybind11::none(), // gem_path
  957. pybind11::none(), // external_subdir_path
  958. pybind11::none(), // template_path
  959. pybind11::none(), // restricted_path
  960. QString_To_Py_String(repoUri), // repo_uri
  961. pybind11::none(), // default_engines_folder
  962. pybind11::none(), // default_projects_folder
  963. pybind11::none(), // default_gems_folder
  964. pybind11::none(), // default_templates_folder
  965. pybind11::none(), // default_restricted_folder
  966. pybind11::none(), // default_third_party_folder
  967. pybind11::none(), // external_subdir_engine_path
  968. pybind11::none(), // external_subdir_project_path
  969. true, // remove
  970. false // force
  971. );
  972. // Returns an exit code so boolify it then invert result
  973. registrationResult = !pythonRegistrationResult.cast<bool>();
  974. });
  975. return result && registrationResult;
  976. }
  977. GemRepoInfo PythonBindings::GetGemRepoInfo(pybind11::handle repoUri)
  978. {
  979. GemRepoInfo gemRepoInfo;
  980. gemRepoInfo.m_repoUri = Py_To_String(repoUri);
  981. auto data = m_manifest.attr("get_repo_json_data")(repoUri);
  982. if (pybind11::isinstance<pybind11::dict>(data))
  983. {
  984. try
  985. {
  986. // required
  987. gemRepoInfo.m_repoUri = Py_To_String(data["repo_uri"]);
  988. gemRepoInfo.m_name = Py_To_String(data["repo_name"]);
  989. gemRepoInfo.m_creator = Py_To_String(data["origin"]);
  990. // optional
  991. gemRepoInfo.m_summary = Py_To_String_Optional(data, "summary", "No summary provided.");
  992. gemRepoInfo.m_additionalInfo = Py_To_String_Optional(data, "additional_info", "");
  993. auto repoPath = m_manifest.attr("get_repo_path")(repoUri);
  994. gemRepoInfo.m_path = gemRepoInfo.m_directoryLink = Py_To_String(repoPath);
  995. QString lastUpdated = Py_To_String_Optional(data, "last_updated", "");
  996. gemRepoInfo.m_lastUpdated = QDateTime::fromString(lastUpdated, RepoTimeFormat);
  997. if (data.contains("enabled"))
  998. {
  999. gemRepoInfo.m_isEnabled = data["enabled"].cast<bool>();
  1000. }
  1001. else
  1002. {
  1003. gemRepoInfo.m_isEnabled = false;
  1004. }
  1005. if (data.contains("gem_paths"))
  1006. {
  1007. for (auto gemPath : data["gem_paths"])
  1008. {
  1009. gemRepoInfo.m_includedGemPaths.push_back(Py_To_String(gemPath));
  1010. }
  1011. }
  1012. }
  1013. catch ([[maybe_unused]] const std::exception& e)
  1014. {
  1015. AZ_Warning("PythonBindings", false, "Failed to get GemRepoInfo for repo %s", Py_To_String(repoUri));
  1016. }
  1017. }
  1018. return gemRepoInfo;
  1019. }
  1020. //#define MOCK_GEM_REPO_INFO true
  1021. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  1022. {
  1023. QVector<GemRepoInfo> gemRepos;
  1024. #ifndef MOCK_GEM_REPO_INFO
  1025. auto result = ExecuteWithLockErrorHandling(
  1026. [&]
  1027. {
  1028. for (auto repoUri : m_manifest.attr("get_repos")())
  1029. {
  1030. gemRepos.push_back(GetGemRepoInfo(repoUri));
  1031. }
  1032. });
  1033. if (!result.IsSuccess())
  1034. {
  1035. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  1036. }
  1037. #else
  1038. GemRepoInfo mockJohnRepo("JohnCreates", "John Smith", QDateTime(QDate(2021, 8, 31), QTime(11, 57)), true);
  1039. mockJohnRepo.m_summary = "John's Summary. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sollicitudin dapibus urna";
  1040. mockJohnRepo.m_repoUri = "https://github.com/o3de/o3de";
  1041. mockJohnRepo.m_additionalInfo = "John's additional info. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sollicitu.";
  1042. gemRepos.push_back(mockJohnRepo);
  1043. GemRepoInfo mockJaneRepo("JanesGems", "Jane Doe", QDateTime(QDate(2021, 9, 10), QTime(18, 23)), false);
  1044. mockJaneRepo.m_summary = "Jane's Summary.";
  1045. mockJaneRepo.m_repoUri = "https://github.com/o3de/o3de.org";
  1046. gemRepos.push_back(mockJaneRepo);
  1047. #endif // MOCK_GEM_REPO_INFO
  1048. std::sort(gemRepos.begin(), gemRepos.end());
  1049. return AZ::Success(AZStd::move(gemRepos));
  1050. }
  1051. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemRepoGemsInfos()
  1052. {
  1053. QVector<GemInfo> gemInfos;
  1054. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1055. [&]
  1056. {
  1057. auto gemPaths = m_repo.attr("get_gem_json_paths_from_all_cached_repos")();
  1058. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1059. {
  1060. for (auto path : gemPaths)
  1061. {
  1062. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1063. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1064. gemInfos.push_back(gemInfo);
  1065. }
  1066. }
  1067. });
  1068. if (!result.IsSuccess())
  1069. {
  1070. return AZ::Failure(result.GetError());
  1071. }
  1072. return AZ::Success(AZStd::move(gemInfos));
  1073. }
  1074. AZ::Outcome<void, AZStd::string> PythonBindings::DownloadGem(
  1075. const QString& gemName, std::function<void(int, int)> gemProgressCallback, bool force)
  1076. {
  1077. // This process is currently limited to download a single gem at a time.
  1078. bool downloadSucceeded = false;
  1079. m_requestCancelDownload = false;
  1080. auto result = ExecuteWithLockErrorHandling(
  1081. [&]
  1082. {
  1083. RedirectOutput::lastPythonError.clear();
  1084. auto downloadResult = m_download.attr("download_gem")(
  1085. QString_To_Py_String(gemName), // gem name
  1086. pybind11::none(), // destination path
  1087. false, // skip auto register
  1088. force, // force overwrite
  1089. pybind11::cpp_function(
  1090. [this, gemProgressCallback](int bytesDownloaded, int totalBytes)
  1091. {
  1092. gemProgressCallback(bytesDownloaded, totalBytes);
  1093. return m_requestCancelDownload;
  1094. }) // Callback for download progress and cancelling
  1095. );
  1096. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1097. });
  1098. if (!result.IsSuccess())
  1099. {
  1100. return result;
  1101. }
  1102. else if (!downloadSucceeded)
  1103. {
  1104. return AZ::Failure<AZStd::string>(AZStd::move(RedirectOutput::lastPythonError));
  1105. }
  1106. return AZ::Success();
  1107. }
  1108. void PythonBindings::CancelDownload()
  1109. {
  1110. m_requestCancelDownload = true;
  1111. }
  1112. bool PythonBindings::IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated)
  1113. {
  1114. bool updateAvaliableResult = false;
  1115. bool result = ExecuteWithLock(
  1116. [&]
  1117. {
  1118. auto pyGemName = QString_To_Py_String(gemName);
  1119. auto pyLastUpdated = QString_To_Py_String(lastUpdated);
  1120. auto pythonUpdateAvaliableResult = m_download.attr("is_o3de_gem_update_available")(pyGemName, pyLastUpdated);
  1121. updateAvaliableResult = pythonUpdateAvaliableResult.cast<bool>();
  1122. });
  1123. return result && updateAvaliableResult;
  1124. }
  1125. }