PythonBindings.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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/std/numeric.h>
  23. #include <AzCore/StringFunc/StringFunc.h>
  24. #include <QDir>
  25. namespace Platform
  26. {
  27. bool InsertPythonLibraryPath(
  28. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  29. {
  30. // append lib path to Python paths
  31. AZ::IO::FixedMaxPath libPath = engineRoot;
  32. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  33. libPath = libPath.LexicallyNormal();
  34. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  35. {
  36. paths.insert(libPath.c_str());
  37. return true;
  38. }
  39. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  40. return false;
  41. }
  42. // Implemented in each different platform's PAL implementation files, as it differs per platform.
  43. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  44. } // namespace Platform
  45. #define Py_To_String(obj) pybind11::str(obj).cast<std::string>().c_str()
  46. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  47. #define Py_To_Int(obj) obj.cast<int>()
  48. #define Py_To_Int_Optional(dict, key, default_int) dict.contains(key) ? Py_To_Int(dict[key]) : default_int
  49. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  50. #define QString_To_Py_Path(value) m_pathlib.attr("Path")(value.toStdString())
  51. namespace RedirectOutput
  52. {
  53. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  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, RedirectOutputFunc stdoutFunction, RedirectOutputFunc stderrFunction)
  179. {
  180. s_RedirectModule = module;
  181. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, stdoutFunction);
  182. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, stderrFunction);
  183. PySys_WriteStdout("RedirectOutput installed\n");
  184. }
  185. void Shutdown()
  186. {
  187. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  188. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  189. Py_XDECREF(s_RedirectModule);
  190. s_RedirectModule = nullptr;
  191. }
  192. } // namespace RedirectOutput
  193. namespace O3DE::ProjectManager
  194. {
  195. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  196. : m_enginePath(enginePath)
  197. {
  198. m_pythonStarted = StartPython();
  199. }
  200. PythonBindings::~PythonBindings()
  201. {
  202. StopPython();
  203. }
  204. void PythonBindings::OnStdOut(const char* msg)
  205. {
  206. AZ::Debug::Trace::Output("Python", msg);
  207. }
  208. void PythonBindings::OnStdError(const char* msg)
  209. {
  210. AZStd::string_view lastPythonError{ msg };
  211. if (constexpr AZStd::string_view pythonErrorPrefix = "ERROR:root:";
  212. lastPythonError.starts_with(pythonErrorPrefix))
  213. {
  214. lastPythonError = lastPythonError.substr(pythonErrorPrefix.size());
  215. }
  216. PythonBindingsInterface::Get()->AddErrorString(lastPythonError);
  217. AZ::Debug::Trace::Output("Python", msg);
  218. }
  219. bool PythonBindings::PythonStarted()
  220. {
  221. return m_pythonStarted && Py_IsInitialized();
  222. }
  223. bool PythonBindings::StartPython()
  224. {
  225. if (Py_IsInitialized())
  226. {
  227. AZ_Warning("python", false, "Python is already active");
  228. return m_pythonStarted;
  229. }
  230. m_pythonStarted = false;
  231. // set PYTHON_HOME
  232. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  233. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  234. {
  235. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  236. return false;
  237. }
  238. AZStd::wstring pyHomePath;
  239. AZStd::to_wstring(pyHomePath, pyBasePath);
  240. Py_SetPythonHome(pyHomePath.c_str());
  241. // display basic Python information
  242. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  243. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  244. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  245. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  246. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  247. try
  248. {
  249. // ignore system location for sites site-packages
  250. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  251. Py_IgnoreEnvironmentFlag = 1; // -E
  252. const bool initializeSignalHandlers = true;
  253. pybind11::initialize_interpreter(initializeSignalHandlers);
  254. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"), &PythonBindings::OnStdOut, &PythonBindings::OnStdError);
  255. // Acquire GIL before calling Python code
  256. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  257. pybind11::gil_scoped_acquire acquire;
  258. // sanity import check
  259. if (PyRun_SimpleString("import sys") != 0)
  260. {
  261. AZ_Assert(false, "Import sys failed");
  262. return false;
  263. }
  264. // import required modules
  265. m_cmake = pybind11::module::import("o3de.cmake");
  266. m_register = pybind11::module::import("o3de.register");
  267. m_manifest = pybind11::module::import("o3de.manifest");
  268. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  269. m_engineProperties = pybind11::module::import("o3de.engine_properties");
  270. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  271. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  272. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  273. m_download = pybind11::module::import("o3de.download");
  274. m_repo = pybind11::module::import("o3de.repo");
  275. m_pathlib = pybind11::module::import("pathlib");
  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. return !PyErr_Occurred();
  293. }
  294. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback)
  295. {
  296. if (!Py_IsInitialized())
  297. {
  298. return AZ::Failure<AZStd::string>("Python is not initialized");
  299. }
  300. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  301. pybind11::gil_scoped_release release;
  302. pybind11::gil_scoped_acquire acquire;
  303. ClearErrorStrings();
  304. try
  305. {
  306. executionCallback();
  307. }
  308. catch ([[maybe_unused]] const std::exception& e)
  309. {
  310. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  311. return AZ::Failure<AZStd::string>(e.what());
  312. }
  313. return AZ::Success();
  314. }
  315. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  316. {
  317. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  318. }
  319. EngineInfo PythonBindings::EngineInfoFromPath(pybind11::handle enginePath)
  320. {
  321. EngineInfo engineInfo;
  322. try
  323. {
  324. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  325. if (pybind11::isinstance<pybind11::dict>(engineData))
  326. {
  327. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  328. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  329. engineInfo.m_path = Py_To_String(enginePath);
  330. }
  331. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  332. if (pybind11::isinstance<pybind11::dict>(o3deData))
  333. {
  334. auto defaultGemsFolder = m_manifest.attr("get_o3de_gems_folder")();
  335. engineInfo.m_defaultGemsFolder = Py_To_String_Optional(o3deData, "default_gems_folder", Py_To_String(defaultGemsFolder));
  336. auto defaultProjectsFolder = m_manifest.attr("get_o3de_projects_folder")();
  337. engineInfo.m_defaultProjectsFolder = Py_To_String_Optional(o3deData, "default_projects_folder", Py_To_String(defaultProjectsFolder));
  338. auto defaultRestrictedFolder = m_manifest.attr("get_o3de_restricted_folder")();
  339. engineInfo.m_defaultRestrictedFolder = Py_To_String_Optional(o3deData, "default_restricted_folder", Py_To_String(defaultRestrictedFolder));
  340. auto defaultTemplatesFolder = m_manifest.attr("get_o3de_templates_folder")();
  341. engineInfo.m_defaultTemplatesFolder = Py_To_String_Optional(o3deData, "default_templates_folder", Py_To_String(defaultTemplatesFolder));
  342. auto defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")();
  343. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData, "default_third_party_folder", Py_To_String(defaultThirdPartyFolder));
  344. }
  345. // check if engine path is registered
  346. auto allEngines = m_manifest.attr("get_manifest_engines")();
  347. if (pybind11::isinstance<pybind11::list>(allEngines))
  348. {
  349. const AZ::IO::FixedMaxPath enginePathFixed(Py_To_String(enginePath));
  350. for (auto engine : allEngines)
  351. {
  352. AZ::IO::FixedMaxPath otherEnginePath(Py_To_String(engine));
  353. if (otherEnginePath.Compare(enginePathFixed) == 0)
  354. {
  355. engineInfo.m_registered = true;
  356. break;
  357. }
  358. }
  359. }
  360. }
  361. catch ([[maybe_unused]] const std::exception& e)
  362. {
  363. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  364. }
  365. return engineInfo;
  366. }
  367. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  368. {
  369. EngineInfo engineInfo;
  370. bool result = ExecuteWithLock([&] {
  371. auto enginePath = m_manifest.attr("get_this_engine_path")();
  372. engineInfo = EngineInfoFromPath(enginePath);
  373. });
  374. if (!result || !engineInfo.IsValid())
  375. {
  376. return AZ::Failure();
  377. }
  378. else
  379. {
  380. return AZ::Success(AZStd::move(engineInfo));
  381. }
  382. }
  383. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo(const QString& engineName)
  384. {
  385. EngineInfo engineInfo;
  386. bool result = ExecuteWithLock([&] {
  387. auto enginePathResult = m_manifest.attr("get_registered")(QString_To_Py_String(engineName));
  388. // if a valid registered object is not found None is returned
  389. if (!pybind11::isinstance<pybind11::none>(enginePathResult))
  390. {
  391. engineInfo = EngineInfoFromPath(enginePathResult);
  392. // it is possible an engine is registered in o3de_manifest.json but the engine.json is
  393. // missing or corrupt in which case we do not consider it a registered engine
  394. }
  395. });
  396. if (!result || !engineInfo.IsValid())
  397. {
  398. return AZ::Failure();
  399. }
  400. else
  401. {
  402. return AZ::Success(AZStd::move(engineInfo));
  403. }
  404. }
  405. IPythonBindings::DetailedOutcome PythonBindings::SetEngineInfo(const EngineInfo& engineInfo, bool force)
  406. {
  407. bool registrationSuccess = false;
  408. bool pythonSuccess = ExecuteWithLock([&] {
  409. EngineInfo currentEngine = EngineInfoFromPath(QString_To_Py_Path(engineInfo.m_path));
  410. // be kind to source control and avoid needlessly updating engine.json
  411. if (currentEngine.IsValid() &&
  412. (currentEngine.m_name.compare(engineInfo.m_name) != 0 || currentEngine.m_version.compare(engineInfo.m_version) != 0))
  413. {
  414. auto enginePropsResult = m_engineProperties.attr("edit_engine_props")(
  415. QString_To_Py_Path(engineInfo.m_path),
  416. pybind11::none(), // existing engine_name
  417. QString_To_Py_String(engineInfo.m_name),
  418. QString_To_Py_String(engineInfo.m_version)
  419. );
  420. if (enginePropsResult.cast<int>() != 0)
  421. {
  422. // do not proceed with registration
  423. return;
  424. }
  425. }
  426. auto result = m_register.attr("register")(
  427. QString_To_Py_Path(engineInfo.m_path),
  428. pybind11::none(), // project_path
  429. pybind11::none(), // gem_path
  430. pybind11::none(), // external_subdir_path
  431. pybind11::none(), // template_path
  432. pybind11::none(), // restricted_path
  433. pybind11::none(), // repo_uri
  434. pybind11::none(), // default_engines_folder
  435. QString_To_Py_Path(engineInfo.m_defaultProjectsFolder),
  436. QString_To_Py_Path(engineInfo.m_defaultGemsFolder),
  437. QString_To_Py_Path(engineInfo.m_defaultTemplatesFolder),
  438. pybind11::none(), // default_restricted_folder
  439. QString_To_Py_Path(engineInfo.m_thirdPartyPath),
  440. pybind11::none(), // external_subdir_engine_path
  441. pybind11::none(), // external_subdir_project_path
  442. false, // remove
  443. force
  444. );
  445. registrationSuccess = result.cast<int>() == 0;
  446. });
  447. if (pythonSuccess && registrationSuccess)
  448. {
  449. return AZ::Success();
  450. }
  451. return AZ::Failure<ErrorPair>(GetErrorPair());
  452. }
  453. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  454. {
  455. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  456. if (gemInfo.IsValid())
  457. {
  458. return AZ::Success(AZStd::move(gemInfo));
  459. }
  460. else
  461. {
  462. return AZ::Failure();
  463. }
  464. }
  465. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  466. {
  467. QVector<GemInfo> gems;
  468. auto result = ExecuteWithLockErrorHandling([&]
  469. {
  470. for (auto path : m_manifest.attr("get_engine_gems")())
  471. {
  472. gems.push_back(GemInfoFromPath(path, pybind11::none()));
  473. }
  474. });
  475. if (!result.IsSuccess())
  476. {
  477. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  478. }
  479. std::sort(gems.begin(), gems.end());
  480. return AZ::Success(AZStd::move(gems));
  481. }
  482. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  483. {
  484. QVector<GemInfo> gems;
  485. auto result = ExecuteWithLockErrorHandling([&]
  486. {
  487. auto pyProjectPath = QString_To_Py_Path(projectPath);
  488. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  489. {
  490. GemInfo gemInfo = GemInfoFromPath(path, pyProjectPath);
  491. // Mark as downloaded because this gem was registered with an existing directory
  492. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  493. gems.push_back(AZStd::move(gemInfo));
  494. }
  495. });
  496. if (!result.IsSuccess())
  497. {
  498. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  499. }
  500. std::sort(gems.begin(), gems.end());
  501. return AZ::Success(AZStd::move(gems));
  502. }
  503. AZ::Outcome<QVector<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath)
  504. {
  505. // Retrieve the path to the cmake file that lists the enabled gems.
  506. pybind11::str enabledGemsFilename;
  507. auto result = ExecuteWithLockErrorHandling([&]
  508. {
  509. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  510. pybind11::none(), // project_name
  511. QString_To_Py_Path(projectPath)); // project_path
  512. });
  513. if (!result.IsSuccess())
  514. {
  515. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  516. }
  517. // Retrieve the actual list of names from the cmake file.
  518. QVector<AZStd::string> gemNames;
  519. result = ExecuteWithLockErrorHandling([&]
  520. {
  521. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  522. for (auto gemName : pyGemNames)
  523. {
  524. gemNames.push_back(Py_To_String(gemName));
  525. }
  526. });
  527. if (!result.IsSuccess())
  528. {
  529. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  530. }
  531. return AZ::Success(AZStd::move(gemNames));
  532. }
  533. AZ::Outcome<void, AZStd::string> PythonBindings::GemRegistration(const QString& gemPath, const QString& projectPath, bool remove)
  534. {
  535. bool registrationResult = false;
  536. auto result = ExecuteWithLockErrorHandling(
  537. [&]
  538. {
  539. auto externalProjectPath = projectPath.isEmpty() ? pybind11::none() : QString_To_Py_Path(projectPath);
  540. auto pythonRegistrationResult = m_register.attr("register")(
  541. pybind11::none(), // engine_path
  542. pybind11::none(), // project_path
  543. QString_To_Py_Path(gemPath), // gem folder
  544. pybind11::none(), // external subdirectory
  545. pybind11::none(), // template_path
  546. pybind11::none(), // restricted folder
  547. pybind11::none(), // repo uri
  548. pybind11::none(), // default_engines_folder
  549. pybind11::none(), // default_projects_folder
  550. pybind11::none(), // default_gems_folder
  551. pybind11::none(), // default_templates_folder
  552. pybind11::none(), // default_restricted_folder
  553. pybind11::none(), // default_third_party_folder
  554. pybind11::none(), // external_subdir_engine_path
  555. externalProjectPath, // external_subdir_project_path
  556. remove // remove
  557. );
  558. // Returns an exit code so boolify it then invert result
  559. registrationResult = !pythonRegistrationResult.cast<bool>();
  560. });
  561. if (!result.IsSuccess())
  562. {
  563. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  564. }
  565. else if (!registrationResult)
  566. {
  567. return AZ::Failure<AZStd::string>(AZStd::string::format(
  568. "Failed to %s gem path %s", remove ? "unregister" : "register", gemPath.toUtf8().constData()));
  569. }
  570. return AZ::Success();
  571. }
  572. AZ::Outcome<void, AZStd::string> PythonBindings::RegisterGem(const QString& gemPath, const QString& projectPath)
  573. {
  574. return GemRegistration(gemPath, projectPath);
  575. }
  576. AZ::Outcome<void, AZStd::string> PythonBindings::UnregisterGem(const QString& gemPath, const QString& projectPath)
  577. {
  578. return GemRegistration(gemPath, projectPath, /*remove*/true);
  579. }
  580. bool PythonBindings::AddProject(const QString& path)
  581. {
  582. bool registrationResult = false;
  583. bool result = ExecuteWithLock(
  584. [&]
  585. {
  586. auto projectPath = QString_To_Py_Path(path);
  587. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  588. // Returns an exit code so boolify it then invert result
  589. registrationResult = !pythonRegistrationResult.cast<bool>();
  590. });
  591. return result && registrationResult;
  592. }
  593. bool PythonBindings::RemoveProject(const QString& path)
  594. {
  595. bool registrationResult = false;
  596. bool result = ExecuteWithLock(
  597. [&]
  598. {
  599. auto pythonRegistrationResult = m_register.attr("register")(
  600. pybind11::none(), // engine_path
  601. QString_To_Py_Path(path), // project_path
  602. pybind11::none(), // gem_path
  603. pybind11::none(), // external_subdir_path
  604. pybind11::none(), // template_path
  605. pybind11::none(), // restricted_path
  606. pybind11::none(), // repo_uri
  607. pybind11::none(), // default_engines_folder
  608. pybind11::none(), // default_projects_folder
  609. pybind11::none(), // default_gems_folder
  610. pybind11::none(), // default_templates_folder
  611. pybind11::none(), // default_restricted_folder
  612. pybind11::none(), // default_third_party_folder
  613. pybind11::none(), // external_subdir_engine_path
  614. pybind11::none(), // external_subdir_project_path
  615. true, // remove
  616. false // force
  617. );
  618. // Returns an exit code so boolify it then invert result
  619. registrationResult = !pythonRegistrationResult.cast<bool>();
  620. });
  621. return result && registrationResult;
  622. }
  623. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo, bool registerProject)
  624. {
  625. using namespace pybind11::literals;
  626. ProjectInfo createdProjectInfo;
  627. bool result = ExecuteWithLock([&] {
  628. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  629. auto createProjectResult = m_engineTemplate.attr("create_project")(
  630. "project_path"_a = projectPath,
  631. "project_name"_a = QString_To_Py_String(projectInfo.m_projectName),
  632. "template_path"_a = QString_To_Py_Path(projectTemplatePath),
  633. "no_register"_a = !registerProject
  634. );
  635. if (createProjectResult.cast<int>() == 0)
  636. {
  637. createdProjectInfo = ProjectInfoFromPath(projectPath);
  638. }
  639. });
  640. if (!result || !createdProjectInfo.IsValid())
  641. {
  642. return AZ::Failure();
  643. }
  644. else
  645. {
  646. return AZ::Success(AZStd::move(createdProjectInfo));
  647. }
  648. }
  649. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  650. {
  651. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  652. if (projectInfo.IsValid())
  653. {
  654. return AZ::Success(AZStd::move(projectInfo));
  655. }
  656. else
  657. {
  658. return AZ::Failure();
  659. }
  660. }
  661. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  662. {
  663. GemInfo gemInfo;
  664. gemInfo.m_path = Py_To_String(path);
  665. gemInfo.m_directoryLink = gemInfo.m_path;
  666. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  667. if (pybind11::isinstance<pybind11::dict>(data))
  668. {
  669. try
  670. {
  671. // required
  672. gemInfo.m_name = Py_To_String(data["gem_name"]);
  673. // optional
  674. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  675. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  676. gemInfo.m_version = Py_To_String_Optional(data, "version", gemInfo.m_version);
  677. gemInfo.m_lastUpdatedDate = Py_To_String_Optional(data, "last_updated", gemInfo.m_lastUpdatedDate);
  678. gemInfo.m_binarySizeInKB = Py_To_Int_Optional(data, "binary_size", gemInfo.m_binarySizeInKB);
  679. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  680. gemInfo.m_creator = Py_To_String_Optional(data, "origin", "");
  681. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  682. gemInfo.m_licenseText = Py_To_String_Optional(data, "license", "Unspecified License");
  683. gemInfo.m_licenseLink = Py_To_String_Optional(data, "license_url", "");
  684. gemInfo.m_repoUri = Py_To_String_Optional(data, "repo_uri", "");
  685. if (gemInfo.m_creator.contains("Open 3D Engine"))
  686. {
  687. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEngine;
  688. }
  689. else if (gemInfo.m_creator.contains("Amazon Web Services"))
  690. {
  691. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  692. }
  693. else if (data.contains("origin"))
  694. {
  695. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Remote;
  696. }
  697. // If no origin was provided this cannot be remote and would be specified if O3DE so it should be local
  698. else
  699. {
  700. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Local;
  701. }
  702. // As long Base Open3DEngine gems are installed before first startup non-remote gems will be downloaded
  703. if (gemInfo.m_gemOrigin != GemInfo::GemOrigin::Remote)
  704. {
  705. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::Downloaded;
  706. }
  707. if (data.contains("user_tags"))
  708. {
  709. for (auto tag : data["user_tags"])
  710. {
  711. gemInfo.m_features.push_back(Py_To_String(tag));
  712. }
  713. }
  714. if (data.contains("dependencies"))
  715. {
  716. for (auto dependency : data["dependencies"])
  717. {
  718. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  719. }
  720. }
  721. QString gemType = Py_To_String_Optional(data, "type", "");
  722. if (gemType == "Asset")
  723. {
  724. gemInfo.m_types |= GemInfo::Type::Asset;
  725. }
  726. if (gemType == "Code")
  727. {
  728. gemInfo.m_types |= GemInfo::Type::Code;
  729. }
  730. if (gemType == "Tool")
  731. {
  732. gemInfo.m_types |= GemInfo::Type::Tool;
  733. }
  734. }
  735. catch ([[maybe_unused]] const std::exception& e)
  736. {
  737. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  738. }
  739. }
  740. return gemInfo;
  741. }
  742. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  743. {
  744. ProjectInfo projectInfo;
  745. projectInfo.m_path = Py_To_String(path);
  746. projectInfo.m_needsBuild = false;
  747. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  748. if (pybind11::isinstance<pybind11::dict>(projectData))
  749. {
  750. try
  751. {
  752. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  753. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  754. projectInfo.m_id = Py_To_String_Optional(projectData, "project_id", projectInfo.m_id);
  755. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  756. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  757. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  758. if (projectData.contains("user_tags"))
  759. {
  760. for (auto tag : projectData["user_tags"])
  761. {
  762. projectInfo.m_userTags.append(Py_To_String(tag));
  763. }
  764. }
  765. }
  766. catch ([[maybe_unused]] const std::exception& e)
  767. {
  768. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  769. }
  770. }
  771. return projectInfo;
  772. }
  773. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  774. {
  775. QVector<ProjectInfo> projects;
  776. bool result = ExecuteWithLock([&] {
  777. // external projects
  778. for (auto path : m_manifest.attr("get_manifest_projects")())
  779. {
  780. projects.push_back(ProjectInfoFromPath(path));
  781. }
  782. // projects from the engine
  783. for (auto path : m_manifest.attr("get_engine_projects")())
  784. {
  785. projects.push_back(ProjectInfoFromPath(path));
  786. }
  787. });
  788. if (!result)
  789. {
  790. return AZ::Failure();
  791. }
  792. else
  793. {
  794. return AZ::Success(AZStd::move(projects));
  795. }
  796. }
  797. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForRepo(const QString& repoUri)
  798. {
  799. QVector<ProjectInfo> projects;
  800. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  801. [&]
  802. {
  803. auto pyUri = QString_To_Py_String(repoUri);
  804. auto projectPaths = m_repo.attr("get_project_json_paths_from_cached_repo")(pyUri);
  805. if (pybind11::isinstance<pybind11::set>(projectPaths))
  806. {
  807. for (auto path : projectPaths)
  808. {
  809. //auto cpath = Py_To_String(path);
  810. //AZ::Outcome<ProjectInfo> projectOutcome = GetProject(QString(cpath));
  811. //if (projectOutcome.IsSuccess())
  812. {
  813. //ProjectInfo projectInfo = projectOutcome.GetValue();
  814. ProjectInfo projectInfo = ProjectInfoFromPath(path);
  815. projectInfo.m_remote = true;
  816. // projectInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  817. projects.push_back(projectInfo);
  818. }
  819. }
  820. }
  821. });
  822. if (!result.IsSuccess())
  823. {
  824. return AZ::Failure(result.GetError());
  825. }
  826. return AZ::Success(AZStd::move(projects));
  827. }
  828. AZ::Outcome<QVector<ProjectInfo>, AZStd::string> PythonBindings::GetProjectsForAllRepos()
  829. {
  830. QVector<ProjectInfo> projectInfos;
  831. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  832. [&]
  833. {
  834. auto projectPaths = m_repo.attr("get_project_json_paths_from_all_cached_repos")();
  835. if (pybind11::isinstance<pybind11::set>(projectPaths))
  836. {
  837. for (auto path : projectPaths)
  838. {
  839. //AZ::Outcome<ProjectInfo> projectOutcome = GetProject(QString(Py_To_String(path)));
  840. //if (projectOutcome.IsSuccess())
  841. {
  842. // ProjectInfo projectInfo = projectOutcome.GetValue();
  843. ProjectInfo projectInfo = ProjectInfoFromPath(path);
  844. projectInfo.m_remote = true;
  845. // projectInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  846. projectInfos.push_back(projectInfo);
  847. }
  848. //GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  849. //gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  850. //projectInfos.push_back(gemInfo);
  851. }
  852. }
  853. });
  854. if (!result.IsSuccess())
  855. {
  856. return AZ::Failure(result.GetError());
  857. }
  858. return AZ::Success(AZStd::move(projectInfos));
  859. }
  860. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  861. {
  862. return ExecuteWithLockErrorHandling([&]
  863. {
  864. m_enableGemProject.attr("enable_gem_in_project")(
  865. pybind11::none(), // gem name not needed as path is provided
  866. QString_To_Py_Path(gemPath),
  867. pybind11::none(), // project name not needed as path is provided
  868. QString_To_Py_Path(projectPath)
  869. );
  870. });
  871. }
  872. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  873. {
  874. return ExecuteWithLockErrorHandling([&]
  875. {
  876. m_disableGemProject.attr("disable_gem_in_project")(
  877. pybind11::none(), // gem name not needed as path is provided
  878. QString_To_Py_Path(gemPath),
  879. pybind11::none(), // project name not needed as path is provided
  880. QString_To_Py_Path(projectPath)
  881. );
  882. });
  883. }
  884. bool PythonBindings::RemoveInvalidProjects()
  885. {
  886. bool removalResult = false;
  887. bool result = ExecuteWithLock(
  888. [&]
  889. {
  890. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  891. // Returns an exit code so boolify it then invert result
  892. removalResult = !pythonRemovalResult.cast<bool>();
  893. });
  894. return result && removalResult;
  895. }
  896. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  897. {
  898. bool updateProjectSucceeded = false;
  899. auto result = ExecuteWithLockErrorHandling([&]
  900. {
  901. std::list<std::string> newTags;
  902. for (const auto& i : projectInfo.m_userTags)
  903. {
  904. newTags.push_back(i.toStdString());
  905. }
  906. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  907. QString_To_Py_Path(projectInfo.m_path),
  908. pybind11::none(), // proj_name not used
  909. QString_To_Py_String(projectInfo.m_projectName),
  910. QString_To_Py_String(projectInfo.m_id),
  911. QString_To_Py_String(projectInfo.m_origin),
  912. QString_To_Py_String(projectInfo.m_displayName),
  913. QString_To_Py_String(projectInfo.m_summary),
  914. QString_To_Py_String(projectInfo.m_iconPath), // new_icon
  915. pybind11::none(), // add_tags not used
  916. pybind11::none(), // remove_tags not used
  917. pybind11::list(pybind11::cast(newTags)));
  918. updateProjectSucceeded = (editResult.cast<int>() == 0);
  919. });
  920. if (!result.IsSuccess())
  921. {
  922. return result;
  923. }
  924. else if (!updateProjectSucceeded)
  925. {
  926. return AZ::Failure<AZStd::string>("Failed to update project.");
  927. }
  928. return AZ::Success();
  929. }
  930. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  931. {
  932. ProjectTemplateInfo templateInfo;
  933. templateInfo.m_path = Py_To_String(path);
  934. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path, pyProjectPath);
  935. if (pybind11::isinstance<pybind11::dict>(data))
  936. {
  937. try
  938. {
  939. // required
  940. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  941. templateInfo.m_name = Py_To_String(data["template_name"]);
  942. templateInfo.m_summary = Py_To_String(data["summary"]);
  943. // optional
  944. if (data.contains("canonical_tags"))
  945. {
  946. for (auto tag : data["canonical_tags"])
  947. {
  948. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  949. }
  950. }
  951. if (data.contains("user_tags"))
  952. {
  953. for (auto tag : data["user_tags"])
  954. {
  955. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  956. }
  957. }
  958. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  959. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  960. if (enabledGemNames)
  961. {
  962. for (auto gem : enabledGemNames.GetValue())
  963. {
  964. // Exclude the template ${Name} placeholder for the list of included gems
  965. // That Gem gets created with the project
  966. if (!gem.contains("${Name}"))
  967. {
  968. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  969. }
  970. }
  971. }
  972. }
  973. catch ([[maybe_unused]] const std::exception& e)
  974. {
  975. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  976. }
  977. }
  978. return templateInfo;
  979. }
  980. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates(const QString& projectPath)
  981. {
  982. QVector<ProjectTemplateInfo> templates;
  983. bool result = ExecuteWithLock([&] {
  984. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  985. {
  986. templates.push_back(ProjectTemplateInfoFromPath(path, QString_To_Py_Path(projectPath)));
  987. }
  988. });
  989. if (!result)
  990. {
  991. return AZ::Failure();
  992. }
  993. else
  994. {
  995. return AZ::Success(AZStd::move(templates));
  996. }
  997. }
  998. AZ::Outcome<void, AZStd::string> PythonBindings::RefreshGemRepo(const QString& repoUri)
  999. {
  1000. bool refreshResult = false;
  1001. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1002. [&]
  1003. {
  1004. auto pyUri = QString_To_Py_String(repoUri);
  1005. auto pythonRefreshResult = m_repo.attr("refresh_repo")(pyUri);
  1006. // Returns an exit code so boolify it then invert result
  1007. refreshResult = !pythonRefreshResult.cast<bool>();
  1008. });
  1009. if (!result.IsSuccess())
  1010. {
  1011. return result;
  1012. }
  1013. else if (!refreshResult)
  1014. {
  1015. return AZ::Failure<AZStd::string>("Failed to refresh repo.");
  1016. }
  1017. return AZ::Success();
  1018. }
  1019. bool PythonBindings::RefreshAllGemRepos()
  1020. {
  1021. bool refreshResult = false;
  1022. bool result = ExecuteWithLock(
  1023. [&]
  1024. {
  1025. auto pythonRefreshResult = m_repo.attr("refresh_repos")();
  1026. // Returns an exit code so boolify it then invert result
  1027. refreshResult = !pythonRefreshResult.cast<bool>();
  1028. });
  1029. return result && refreshResult;
  1030. }
  1031. IPythonBindings::DetailedOutcome PythonBindings::AddGemRepo(const QString& repoUri)
  1032. {
  1033. bool registrationResult = false;
  1034. bool result = ExecuteWithLock(
  1035. [&]
  1036. {
  1037. auto pyUri = QString_To_Py_String(repoUri);
  1038. auto pythonRegistrationResult = m_register.attr("register")(
  1039. pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pybind11::none(), pyUri);
  1040. // Returns an exit code so boolify it then invert result
  1041. registrationResult = !pythonRegistrationResult.cast<bool>();
  1042. });
  1043. if (!result || !registrationResult)
  1044. {
  1045. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1046. }
  1047. return AZ::Success();
  1048. }
  1049. bool PythonBindings::RemoveGemRepo(const QString& repoUri)
  1050. {
  1051. bool registrationResult = false;
  1052. bool result = ExecuteWithLock(
  1053. [&]
  1054. {
  1055. auto pythonRegistrationResult = m_register.attr("register")(
  1056. pybind11::none(), // engine_path
  1057. pybind11::none(), // project_path
  1058. pybind11::none(), // gem_path
  1059. pybind11::none(), // external_subdir_path
  1060. pybind11::none(), // template_path
  1061. pybind11::none(), // restricted_path
  1062. QString_To_Py_String(repoUri), // repo_uri
  1063. pybind11::none(), // default_engines_folder
  1064. pybind11::none(), // default_projects_folder
  1065. pybind11::none(), // default_gems_folder
  1066. pybind11::none(), // default_templates_folder
  1067. pybind11::none(), // default_restricted_folder
  1068. pybind11::none(), // default_third_party_folder
  1069. pybind11::none(), // external_subdir_engine_path
  1070. pybind11::none(), // external_subdir_project_path
  1071. true, // remove
  1072. false // force
  1073. );
  1074. // Returns an exit code so boolify it then invert result
  1075. registrationResult = !pythonRegistrationResult.cast<bool>();
  1076. });
  1077. return result && registrationResult;
  1078. }
  1079. GemRepoInfo PythonBindings::GetGemRepoInfo(pybind11::handle repoUri)
  1080. {
  1081. GemRepoInfo gemRepoInfo;
  1082. gemRepoInfo.m_repoUri = Py_To_String(repoUri);
  1083. auto data = m_manifest.attr("get_repo_json_data")(repoUri);
  1084. if (pybind11::isinstance<pybind11::dict>(data))
  1085. {
  1086. try
  1087. {
  1088. // required
  1089. gemRepoInfo.m_repoUri = Py_To_String(data["repo_uri"]);
  1090. gemRepoInfo.m_name = Py_To_String(data["repo_name"]);
  1091. gemRepoInfo.m_creator = Py_To_String(data["origin"]);
  1092. // optional
  1093. gemRepoInfo.m_summary = Py_To_String_Optional(data, "summary", "No summary provided.");
  1094. gemRepoInfo.m_additionalInfo = Py_To_String_Optional(data, "additional_info", "");
  1095. auto repoPath = m_manifest.attr("get_repo_path")(repoUri);
  1096. gemRepoInfo.m_path = gemRepoInfo.m_directoryLink = Py_To_String(repoPath);
  1097. QString lastUpdated = Py_To_String_Optional(data, "last_updated", "");
  1098. gemRepoInfo.m_lastUpdated = QDateTime::fromString(lastUpdated, RepoTimeFormat);
  1099. if (data.contains("enabled"))
  1100. {
  1101. gemRepoInfo.m_isEnabled = data["enabled"].cast<bool>();
  1102. }
  1103. else
  1104. {
  1105. gemRepoInfo.m_isEnabled = false;
  1106. }
  1107. if (data.contains("gems"))
  1108. {
  1109. for (auto gemPath : data["gems"])
  1110. {
  1111. gemRepoInfo.m_includedGemUris.push_back(Py_To_String(gemPath));
  1112. }
  1113. }
  1114. }
  1115. catch ([[maybe_unused]] const std::exception& e)
  1116. {
  1117. AZ_Warning("PythonBindings", false, "Failed to get GemRepoInfo for repo %s", Py_To_String(repoUri));
  1118. }
  1119. }
  1120. return gemRepoInfo;
  1121. }
  1122. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  1123. {
  1124. QVector<GemRepoInfo> gemRepos;
  1125. auto result = ExecuteWithLockErrorHandling(
  1126. [&]
  1127. {
  1128. for (auto repoUri : m_manifest.attr("get_manifest_repos")())
  1129. {
  1130. gemRepos.push_back(GetGemRepoInfo(repoUri));
  1131. }
  1132. });
  1133. if (!result.IsSuccess())
  1134. {
  1135. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  1136. }
  1137. std::sort(gemRepos.begin(), gemRepos.end());
  1138. return AZ::Success(AZStd::move(gemRepos));
  1139. }
  1140. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForRepo(const QString& repoUri)
  1141. {
  1142. QVector<GemInfo> gemInfos;
  1143. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1144. [&]
  1145. {
  1146. auto pyUri = QString_To_Py_String(repoUri);
  1147. auto gemPaths = m_repo.attr("get_gem_json_paths_from_cached_repo")(pyUri);
  1148. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1149. {
  1150. for (auto path : gemPaths)
  1151. {
  1152. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1153. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1154. gemInfos.push_back(gemInfo);
  1155. }
  1156. }
  1157. });
  1158. if (!result.IsSuccess())
  1159. {
  1160. return AZ::Failure(result.GetError());
  1161. }
  1162. return AZ::Success(AZStd::move(gemInfos));
  1163. }
  1164. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetGemInfosForAllRepos()
  1165. {
  1166. QVector<GemInfo> gemInfos;
  1167. AZ::Outcome<void, AZStd::string> result = ExecuteWithLockErrorHandling(
  1168. [&]
  1169. {
  1170. auto gemPaths = m_repo.attr("get_gem_json_paths_from_all_cached_repos")();
  1171. if (pybind11::isinstance<pybind11::set>(gemPaths))
  1172. {
  1173. for (auto path : gemPaths)
  1174. {
  1175. GemInfo gemInfo = GemInfoFromPath(path, pybind11::none());
  1176. gemInfo.m_downloadStatus = GemInfo::DownloadStatus::NotDownloaded;
  1177. gemInfos.push_back(gemInfo);
  1178. }
  1179. }
  1180. });
  1181. if (!result.IsSuccess())
  1182. {
  1183. return AZ::Failure(result.GetError());
  1184. }
  1185. return AZ::Success(AZStd::move(gemInfos));
  1186. }
  1187. IPythonBindings::DetailedOutcome PythonBindings::DownloadGem(
  1188. const QString& gemName, std::function<void(int, int)> gemProgressCallback, bool force)
  1189. {
  1190. // This process is currently limited to download a single gem at a time.
  1191. bool downloadSucceeded = false;
  1192. m_requestCancelDownload = false;
  1193. auto result = ExecuteWithLockErrorHandling(
  1194. [&]
  1195. {
  1196. auto downloadResult = m_download.attr("download_gem")(
  1197. QString_To_Py_String(gemName), // gem name
  1198. pybind11::none(), // destination path
  1199. false, // skip auto register
  1200. force, // force overwrite
  1201. pybind11::cpp_function(
  1202. [this, gemProgressCallback](int bytesDownloaded, int totalBytes)
  1203. {
  1204. gemProgressCallback(bytesDownloaded, totalBytes);
  1205. return m_requestCancelDownload;
  1206. }) // Callback for download progress and cancelling
  1207. );
  1208. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1209. });
  1210. if (!result.IsSuccess())
  1211. {
  1212. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1213. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1214. }
  1215. else if (!downloadSucceeded)
  1216. {
  1217. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1218. }
  1219. return AZ::Success();
  1220. }
  1221. IPythonBindings::DetailedOutcome PythonBindings::DownloadProject(
  1222. const QString& projectName, std::function<void(int, int)> projectProgressCallback, bool force)
  1223. {
  1224. // This process is currently limited to download a single gem at a time.
  1225. bool downloadSucceeded = false;
  1226. m_requestCancelDownload = false;
  1227. auto result = ExecuteWithLockErrorHandling(
  1228. [&]
  1229. {
  1230. auto downloadResult = m_download.attr("download_project")(
  1231. QString_To_Py_String(projectName), // gem name
  1232. pybind11::none(), // destination path
  1233. false, // skip auto register
  1234. force, // force overwrite
  1235. pybind11::cpp_function(
  1236. [this, projectProgressCallback](int bytesDownloaded, int totalBytes)
  1237. {
  1238. projectProgressCallback(bytesDownloaded, totalBytes);
  1239. return m_requestCancelDownload;
  1240. }) // Callback for download progress and cancelling
  1241. );
  1242. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1243. });
  1244. if (!result.IsSuccess())
  1245. {
  1246. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1247. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1248. }
  1249. else if (!downloadSucceeded)
  1250. {
  1251. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1252. }
  1253. return AZ::Success();
  1254. }
  1255. IPythonBindings::DetailedOutcome PythonBindings::DownloadTemplate(
  1256. const QString& templateName, std::function<void(int, int)> templateProgressCallback, bool force)
  1257. {
  1258. // This process is currently limited to download a single gem at a time.
  1259. bool downloadSucceeded = false;
  1260. m_requestCancelDownload = false;
  1261. auto result = ExecuteWithLockErrorHandling(
  1262. [&]
  1263. {
  1264. auto downloadResult = m_download.attr("download_template")(
  1265. QString_To_Py_String(templateName), // gem name
  1266. pybind11::none(), // destination path
  1267. false, // skip auto register
  1268. force, // force overwrite
  1269. pybind11::cpp_function(
  1270. [this, templateProgressCallback](int bytesDownloaded, int totalBytes)
  1271. {
  1272. templateProgressCallback(bytesDownloaded, totalBytes);
  1273. return m_requestCancelDownload;
  1274. }) // Callback for download progress and cancelling
  1275. );
  1276. downloadSucceeded = (downloadResult.cast<int>() == 0);
  1277. });
  1278. if (!result.IsSuccess())
  1279. {
  1280. IPythonBindings::ErrorPair pythonRunError(result.GetError(), result.GetError());
  1281. return AZ::Failure<IPythonBindings::ErrorPair>(AZStd::move(pythonRunError));
  1282. }
  1283. else if (!downloadSucceeded)
  1284. {
  1285. return AZ::Failure<IPythonBindings::ErrorPair>(GetErrorPair());
  1286. }
  1287. return AZ::Success();
  1288. }
  1289. void PythonBindings::CancelDownload()
  1290. {
  1291. m_requestCancelDownload = true;
  1292. }
  1293. bool PythonBindings::IsGemUpdateAvaliable(const QString& gemName, const QString& lastUpdated)
  1294. {
  1295. bool updateAvaliableResult = false;
  1296. bool result = ExecuteWithLock(
  1297. [&]
  1298. {
  1299. auto pyGemName = QString_To_Py_String(gemName);
  1300. auto pyLastUpdated = QString_To_Py_String(lastUpdated);
  1301. auto pythonUpdateAvaliableResult = m_download.attr("is_o3de_gem_update_available")(pyGemName, pyLastUpdated);
  1302. updateAvaliableResult = pythonUpdateAvaliableResult.cast<bool>();
  1303. });
  1304. return result && updateAvaliableResult;
  1305. }
  1306. IPythonBindings::ErrorPair PythonBindings::GetErrorPair()
  1307. {
  1308. if (const size_t errorSize = m_pythonErrorStrings.size())
  1309. {
  1310. AZStd::string detailedString =
  1311. errorSize == 1 ? "" : AZStd::accumulate(m_pythonErrorStrings.begin(), m_pythonErrorStrings.end(), AZStd::string(""));
  1312. return IPythonBindings::ErrorPair(m_pythonErrorStrings.front(), detailedString);
  1313. }
  1314. // If no error was found
  1315. else
  1316. {
  1317. return IPythonBindings::ErrorPair(AZStd::string("Unknown Python Bindings Error"), AZStd::string(""));
  1318. }
  1319. }
  1320. void PythonBindings::AddErrorString(AZStd::string errorString)
  1321. {
  1322. m_pythonErrorStrings.push_back(errorString);
  1323. }
  1324. void PythonBindings::ClearErrorStrings()
  1325. {
  1326. m_pythonErrorStrings.clear();
  1327. }
  1328. } // namespace O3DE::ProjectManager