PythonBindings.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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/string/conversions.h>
  21. #include <AzCore/StringFunc/StringFunc.h>
  22. #include <QDir>
  23. namespace Platform
  24. {
  25. bool InsertPythonLibraryPath(
  26. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  27. {
  28. // append lib path to Python paths
  29. AZ::IO::FixedMaxPath libPath = engineRoot;
  30. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  31. libPath = libPath.LexicallyNormal();
  32. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  33. {
  34. paths.insert(libPath.c_str());
  35. return true;
  36. }
  37. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  38. return false;
  39. }
  40. // Implemented in each different platform's PAL implementation files, as it differs per platform.
  41. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  42. } // namespace Platform
  43. #define Py_To_String(obj) pybind11::str(obj).cast<std::string>().c_str()
  44. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  45. #define QString_To_Py_String(value) pybind11::str(value.toStdString())
  46. #define QString_To_Py_Path(value) m_pathlib.attr("Path")(value.toStdString())
  47. namespace RedirectOutput
  48. {
  49. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  50. struct RedirectOutput
  51. {
  52. PyObject_HEAD RedirectOutputFunc write;
  53. };
  54. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  55. {
  56. std::size_t written(0);
  57. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  58. if (selfimpl->write)
  59. {
  60. char* data;
  61. if (!PyArg_ParseTuple(args, "s", &data))
  62. {
  63. return PyLong_FromSize_t(0);
  64. }
  65. selfimpl->write(data);
  66. written = strlen(data);
  67. }
  68. return PyLong_FromSize_t(written);
  69. }
  70. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  71. {
  72. // no-op
  73. return Py_BuildValue("");
  74. }
  75. PyMethodDef RedirectMethods[] = {
  76. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  77. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  78. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  79. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  80. {0, 0, 0, 0} // sentinel
  81. };
  82. PyTypeObject RedirectOutputType = {
  83. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  84. sizeof(RedirectOutput), /* tp_basicsize */
  85. 0, /* tp_itemsize */
  86. 0, /* tp_dealloc */
  87. 0, /* tp_print */
  88. 0, /* tp_getattr */
  89. 0, /* tp_setattr */
  90. 0, /* tp_reserved */
  91. 0, /* tp_repr */
  92. 0, /* tp_as_number */
  93. 0, /* tp_as_sequence */
  94. 0, /* tp_as_mapping */
  95. 0, /* tp_hash */
  96. 0, /* tp_call */
  97. 0, /* tp_str */
  98. 0, /* tp_getattro */
  99. 0, /* tp_setattro */
  100. 0, /* tp_as_buffer */
  101. Py_TPFLAGS_DEFAULT, /* tp_flags */
  102. "azlmbr_redirect objects", /* tp_doc */
  103. 0, /* tp_traverse */
  104. 0, /* tp_clear */
  105. 0, /* tp_richcompare */
  106. 0, /* tp_weaklistoffset */
  107. 0, /* tp_iter */
  108. 0, /* tp_iternext */
  109. RedirectMethods, /* tp_methods */
  110. 0, /* tp_members */
  111. 0, /* tp_getset */
  112. 0, /* tp_base */
  113. 0, /* tp_dict */
  114. 0, /* tp_descr_get */
  115. 0, /* tp_descr_set */
  116. 0, /* tp_dictoffset */
  117. 0, /* tp_init */
  118. 0, /* tp_alloc */
  119. 0 /* tp_new */
  120. };
  121. PyModuleDef RedirectOutputModule = {
  122. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  123. };
  124. // Internal state
  125. PyObject* g_redirect_stdout = nullptr;
  126. PyObject* g_redirect_stdout_saved = nullptr;
  127. PyObject* g_redirect_stderr = nullptr;
  128. PyObject* g_redirect_stderr_saved = nullptr;
  129. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  130. {
  131. g_redirect_stdout = nullptr;
  132. g_redirect_stdout_saved = nullptr;
  133. g_redirect_stderr = nullptr;
  134. g_redirect_stderr_saved = nullptr;
  135. RedirectOutputType.tp_new = PyType_GenericNew;
  136. if (PyType_Ready(&RedirectOutputType) < 0)
  137. {
  138. return 0;
  139. }
  140. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  141. if (redirectModule)
  142. {
  143. Py_INCREF(&RedirectOutputType);
  144. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  145. }
  146. return redirectModule;
  147. }
  148. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  149. {
  150. if (PyType_Ready(&RedirectOutputType) < 0)
  151. {
  152. AZ_Warning("python", false, "RedirectOutputType not ready!");
  153. return;
  154. }
  155. if (!current)
  156. {
  157. saved = PySys_GetObject(funcname); // borrowed
  158. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  159. }
  160. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  161. redirectOutput->write = func;
  162. PySys_SetObject(funcname, current);
  163. }
  164. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  165. {
  166. if (current)
  167. {
  168. PySys_SetObject(funcname, saved);
  169. }
  170. Py_XDECREF(current);
  171. current = nullptr;
  172. }
  173. PyObject* s_RedirectModule = nullptr;
  174. void Intialize(PyObject* module)
  175. {
  176. s_RedirectModule = module;
  177. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, []([[maybe_unused]] const char* msg) {
  178. AZ_TracePrintf("Python", msg);
  179. });
  180. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) {
  181. AZ_TracePrintf("Python", msg);
  182. });
  183. PySys_WriteStdout("RedirectOutput installed");
  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. bool PythonBindings::PythonStarted()
  205. {
  206. return m_pythonStarted && Py_IsInitialized();
  207. }
  208. bool PythonBindings::StartPython()
  209. {
  210. if (Py_IsInitialized())
  211. {
  212. AZ_Warning("python", false, "Python is already active");
  213. return false;
  214. }
  215. // set PYTHON_HOME
  216. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  217. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  218. {
  219. AZ_Error("python", false, "Python home path does not exist: %s", pyBasePath.c_str());
  220. return false;
  221. }
  222. AZStd::wstring pyHomePath;
  223. AZStd::to_wstring(pyHomePath, pyBasePath);
  224. Py_SetPythonHome(pyHomePath.c_str());
  225. // display basic Python information
  226. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  227. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  228. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  229. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  230. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  231. try
  232. {
  233. // ignore system location for sites site-packages
  234. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  235. Py_IgnoreEnvironmentFlag = 1; // -E
  236. const bool initializeSignalHandlers = true;
  237. pybind11::initialize_interpreter(initializeSignalHandlers);
  238. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  239. // Acquire GIL before calling Python code
  240. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  241. pybind11::gil_scoped_acquire acquire;
  242. // sanity import check
  243. if (PyRun_SimpleString("import sys") != 0)
  244. {
  245. AZ_Assert(false, "Import sys failed");
  246. return false;
  247. }
  248. // import required modules
  249. m_cmake = pybind11::module::import("o3de.cmake");
  250. m_register = pybind11::module::import("o3de.register");
  251. m_manifest = pybind11::module::import("o3de.manifest");
  252. m_engineTemplate = pybind11::module::import("o3de.engine_template");
  253. m_enableGemProject = pybind11::module::import("o3de.enable_gem");
  254. m_disableGemProject = pybind11::module::import("o3de.disable_gem");
  255. m_editProjectProperties = pybind11::module::import("o3de.project_properties");
  256. m_pathlib = pybind11::module::import("pathlib");
  257. // make sure the engine is registered
  258. RegisterThisEngine();
  259. return !PyErr_Occurred();
  260. }
  261. catch ([[maybe_unused]] const std::exception& e)
  262. {
  263. AZ_Assert(false, "Py_Initialize() failed with %s", e.what());
  264. return false;
  265. }
  266. }
  267. bool PythonBindings::StopPython()
  268. {
  269. if (Py_IsInitialized())
  270. {
  271. RedirectOutput::Shutdown();
  272. pybind11::finalize_interpreter();
  273. }
  274. else
  275. {
  276. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  277. }
  278. return !PyErr_Occurred();
  279. }
  280. bool PythonBindings::RegisterThisEngine()
  281. {
  282. bool registrationResult = true; // already registered is considered successful
  283. bool pythonResult = ExecuteWithLock(
  284. [&]
  285. {
  286. // check current engine path against all other registered engines
  287. // to see if we are already registered
  288. auto allEngines = m_manifest.attr("get_engines")();
  289. if (pybind11::isinstance<pybind11::list>(allEngines))
  290. {
  291. for (auto engine : allEngines)
  292. {
  293. AZ::IO::FixedMaxPath enginePath(Py_To_String(engine));
  294. if (enginePath.Compare(m_enginePath) == 0)
  295. {
  296. return;
  297. }
  298. }
  299. }
  300. auto result = m_register.attr("register")(QString_To_Py_Path(QString(m_enginePath.c_str())));
  301. registrationResult = (result.cast<int>() == 0);
  302. });
  303. bool finalResult = (registrationResult && pythonResult);
  304. AZ_Assert(finalResult, "Registration of this engine failed!");
  305. return finalResult;
  306. }
  307. AZ::Outcome<void, AZStd::string> PythonBindings::ExecuteWithLockErrorHandling(AZStd::function<void()> executionCallback)
  308. {
  309. if (!Py_IsInitialized())
  310. {
  311. return AZ::Failure<AZStd::string>("Python is not initialized");
  312. }
  313. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  314. pybind11::gil_scoped_release release;
  315. pybind11::gil_scoped_acquire acquire;
  316. try
  317. {
  318. executionCallback();
  319. }
  320. catch ([[maybe_unused]] const std::exception& e)
  321. {
  322. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  323. return AZ::Failure<AZStd::string>(e.what());
  324. }
  325. return AZ::Success();
  326. }
  327. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  328. {
  329. return ExecuteWithLockErrorHandling(executionCallback).IsSuccess();
  330. }
  331. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  332. {
  333. EngineInfo engineInfo;
  334. bool result = ExecuteWithLock([&] {
  335. auto enginePath = m_manifest.attr("get_this_engine_path")();
  336. auto o3deData = m_manifest.attr("load_o3de_manifest")();
  337. if (pybind11::isinstance<pybind11::dict>(o3deData))
  338. {
  339. engineInfo.m_path = Py_To_String(enginePath);
  340. auto defaultGemsFolder = m_manifest.attr("get_o3de_gems_folder")();
  341. engineInfo.m_defaultGemsFolder = Py_To_String_Optional(o3deData, "default_gems_folder", Py_To_String(defaultGemsFolder));
  342. auto defaultProjectsFolder = m_manifest.attr("get_o3de_projects_folder")();
  343. engineInfo.m_defaultProjectsFolder = Py_To_String_Optional(o3deData, "default_projects_folder", Py_To_String(defaultProjectsFolder));
  344. auto defaultRestrictedFolder = m_manifest.attr("get_o3de_restricted_folder")();
  345. engineInfo.m_defaultRestrictedFolder = Py_To_String_Optional(o3deData, "default_restricted_folder", Py_To_String(defaultRestrictedFolder));
  346. auto defaultTemplatesFolder = m_manifest.attr("get_o3de_templates_folder")();
  347. engineInfo.m_defaultTemplatesFolder = Py_To_String_Optional(o3deData, "default_templates_folder", Py_To_String(defaultTemplatesFolder));
  348. auto defaultThirdPartyFolder = m_manifest.attr("get_o3de_third_party_folder")();
  349. engineInfo.m_thirdPartyPath = Py_To_String_Optional(o3deData, "default_third_party_folder", Py_To_String(defaultThirdPartyFolder));
  350. }
  351. auto engineData = m_manifest.attr("get_engine_json_data")(pybind11::none(), enginePath);
  352. if (pybind11::isinstance<pybind11::dict>(engineData))
  353. {
  354. try
  355. {
  356. engineInfo.m_version = Py_To_String_Optional(engineData, "O3DEVersion", "0.0.0.0");
  357. engineInfo.m_name = Py_To_String_Optional(engineData, "engine_name", "O3DE");
  358. }
  359. catch ([[maybe_unused]] const std::exception& e)
  360. {
  361. AZ_Warning("PythonBindings", false, "Failed to get EngineInfo from %s", Py_To_String(enginePath));
  362. }
  363. }
  364. });
  365. if (!result || !engineInfo.IsValid())
  366. {
  367. return AZ::Failure();
  368. }
  369. else
  370. {
  371. return AZ::Success(AZStd::move(engineInfo));
  372. }
  373. }
  374. bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo)
  375. {
  376. bool result = ExecuteWithLock([&] {
  377. auto registrationResult = m_register.attr("register")(
  378. QString_To_Py_Path(engineInfo.m_path),
  379. pybind11::none(), // project_path
  380. pybind11::none(), // gem_path
  381. pybind11::none(), // external_subdir_path
  382. pybind11::none(), // template_path
  383. pybind11::none(), // restricted_path
  384. pybind11::none(), // repo_uri
  385. pybind11::none(), // default_engines_folder
  386. QString_To_Py_Path(engineInfo.m_defaultProjectsFolder),
  387. QString_To_Py_Path(engineInfo.m_defaultGemsFolder),
  388. QString_To_Py_Path(engineInfo.m_defaultTemplatesFolder),
  389. pybind11::none(), // default_restricted_folder
  390. QString_To_Py_Path(engineInfo.m_thirdPartyPath)
  391. );
  392. if (registrationResult.cast<int>() != 0)
  393. {
  394. result = false;
  395. }
  396. });
  397. return result;
  398. }
  399. AZ::Outcome<GemInfo> PythonBindings::GetGemInfo(const QString& path, const QString& projectPath)
  400. {
  401. GemInfo gemInfo = GemInfoFromPath(QString_To_Py_String(path), QString_To_Py_Path(projectPath));
  402. if (gemInfo.IsValid())
  403. {
  404. return AZ::Success(AZStd::move(gemInfo));
  405. }
  406. else
  407. {
  408. return AZ::Failure();
  409. }
  410. }
  411. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetEngineGemInfos()
  412. {
  413. QVector<GemInfo> gems;
  414. auto result = ExecuteWithLockErrorHandling([&]
  415. {
  416. for (auto path : m_manifest.attr("get_engine_gems")())
  417. {
  418. gems.push_back(GemInfoFromPath(path, pybind11::none()));
  419. }
  420. });
  421. if (!result.IsSuccess())
  422. {
  423. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  424. }
  425. std::sort(gems.begin(), gems.end());
  426. return AZ::Success(AZStd::move(gems));
  427. }
  428. AZ::Outcome<QVector<GemInfo>, AZStd::string> PythonBindings::GetAllGemInfos(const QString& projectPath)
  429. {
  430. QVector<GemInfo> gems;
  431. auto result = ExecuteWithLockErrorHandling([&]
  432. {
  433. auto pyProjectPath = QString_To_Py_Path(projectPath);
  434. for (auto path : m_manifest.attr("get_all_gems")(pyProjectPath))
  435. {
  436. gems.push_back(GemInfoFromPath(path, pyProjectPath));
  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<AZStd::string>, AZStd::string> PythonBindings::GetEnabledGemNames(const QString& projectPath)
  447. {
  448. // Retrieve the path to the cmake file that lists the enabled gems.
  449. pybind11::str enabledGemsFilename;
  450. auto result = ExecuteWithLockErrorHandling([&]
  451. {
  452. enabledGemsFilename = m_cmake.attr("get_enabled_gem_cmake_file")(
  453. pybind11::none(), // project_name
  454. QString_To_Py_Path(projectPath)); // project_path
  455. });
  456. if (!result.IsSuccess())
  457. {
  458. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  459. }
  460. // Retrieve the actual list of names from the cmake file.
  461. QVector<AZStd::string> gemNames;
  462. result = ExecuteWithLockErrorHandling([&]
  463. {
  464. const auto pyGemNames = m_cmake.attr("get_enabled_gems")(enabledGemsFilename);
  465. for (auto gemName : pyGemNames)
  466. {
  467. gemNames.push_back(Py_To_String(gemName));
  468. }
  469. });
  470. if (!result.IsSuccess())
  471. {
  472. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  473. }
  474. return AZ::Success(AZStd::move(gemNames));
  475. }
  476. bool PythonBindings::AddProject(const QString& path)
  477. {
  478. bool registrationResult = false;
  479. bool result = ExecuteWithLock(
  480. [&]
  481. {
  482. auto projectPath = QString_To_Py_Path(path);
  483. auto pythonRegistrationResult = m_register.attr("register")(pybind11::none(), projectPath);
  484. // Returns an exit code so boolify it then invert result
  485. registrationResult = !pythonRegistrationResult.cast<bool>();
  486. });
  487. return result && registrationResult;
  488. }
  489. bool PythonBindings::RemoveProject(const QString& path)
  490. {
  491. bool registrationResult = false;
  492. bool result = ExecuteWithLock(
  493. [&]
  494. {
  495. auto pythonRegistrationResult = m_register.attr("register")(
  496. pybind11::none(), // engine_path
  497. QString_To_Py_Path(path), // project_path
  498. pybind11::none(), // gem_path
  499. pybind11::none(), // external_subdir_path
  500. pybind11::none(), // template_path
  501. pybind11::none(), // restricted_path
  502. pybind11::none(), // repo_uri
  503. pybind11::none(), // default_engines_folder
  504. pybind11::none(), // default_projects_folder
  505. pybind11::none(), // default_gems_folder
  506. pybind11::none(), // default_templates_folder
  507. pybind11::none(), // default_restricted_folder
  508. pybind11::none(), // default_third_party_folder
  509. pybind11::none(), // external_subdir_engine_path
  510. pybind11::none(), // external_subdir_project_path
  511. true, // remove
  512. false // force
  513. );
  514. // Returns an exit code so boolify it then invert result
  515. registrationResult = !pythonRegistrationResult.cast<bool>();
  516. });
  517. return result && registrationResult;
  518. }
  519. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  520. {
  521. ProjectInfo createdProjectInfo;
  522. bool result = ExecuteWithLock([&] {
  523. auto projectPath = QString_To_Py_Path(projectInfo.m_path);
  524. auto createProjectResult = m_engineTemplate.attr("create_project")(
  525. projectPath,
  526. QString_To_Py_String(projectInfo.m_projectName),
  527. QString_To_Py_Path(projectTemplatePath)
  528. );
  529. if (createProjectResult.cast<int>() == 0)
  530. {
  531. createdProjectInfo = ProjectInfoFromPath(projectPath);
  532. }
  533. });
  534. if (!result || !createdProjectInfo.IsValid())
  535. {
  536. return AZ::Failure();
  537. }
  538. else
  539. {
  540. return AZ::Success(AZStd::move(createdProjectInfo));
  541. }
  542. }
  543. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  544. {
  545. ProjectInfo projectInfo = ProjectInfoFromPath(QString_To_Py_Path(path));
  546. if (projectInfo.IsValid())
  547. {
  548. return AZ::Success(AZStd::move(projectInfo));
  549. }
  550. else
  551. {
  552. return AZ::Failure();
  553. }
  554. }
  555. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  556. {
  557. GemInfo gemInfo;
  558. gemInfo.m_path = Py_To_String(path);
  559. gemInfo.m_directoryLink = gemInfo.m_path;
  560. auto data = m_manifest.attr("get_gem_json_data")(pybind11::none(), path, pyProjectPath);
  561. if (pybind11::isinstance<pybind11::dict>(data))
  562. {
  563. try
  564. {
  565. // required
  566. gemInfo.m_name = Py_To_String(data["gem_name"]);
  567. // optional
  568. gemInfo.m_displayName = Py_To_String_Optional(data, "display_name", gemInfo.m_name);
  569. gemInfo.m_summary = Py_To_String_Optional(data, "summary", "");
  570. gemInfo.m_version = "";
  571. gemInfo.m_requirement = Py_To_String_Optional(data, "requirements", "");
  572. gemInfo.m_creator = Py_To_String_Optional(data, "origin", "");
  573. gemInfo.m_documentationLink = Py_To_String_Optional(data, "documentation_url", "");
  574. if (gemInfo.m_creator.contains("Open 3D Engine"))
  575. {
  576. gemInfo.m_gemOrigin = GemInfo::GemOrigin::Open3DEEngine;
  577. }
  578. if (data.contains("user_tags"))
  579. {
  580. for (auto tag : data["user_tags"])
  581. {
  582. gemInfo.m_features.push_back(Py_To_String(tag));
  583. }
  584. }
  585. if (data.contains("dependencies"))
  586. {
  587. for (auto dependency : data["dependencies"])
  588. {
  589. gemInfo.m_dependencies.push_back(Py_To_String(dependency));
  590. }
  591. }
  592. QString gemType = Py_To_String_Optional(data, "type", "");
  593. if (gemType == "Asset")
  594. {
  595. gemInfo.m_types |= GemInfo::Type::Asset;
  596. }
  597. if (gemType == "Code")
  598. {
  599. gemInfo.m_types |= GemInfo::Type::Code;
  600. }
  601. if (gemType == "Tool")
  602. {
  603. gemInfo.m_types |= GemInfo::Type::Tool;
  604. }
  605. }
  606. catch ([[maybe_unused]] const std::exception& e)
  607. {
  608. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  609. }
  610. }
  611. return gemInfo;
  612. }
  613. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  614. {
  615. ProjectInfo projectInfo;
  616. projectInfo.m_path = Py_To_String(path);
  617. projectInfo.m_needsBuild = false;
  618. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  619. if (pybind11::isinstance<pybind11::dict>(projectData))
  620. {
  621. try
  622. {
  623. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  624. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  625. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  626. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  627. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  628. if (projectData.contains("user_tags"))
  629. {
  630. for (auto tag : projectData["user_tags"])
  631. {
  632. projectInfo.m_userTags.append(Py_To_String(tag));
  633. }
  634. }
  635. }
  636. catch ([[maybe_unused]] const std::exception& e)
  637. {
  638. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  639. }
  640. }
  641. return projectInfo;
  642. }
  643. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  644. {
  645. QVector<ProjectInfo> projects;
  646. bool result = ExecuteWithLock([&] {
  647. // external projects
  648. for (auto path : m_manifest.attr("get_projects")())
  649. {
  650. projects.push_back(ProjectInfoFromPath(path));
  651. }
  652. // projects from the engine
  653. for (auto path : m_manifest.attr("get_engine_projects")())
  654. {
  655. projects.push_back(ProjectInfoFromPath(path));
  656. }
  657. });
  658. if (!result)
  659. {
  660. return AZ::Failure();
  661. }
  662. else
  663. {
  664. return AZ::Success(AZStd::move(projects));
  665. }
  666. }
  667. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  668. {
  669. return ExecuteWithLockErrorHandling([&]
  670. {
  671. m_enableGemProject.attr("enable_gem_in_project")(
  672. pybind11::none(), // gem name not needed as path is provided
  673. QString_To_Py_Path(gemPath),
  674. pybind11::none(), // project name not needed as path is provided
  675. QString_To_Py_Path(projectPath)
  676. );
  677. });
  678. }
  679. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  680. {
  681. return ExecuteWithLockErrorHandling([&]
  682. {
  683. m_disableGemProject.attr("disable_gem_in_project")(
  684. pybind11::none(), // gem name not needed as path is provided
  685. QString_To_Py_Path(gemPath),
  686. pybind11::none(), // project name not needed as path is provided
  687. QString_To_Py_Path(projectPath)
  688. );
  689. });
  690. }
  691. bool PythonBindings::RemoveInvalidProjects()
  692. {
  693. bool removalResult = false;
  694. bool result = ExecuteWithLock(
  695. [&]
  696. {
  697. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  698. // Returns an exit code so boolify it then invert result
  699. removalResult = !pythonRemovalResult.cast<bool>();
  700. });
  701. return result && removalResult;
  702. }
  703. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  704. {
  705. bool updateProjectSucceeded = false;
  706. auto result = ExecuteWithLockErrorHandling([&]
  707. {
  708. std::list<std::string> newTags;
  709. for (const auto& i : projectInfo.m_userTags)
  710. {
  711. newTags.push_back(i.toStdString());
  712. }
  713. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  714. QString_To_Py_Path(projectInfo.m_path),
  715. pybind11::none(), // proj_name not used
  716. QString_To_Py_String(projectInfo.m_projectName),
  717. QString_To_Py_String(projectInfo.m_origin),
  718. QString_To_Py_String(projectInfo.m_displayName),
  719. QString_To_Py_String(projectInfo.m_summary),
  720. QString_To_Py_String(projectInfo.m_iconPath), // new_icon
  721. pybind11::none(), // add_tags not used
  722. pybind11::none(), // remove_tags not used
  723. pybind11::list(pybind11::cast(newTags)));
  724. updateProjectSucceeded = (editResult.cast<int>() == 0);
  725. });
  726. if (!result.IsSuccess())
  727. {
  728. return result;
  729. }
  730. else if (!updateProjectSucceeded)
  731. {
  732. return AZ::Failure<AZStd::string>("Failed to update project.");
  733. }
  734. return AZ::Success();
  735. }
  736. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  737. {
  738. ProjectTemplateInfo templateInfo;
  739. templateInfo.m_path = Py_To_String(path);
  740. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path, pyProjectPath);
  741. if (pybind11::isinstance<pybind11::dict>(data))
  742. {
  743. try
  744. {
  745. // required
  746. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  747. templateInfo.m_name = Py_To_String(data["template_name"]);
  748. templateInfo.m_summary = Py_To_String(data["summary"]);
  749. // optional
  750. if (data.contains("canonical_tags"))
  751. {
  752. for (auto tag : data["canonical_tags"])
  753. {
  754. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  755. }
  756. }
  757. if (data.contains("user_tags"))
  758. {
  759. for (auto tag : data["user_tags"])
  760. {
  761. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  762. }
  763. }
  764. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  765. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  766. if (enabledGemNames)
  767. {
  768. for (auto gem : enabledGemNames.GetValue())
  769. {
  770. // Exclude the template ${Name} placeholder for the list of included gems
  771. // That Gem gets created with the project
  772. if (!gem.contains("${Name}"))
  773. {
  774. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  775. }
  776. }
  777. }
  778. }
  779. catch ([[maybe_unused]] const std::exception& e)
  780. {
  781. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  782. }
  783. }
  784. return templateInfo;
  785. }
  786. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates(const QString& projectPath)
  787. {
  788. QVector<ProjectTemplateInfo> templates;
  789. bool result = ExecuteWithLock([&] {
  790. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  791. {
  792. templates.push_back(ProjectTemplateInfoFromPath(path, QString_To_Py_Path(projectPath)));
  793. }
  794. });
  795. if (!result)
  796. {
  797. return AZ::Failure();
  798. }
  799. else
  800. {
  801. return AZ::Success(AZStd::move(templates));
  802. }
  803. }
  804. GemRepoInfo PythonBindings::GemRepoInfoFromPath(pybind11::handle path, pybind11::handle pyEnginePath)
  805. {
  806. /* Placeholder Logic */
  807. (void)path;
  808. (void)pyEnginePath;
  809. return GemRepoInfo();
  810. }
  811. //#define MOCK_GEM_REPO_INFO true
  812. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  813. {
  814. QVector<GemRepoInfo> gemRepos;
  815. #ifndef MOCK_GEM_REPO_INFO
  816. auto result = ExecuteWithLockErrorHandling(
  817. [&]
  818. {
  819. /* Placeholder Logic, o3de scripts need method added
  820. *
  821. for (auto path : m_manifest.attr("get_gem_repos")())
  822. {
  823. gemRepos.push_back(GemRepoInfoFromPath(path, pybind11::none()));
  824. }
  825. *
  826. */
  827. });
  828. if (!result.IsSuccess())
  829. {
  830. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  831. }
  832. #else
  833. GemRepoInfo mockJohnRepo("JohnCreates", "John Smith", QDateTime(QDate(2021, 8, 31), QTime(11, 57)), true);
  834. mockJohnRepo.m_summary = "John's Summary. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sollicitudin dapibus urna";
  835. mockJohnRepo.m_repoLink = "https://github.com/o3de/o3de";
  836. mockJohnRepo.m_additionalInfo = "John's additional info. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sollicitu.";
  837. gemRepos.push_back(mockJohnRepo);
  838. GemRepoInfo mockJaneRepo("JanesGems", "Jane Doe", QDateTime(QDate(2021, 9, 10), QTime(18, 23)), false);
  839. mockJaneRepo.m_summary = "Jane's Summary.";
  840. mockJaneRepo.m_repoLink = "https://github.com/o3de/o3de.org";
  841. gemRepos.push_back(mockJaneRepo);
  842. #endif // MOCK_GEM_REPO_INFO
  843. std::sort(gemRepos.begin(), gemRepos.end());
  844. return AZ::Success(AZStd::move(gemRepos));
  845. }
  846. }