2
0

PythonBindings.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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["path"]));
  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. QString gemType = Py_To_String_Optional(data, "type", "");
  586. if (gemType == "Asset")
  587. {
  588. gemInfo.m_types |= GemInfo::Type::Asset;
  589. }
  590. if (gemType == "Code")
  591. {
  592. gemInfo.m_types |= GemInfo::Type::Code;
  593. }
  594. if (gemType == "Tool")
  595. {
  596. gemInfo.m_types |= GemInfo::Type::Tool;
  597. }
  598. }
  599. catch ([[maybe_unused]] const std::exception& e)
  600. {
  601. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  602. }
  603. }
  604. return gemInfo;
  605. }
  606. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  607. {
  608. ProjectInfo projectInfo;
  609. projectInfo.m_path = Py_To_String(path);
  610. projectInfo.m_needsBuild = false;
  611. auto projectData = m_manifest.attr("get_project_json_data")(pybind11::none(), path);
  612. if (pybind11::isinstance<pybind11::dict>(projectData))
  613. {
  614. try
  615. {
  616. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  617. projectInfo.m_displayName = Py_To_String_Optional(projectData, "display_name", projectInfo.m_projectName);
  618. projectInfo.m_origin = Py_To_String_Optional(projectData, "origin", projectInfo.m_origin);
  619. projectInfo.m_summary = Py_To_String_Optional(projectData, "summary", projectInfo.m_summary);
  620. projectInfo.m_iconPath = Py_To_String_Optional(projectData, "icon", ProjectPreviewImagePath);
  621. if (projectData.contains("user_tags"))
  622. {
  623. for (auto tag : projectData["user_tags"])
  624. {
  625. projectInfo.m_userTags.append(Py_To_String(tag));
  626. }
  627. }
  628. }
  629. catch ([[maybe_unused]] const std::exception& e)
  630. {
  631. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  632. }
  633. }
  634. return projectInfo;
  635. }
  636. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  637. {
  638. QVector<ProjectInfo> projects;
  639. bool result = ExecuteWithLock([&] {
  640. // external projects
  641. for (auto path : m_manifest.attr("get_projects")())
  642. {
  643. projects.push_back(ProjectInfoFromPath(path));
  644. }
  645. // projects from the engine
  646. for (auto path : m_manifest.attr("get_engine_projects")())
  647. {
  648. projects.push_back(ProjectInfoFromPath(path));
  649. }
  650. });
  651. if (!result)
  652. {
  653. return AZ::Failure();
  654. }
  655. else
  656. {
  657. return AZ::Success(AZStd::move(projects));
  658. }
  659. }
  660. AZ::Outcome<void, AZStd::string> PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
  661. {
  662. return ExecuteWithLockErrorHandling([&]
  663. {
  664. m_enableGemProject.attr("enable_gem_in_project")(
  665. pybind11::none(), // gem name not needed as path is provided
  666. QString_To_Py_Path(gemPath),
  667. pybind11::none(), // project name not needed as path is provided
  668. QString_To_Py_Path(projectPath)
  669. );
  670. });
  671. }
  672. AZ::Outcome<void, AZStd::string> PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
  673. {
  674. return ExecuteWithLockErrorHandling([&]
  675. {
  676. m_disableGemProject.attr("disable_gem_in_project")(
  677. pybind11::none(), // gem name not needed as path is provided
  678. QString_To_Py_Path(gemPath),
  679. pybind11::none(), // project name not needed as path is provided
  680. QString_To_Py_Path(projectPath)
  681. );
  682. });
  683. }
  684. bool PythonBindings::RemoveInvalidProjects()
  685. {
  686. bool removalResult = false;
  687. bool result = ExecuteWithLock(
  688. [&]
  689. {
  690. auto pythonRemovalResult = m_register.attr("remove_invalid_o3de_projects")();
  691. // Returns an exit code so boolify it then invert result
  692. removalResult = !pythonRemovalResult.cast<bool>();
  693. });
  694. return result && removalResult;
  695. }
  696. AZ::Outcome<void, AZStd::string> PythonBindings::UpdateProject(const ProjectInfo& projectInfo)
  697. {
  698. bool updateProjectSucceeded = false;
  699. auto result = ExecuteWithLockErrorHandling([&]
  700. {
  701. std::list<std::string> newTags;
  702. for (const auto& i : projectInfo.m_userTags)
  703. {
  704. newTags.push_back(i.toStdString());
  705. }
  706. auto editResult = m_editProjectProperties.attr("edit_project_props")(
  707. QString_To_Py_Path(projectInfo.m_path),
  708. pybind11::none(), // proj_name not used
  709. QString_To_Py_String(projectInfo.m_projectName),
  710. QString_To_Py_String(projectInfo.m_origin),
  711. QString_To_Py_String(projectInfo.m_displayName),
  712. QString_To_Py_String(projectInfo.m_summary),
  713. QString_To_Py_String(projectInfo.m_iconPath), // new_icon
  714. pybind11::none(), // add_tags not used
  715. pybind11::none(), // remove_tags not used
  716. pybind11::list(pybind11::cast(newTags)));
  717. updateProjectSucceeded = (editResult.cast<int>() == 0);
  718. });
  719. if (!result.IsSuccess())
  720. {
  721. return result;
  722. }
  723. else if (!updateProjectSucceeded)
  724. {
  725. return AZ::Failure<AZStd::string>("Failed to update project.");
  726. }
  727. return AZ::Success();
  728. }
  729. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path, pybind11::handle pyProjectPath)
  730. {
  731. ProjectTemplateInfo templateInfo;
  732. templateInfo.m_path = Py_To_String(path);
  733. auto data = m_manifest.attr("get_template_json_data")(pybind11::none(), path, pyProjectPath);
  734. if (pybind11::isinstance<pybind11::dict>(data))
  735. {
  736. try
  737. {
  738. // required
  739. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  740. templateInfo.m_name = Py_To_String(data["template_name"]);
  741. templateInfo.m_summary = Py_To_String(data["summary"]);
  742. // optional
  743. if (data.contains("canonical_tags"))
  744. {
  745. for (auto tag : data["canonical_tags"])
  746. {
  747. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  748. }
  749. }
  750. if (data.contains("user_tags"))
  751. {
  752. for (auto tag : data["user_tags"])
  753. {
  754. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  755. }
  756. }
  757. QString templateProjectPath = QDir(templateInfo.m_path).filePath("Template");
  758. auto enabledGemNames = GetEnabledGemNames(templateProjectPath);
  759. if (enabledGemNames)
  760. {
  761. for (auto gem : enabledGemNames.GetValue())
  762. {
  763. // Exclude the template ${Name} placeholder for the list of included gems
  764. // That Gem gets created with the project
  765. if (!gem.contains("${Name}"))
  766. {
  767. templateInfo.m_includedGems.push_back(Py_To_String(gem.c_str()));
  768. }
  769. }
  770. }
  771. }
  772. catch ([[maybe_unused]] const std::exception& e)
  773. {
  774. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  775. }
  776. }
  777. return templateInfo;
  778. }
  779. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates(const QString& projectPath)
  780. {
  781. QVector<ProjectTemplateInfo> templates;
  782. bool result = ExecuteWithLock([&] {
  783. for (auto path : m_manifest.attr("get_templates_for_project_creation")())
  784. {
  785. templates.push_back(ProjectTemplateInfoFromPath(path, QString_To_Py_Path(projectPath)));
  786. }
  787. });
  788. if (!result)
  789. {
  790. return AZ::Failure();
  791. }
  792. else
  793. {
  794. return AZ::Success(AZStd::move(templates));
  795. }
  796. }
  797. GemRepoInfo PythonBindings::GemRepoInfoFromPath(pybind11::handle path, pybind11::handle pyEnginePath)
  798. {
  799. /* Placeholder Logic */
  800. (void)path;
  801. (void)pyEnginePath;
  802. return GemRepoInfo();
  803. }
  804. //#define MOCK_GEM_REPO_INFO true
  805. AZ::Outcome<QVector<GemRepoInfo>, AZStd::string> PythonBindings::GetAllGemRepoInfos()
  806. {
  807. QVector<GemRepoInfo> gemRepos;
  808. #ifndef MOCK_GEM_REPO_INFO
  809. auto result = ExecuteWithLockErrorHandling(
  810. [&]
  811. {
  812. /* Placeholder Logic, o3de scripts need method added
  813. *
  814. for (auto path : m_manifest.attr("get_gem_repos")())
  815. {
  816. gemRepos.push_back(GemRepoInfoFromPath(path, pybind11::none()));
  817. }
  818. *
  819. */
  820. });
  821. if (!result.IsSuccess())
  822. {
  823. return AZ::Failure<AZStd::string>(result.GetError().c_str());
  824. }
  825. #else
  826. gemRepos.push_back(GemRepoInfo("JohnCreates", "John Smith", "", QDateTime(QDate(2021, 8, 31), QTime(11, 57)), true));
  827. gemRepos.push_back(GemRepoInfo("JanesGems", "Jane Doe", "", QDateTime(QDate(2021, 9, 10), QTime(18, 23)), false));
  828. #endif // MOCK_GEM_REPO_INFO
  829. std::sort(gemRepos.begin(), gemRepos.end());
  830. return AZ::Success(AZStd::move(gemRepos));
  831. }
  832. }