PythonBindings.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. * its licensors.
  4. *
  5. * For complete copyright and license terms please see the LICENSE at the root of this
  6. * distribution (the "License"). All use of this software is governed by the License,
  7. * or, if provided, by the license below or the license accompanying this file. Do not
  8. * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. *
  11. */
  12. #include <PythonBindings.h>
  13. // Qt defines slots, which interferes with the use here.
  14. #pragma push_macro("slots")
  15. #undef slots
  16. #include <pybind11/functional.h>
  17. #include <pybind11/embed.h>
  18. #include <pybind11/eval.h>
  19. #pragma pop_macro("slots")
  20. #include <AzCore/IO/FileIO.h>
  21. #include <AzCore/IO/SystemFile.h>
  22. #include <AzCore/std/string/conversions.h>
  23. #include <AzCore/StringFunc/StringFunc.h>
  24. namespace Platform
  25. {
  26. bool InsertPythonLibraryPath(
  27. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  28. {
  29. // append lib path to Python paths
  30. AZ::IO::FixedMaxPath libPath = engineRoot;
  31. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  32. libPath = libPath.LexicallyNormal();
  33. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  34. {
  35. paths.insert(libPath.c_str());
  36. return true;
  37. }
  38. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  39. return false;
  40. }
  41. // Implemented in each different platform's PAL implentation files, as it differs per platform.
  42. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  43. } // namespace Platform
  44. #define Py_To_String(obj) obj.cast<std::string>().c_str()
  45. #define Py_To_String_Optional(dict, key, default_string) dict.contains(key) ? Py_To_String(dict[key]) : default_string
  46. namespace RedirectOutput
  47. {
  48. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  49. struct RedirectOutput
  50. {
  51. PyObject_HEAD RedirectOutputFunc write;
  52. };
  53. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  54. {
  55. std::size_t written(0);
  56. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  57. if (selfimpl->write)
  58. {
  59. char* data;
  60. if (!PyArg_ParseTuple(args, "s", &data))
  61. {
  62. return PyLong_FromSize_t(0);
  63. }
  64. selfimpl->write(data);
  65. written = strlen(data);
  66. }
  67. return PyLong_FromSize_t(written);
  68. }
  69. PyObject* RedirectFlush([[maybe_unused]] PyObject* self,[[maybe_unused]] PyObject* args)
  70. {
  71. // no-op
  72. return Py_BuildValue("");
  73. }
  74. PyMethodDef RedirectMethods[] = {
  75. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  76. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  77. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  78. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  79. {0, 0, 0, 0} // sentinel
  80. };
  81. PyTypeObject RedirectOutputType = {
  82. PyVarObject_HEAD_INIT(0, 0) "azlmbr_redirect.RedirectOutputType", // tp_name
  83. sizeof(RedirectOutput), /* tp_basicsize */
  84. 0, /* tp_itemsize */
  85. 0, /* tp_dealloc */
  86. 0, /* tp_print */
  87. 0, /* tp_getattr */
  88. 0, /* tp_setattr */
  89. 0, /* tp_reserved */
  90. 0, /* tp_repr */
  91. 0, /* tp_as_number */
  92. 0, /* tp_as_sequence */
  93. 0, /* tp_as_mapping */
  94. 0, /* tp_hash */
  95. 0, /* tp_call */
  96. 0, /* tp_str */
  97. 0, /* tp_getattro */
  98. 0, /* tp_setattro */
  99. 0, /* tp_as_buffer */
  100. Py_TPFLAGS_DEFAULT, /* tp_flags */
  101. "azlmbr_redirect objects", /* tp_doc */
  102. 0, /* tp_traverse */
  103. 0, /* tp_clear */
  104. 0, /* tp_richcompare */
  105. 0, /* tp_weaklistoffset */
  106. 0, /* tp_iter */
  107. 0, /* tp_iternext */
  108. RedirectMethods, /* tp_methods */
  109. 0, /* tp_members */
  110. 0, /* tp_getset */
  111. 0, /* tp_base */
  112. 0, /* tp_dict */
  113. 0, /* tp_descr_get */
  114. 0, /* tp_descr_set */
  115. 0, /* tp_dictoffset */
  116. 0, /* tp_init */
  117. 0, /* tp_alloc */
  118. 0 /* tp_new */
  119. };
  120. PyModuleDef RedirectOutputModule = {
  121. PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0,
  122. };
  123. // Internal state
  124. PyObject* g_redirect_stdout = nullptr;
  125. PyObject* g_redirect_stdout_saved = nullptr;
  126. PyObject* g_redirect_stderr = nullptr;
  127. PyObject* g_redirect_stderr_saved = nullptr;
  128. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  129. {
  130. g_redirect_stdout = nullptr;
  131. g_redirect_stdout_saved = nullptr;
  132. g_redirect_stderr = nullptr;
  133. g_redirect_stderr_saved = nullptr;
  134. RedirectOutputType.tp_new = PyType_GenericNew;
  135. if (PyType_Ready(&RedirectOutputType) < 0)
  136. {
  137. return 0;
  138. }
  139. PyObject* redirectModule = PyModule_Create(&RedirectOutputModule);
  140. if (redirectModule)
  141. {
  142. Py_INCREF(&RedirectOutputType);
  143. PyModule_AddObject(redirectModule, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  144. }
  145. return redirectModule;
  146. }
  147. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  148. {
  149. if (PyType_Ready(&RedirectOutputType) < 0)
  150. {
  151. AZ_Warning("python", false, "RedirectOutputType not ready!");
  152. return;
  153. }
  154. if (!current)
  155. {
  156. saved = PySys_GetObject(funcname); // borrowed
  157. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  158. }
  159. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  160. redirectOutput->write = func;
  161. PySys_SetObject(funcname, current);
  162. }
  163. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  164. {
  165. if (current)
  166. {
  167. PySys_SetObject(funcname, saved);
  168. }
  169. Py_XDECREF(current);
  170. current = nullptr;
  171. }
  172. PyObject* s_RedirectModule = nullptr;
  173. void Intialize(PyObject* module)
  174. {
  175. s_RedirectModule = module;
  176. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, []([[maybe_unused]] const char* msg) {
  177. AZ_TracePrintf("Python", msg);
  178. });
  179. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, []([[maybe_unused]] const char* msg) {
  180. AZ_TracePrintf("Python", msg);
  181. });
  182. PySys_WriteStdout("RedirectOutput installed");
  183. }
  184. void Shutdown()
  185. {
  186. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  187. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  188. Py_XDECREF(s_RedirectModule);
  189. s_RedirectModule = nullptr;
  190. }
  191. } // namespace RedirectOutput
  192. namespace O3DE::ProjectManager
  193. {
  194. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  195. : m_enginePath(enginePath)
  196. {
  197. StartPython();
  198. }
  199. PythonBindings::~PythonBindings()
  200. {
  201. StopPython();
  202. }
  203. bool PythonBindings::StartPython()
  204. {
  205. if (Py_IsInitialized())
  206. {
  207. AZ_Warning("python", false, "Python is already active");
  208. return false;
  209. }
  210. // set PYTHON_HOME
  211. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  212. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  213. {
  214. AZ_Warning("python", false, "Python home path must exist. path:%s", pyBasePath.c_str());
  215. return false;
  216. }
  217. AZStd::wstring pyHomePath;
  218. AZStd::to_wstring(pyHomePath, pyBasePath);
  219. Py_SetPythonHome(pyHomePath.c_str());
  220. // display basic Python information
  221. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  222. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  223. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  224. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  225. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  226. try
  227. {
  228. // ignore system location for sites site-packages
  229. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  230. Py_IgnoreEnvironmentFlag = 1; // -E
  231. const bool initializeSignalHandlers = true;
  232. pybind11::initialize_interpreter(initializeSignalHandlers);
  233. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  234. // Acquire GIL before calling Python code
  235. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  236. pybind11::gil_scoped_acquire acquire;
  237. // Setup sys.path
  238. int result = PyRun_SimpleString("import sys");
  239. AZ_Warning("ProjectManagerWindow", result != -1, "Import sys failed");
  240. result = PyRun_SimpleString(AZStd::string::format("sys.path.append('%s')", m_enginePath.c_str()).c_str());
  241. AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed");
  242. // import required modules
  243. m_registration = pybind11::module::import("cmake.Tools.registration");
  244. m_engineTemplate = pybind11::module::import("cmake.Tools.engine_template");
  245. return result == 0 && !PyErr_Occurred();
  246. } catch ([[maybe_unused]] const std::exception& e)
  247. {
  248. AZ_Warning("ProjectManagerWindow", false, "Py_Initialize() failed with %s", e.what());
  249. return false;
  250. }
  251. }
  252. bool PythonBindings::StopPython()
  253. {
  254. if (Py_IsInitialized())
  255. {
  256. RedirectOutput::Shutdown();
  257. pybind11::finalize_interpreter();
  258. }
  259. else
  260. {
  261. AZ_Warning("ProjectManagerWindow", false, "Did not finalize since Py_IsInitialized() was false");
  262. }
  263. return !PyErr_Occurred();
  264. }
  265. bool PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  266. {
  267. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  268. pybind11::gil_scoped_release release;
  269. pybind11::gil_scoped_acquire acquire;
  270. try
  271. {
  272. executionCallback();
  273. return true;
  274. }
  275. catch ([[maybe_unused]] const std::exception& e)
  276. {
  277. AZ_Warning("PythonBindings", false, "Python exception %s", e.what());
  278. return false;
  279. }
  280. }
  281. AZ::Outcome<EngineInfo> PythonBindings::GetEngineInfo()
  282. {
  283. return AZ::Failure();
  284. }
  285. bool PythonBindings::SetEngineInfo([[maybe_unused]] const EngineInfo& engineInfo)
  286. {
  287. return false;
  288. }
  289. AZ::Outcome<GemInfo> PythonBindings::GetGem(const QString& path)
  290. {
  291. GemInfo gemInfo = GemInfoFromPath(pybind11::str(path.toStdString()));
  292. if (gemInfo.IsValid())
  293. {
  294. return AZ::Success(AZStd::move(gemInfo));
  295. }
  296. else
  297. {
  298. return AZ::Failure();
  299. }
  300. }
  301. AZ::Outcome<QVector<GemInfo>> PythonBindings::GetGems()
  302. {
  303. QVector<GemInfo> gems;
  304. bool result = ExecuteWithLock([&] {
  305. // external gems
  306. for (auto path : m_registration.attr("get_gems")())
  307. {
  308. gems.push_back(GemInfoFromPath(path));
  309. }
  310. // gems from the engine
  311. for (auto path : m_registration.attr("get_engine_gems")())
  312. {
  313. gems.push_back(GemInfoFromPath(path));
  314. }
  315. });
  316. if (!result)
  317. {
  318. return AZ::Failure();
  319. }
  320. else
  321. {
  322. return AZ::Success(AZStd::move(gems));
  323. }
  324. }
  325. AZ::Outcome<ProjectInfo> PythonBindings::CreateProject(const QString& projectTemplatePath, const ProjectInfo& projectInfo)
  326. {
  327. ProjectInfo createdProjectInfo;
  328. bool result = ExecuteWithLock([&] {
  329. pybind11::str projectPath = projectInfo.m_path.toStdString();
  330. pybind11::str templatePath = projectTemplatePath.toStdString();
  331. auto createProjectResult = m_engineTemplate.attr("create_project")(projectPath, templatePath);
  332. if (createProjectResult.cast<int>() == 0)
  333. {
  334. createdProjectInfo = ProjectInfoFromPath(projectPath);
  335. }
  336. });
  337. if (!result || !createdProjectInfo.IsValid())
  338. {
  339. return AZ::Failure();
  340. }
  341. else
  342. {
  343. return AZ::Success(AZStd::move(createdProjectInfo));
  344. }
  345. }
  346. AZ::Outcome<ProjectInfo> PythonBindings::GetProject(const QString& path)
  347. {
  348. ProjectInfo projectInfo = ProjectInfoFromPath(pybind11::str(path.toStdString()));
  349. if (projectInfo.IsValid())
  350. {
  351. return AZ::Success(AZStd::move(projectInfo));
  352. }
  353. else
  354. {
  355. return AZ::Failure();
  356. }
  357. }
  358. GemInfo PythonBindings::GemInfoFromPath(pybind11::handle path)
  359. {
  360. GemInfo gemInfo;
  361. gemInfo.m_path = Py_To_String(path);
  362. auto data = m_registration.attr("get_gem_data")(pybind11::none(), path);
  363. if (pybind11::isinstance<pybind11::dict>(data))
  364. {
  365. try
  366. {
  367. // required
  368. gemInfo.m_name = Py_To_String(data["Name"]);
  369. gemInfo.m_uuid = AZ::Uuid(Py_To_String(data["Uuid"]));
  370. // optional
  371. gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name);
  372. gemInfo.m_summary = Py_To_String_Optional(data, "Summary", "");
  373. gemInfo.m_version = Py_To_String_Optional(data, "Version", "");
  374. if (data.contains("Dependencies"))
  375. {
  376. for (auto dependency : data["Dependencies"])
  377. {
  378. gemInfo.m_dependingGemUuids.push_back(Py_To_String(dependency["Uuid"]));
  379. }
  380. }
  381. if (data.contains("Tags"))
  382. {
  383. for (auto tag : data["Tags"])
  384. {
  385. gemInfo.m_features.push_back(Py_To_String(tag));
  386. }
  387. }
  388. }
  389. catch ([[maybe_unused]] const std::exception& e)
  390. {
  391. AZ_Warning("PythonBindings", false, "Failed to get GemInfo for gem %s", Py_To_String(path));
  392. }
  393. }
  394. return gemInfo;
  395. }
  396. ProjectInfo PythonBindings::ProjectInfoFromPath(pybind11::handle path)
  397. {
  398. ProjectInfo projectInfo;
  399. projectInfo.m_path = Py_To_String(path);
  400. auto projectData = m_registration.attr("get_project_data")(pybind11::none(), path);
  401. if (pybind11::isinstance<pybind11::dict>(projectData))
  402. {
  403. try
  404. {
  405. projectInfo.m_projectName = Py_To_String(projectData["project_name"]);
  406. projectInfo.m_displayName = Py_To_String_Optional(projectData,"display_name", projectInfo.m_projectName);
  407. }
  408. catch ([[maybe_unused]] const std::exception& e)
  409. {
  410. AZ_Warning("PythonBindings", false, "Failed to get ProjectInfo for project %s", Py_To_String(path));
  411. }
  412. }
  413. return projectInfo;
  414. }
  415. AZ::Outcome<QVector<ProjectInfo>> PythonBindings::GetProjects()
  416. {
  417. QVector<ProjectInfo> projects;
  418. bool result = ExecuteWithLock([&] {
  419. // external projects
  420. for (auto path : m_registration.attr("get_projects")())
  421. {
  422. projects.push_back(ProjectInfoFromPath(path));
  423. }
  424. // projects from the engine
  425. for (auto path : m_registration.attr("get_engine_projects")())
  426. {
  427. projects.push_back(ProjectInfoFromPath(path));
  428. }
  429. });
  430. if (!result)
  431. {
  432. return AZ::Failure();
  433. }
  434. else
  435. {
  436. return AZ::Success(AZStd::move(projects));
  437. }
  438. }
  439. bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo)
  440. {
  441. return false;
  442. }
  443. ProjectTemplateInfo PythonBindings::ProjectTemplateInfoFromPath(pybind11::handle path)
  444. {
  445. ProjectTemplateInfo templateInfo;
  446. templateInfo.m_path = Py_To_String(path);
  447. auto data = m_registration.attr("get_template_data")(pybind11::none(), path);
  448. if (pybind11::isinstance<pybind11::dict>(data))
  449. {
  450. try
  451. {
  452. // required
  453. templateInfo.m_displayName = Py_To_String(data["display_name"]);
  454. templateInfo.m_name = Py_To_String(data["template_name"]);
  455. templateInfo.m_summary = Py_To_String(data["summary"]);
  456. // optional
  457. if (data.contains("canonical_tags"))
  458. {
  459. for (auto tag : data["canonical_tags"])
  460. {
  461. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  462. }
  463. }
  464. if (data.contains("user_tags"))
  465. {
  466. for (auto tag : data["user_tags"])
  467. {
  468. templateInfo.m_canonicalTags.push_back(Py_To_String(tag));
  469. }
  470. }
  471. }
  472. catch ([[maybe_unused]] const std::exception& e)
  473. {
  474. AZ_Warning("PythonBindings", false, "Failed to get ProjectTemplateInfo for %s", Py_To_String(path));
  475. }
  476. }
  477. return templateInfo;
  478. }
  479. AZ::Outcome<QVector<ProjectTemplateInfo>> PythonBindings::GetProjectTemplates()
  480. {
  481. QVector<ProjectTemplateInfo> templates;
  482. bool result = ExecuteWithLock([&] {
  483. for (auto path : m_registration.attr("get_project_templates")())
  484. {
  485. templates.push_back(ProjectTemplateInfoFromPath(path));
  486. }
  487. });
  488. if (!result)
  489. {
  490. return AZ::Failure();
  491. }
  492. else
  493. {
  494. return AZ::Success(AZStd::move(templates));
  495. }
  496. }
  497. }