You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

555 lines
15 KiB

3 years ago
3 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2012 NBEE Embedded Systems, Miguel Angel Ajo <miguelangel@nbee.es>
  5. * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, you may find one here:
  19. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. * or you may search the http://www.gnu.org website for the version 2 license,
  21. * or you may write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. /**
  25. * @file python_scripting.cpp
  26. * @brief methods to add scripting capabilities inside Pcbnew
  27. */
  28. #include <python_scripting.h>
  29. #undef pid_t
  30. #include <pybind11/embed.h>
  31. #include <cstdlib>
  32. #include <cstring>
  33. #include <string>
  34. #include <env_vars.h>
  35. #include <trace_helpers.h>
  36. #include <string_utils.h>
  37. #include <macros.h>
  38. #include <kiface_ids.h>
  39. #include <paths.h>
  40. #include <pgm_base.h>
  41. #include <wx_filename.h>
  42. #include <settings/settings_manager.h>
  43. #include <kiplatform/environment.h>
  44. #include <wx/app.h>
  45. #include <wx/regex.h>
  46. #include <wx/utils.h>
  47. #include <config.h>
  48. #include <gestfich.h>
  49. SCRIPTING::SCRIPTING()
  50. {
  51. scriptingSetup();
  52. pybind11::initialize_interpreter();
  53. // Save the current Python thread state and release the Global Interpreter Lock.
  54. m_python_thread_state = PyEval_SaveThread();
  55. }
  56. SCRIPTING::~SCRIPTING()
  57. {
  58. PyEval_RestoreThread( m_python_thread_state );
  59. try
  60. {
  61. pybind11::finalize_interpreter();
  62. }
  63. catch( const std::runtime_error& exc )
  64. {
  65. wxLogError( wxT( "Run time error '%s' occurred closing Python scripting" ), exc.what() );
  66. }
  67. }
  68. bool SCRIPTING::IsWxAvailable()
  69. {
  70. #ifdef KICAD_SCRIPTING_WXPYTHON
  71. static bool run = false;
  72. static bool available = true;
  73. if( run )
  74. return available;
  75. PyLOCK lock;
  76. using namespace pybind11::literals;
  77. pybind11::dict locals;
  78. pybind11::exec( R"(
  79. wx_version = ""
  80. try:
  81. from wx import version
  82. wx_version = version()
  83. # Import wx modules that re-initialize wx globals, because they break wxPropertyGrid
  84. # (and probably some other stuff) if we let this happen after we already have started
  85. # mutating those globals.
  86. import wx.adv, wx.html, wx.richtext
  87. except:
  88. pass
  89. )", pybind11::globals(), locals );
  90. // e.g. "4.0.7 gtk3 (phoenix) wxWidgets 3.0.4"
  91. wxString version( locals["wx_version"].cast<std::string>().c_str(), wxConvUTF8 );
  92. int idx = version.Find( wxT( "wxWidgets " ) );
  93. if( idx == wxNOT_FOUND || version.IsEmpty() )
  94. {
  95. wxLogError( wxT( "Could not determine wxPython version. "
  96. "Python plugins will not be available." ) );
  97. available = false;
  98. }
  99. else
  100. {
  101. wxVersionInfo wxVI = wxGetLibraryVersionInfo();
  102. wxString wxVersion = wxString::Format( wxT( "%d.%d.%d" ),
  103. wxVI.GetMajor(), wxVI.GetMinor(), wxVI.GetMicro() );
  104. version = version.Mid( idx + 10 );
  105. long wxPy_major = 0;
  106. long wxPy_minor = 0;
  107. long wxPy_micro = 0;
  108. long wxPy_rev = 0;
  109. // Compile a regex to extract the wxPython version
  110. wxRegEx re( "([0-9]+)\\.([0-9]+)\\.?([0-9]+)?\\.?([0-9]+)?" );
  111. wxASSERT( re.IsValid() );
  112. if( re.Matches( version ) )
  113. {
  114. wxString v = re.GetMatch( version, 1 );
  115. if( !v.IsEmpty() )
  116. v.ToLong( &wxPy_major );
  117. v = re.GetMatch( version, 2 );
  118. if( !v.IsEmpty() )
  119. v.ToLong( &wxPy_minor );
  120. v = re.GetMatch( version, 3 );
  121. if( !v.IsEmpty() )
  122. v.ToLong( &wxPy_micro );
  123. v = re.GetMatch( version, 4 );
  124. if( !v.IsEmpty() )
  125. v.ToLong( &wxPy_rev );
  126. }
  127. if( ( wxVI.GetMajor() != wxPy_major ) || ( wxVI.GetMinor() != wxPy_minor ) )
  128. {
  129. wxString msg = wxT( "The wxPython library was compiled against wxWidgets %s but KiCad is "
  130. "using %s. Python plugins will not be available." );
  131. wxLogError( wxString::Format( msg, version, wxVersion ) );
  132. available = false;
  133. }
  134. }
  135. run = true;
  136. return available;
  137. #else
  138. return false;
  139. #endif
  140. }
  141. bool SCRIPTING::IsModuleLoaded( std::string& aModule )
  142. {
  143. PyLOCK lock;
  144. using namespace pybind11::literals;
  145. auto locals = pybind11::dict( "modulename"_a = aModule );
  146. pybind11::exec( R"(
  147. import sys
  148. loaded = False
  149. if modulename in sys.modules:
  150. loaded = True
  151. )", pybind11::globals(), locals );
  152. return locals["loaded"].cast<bool>();
  153. }
  154. bool SCRIPTING::scriptingSetup()
  155. {
  156. #if defined( __WINDOWS__ )
  157. #ifdef _MSC_VER
  158. // Under vcpkg/msvc, we need to explicitly set the python home or else it'll start consuming
  159. // system python registry keys and the like instead of the Python distributed with KiCad.
  160. // We are going to follow the "unix" layout for the msvc/vcpkg distributions so executable
  161. // files are in the /root/bin path and the Python library files are in the
  162. // /root/lib/python3(/Lib,/DLLs) path(s).
  163. wxFileName pyHome;
  164. pyHome.Assign( Pgm().GetExecutablePath() );
  165. // @warning Do we want to use our own ExpandEnvVarSubstitutions() here rather than depend
  166. // on wxFileName::Normalize() to expand environment variables.
  167. pyHome.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
  168. // MUST be called before Py_Initialize so it will to create valid default lib paths
  169. if( !wxGetEnv( wxT( "KICAD_USE_EXTERNAL_PYTHONHOME" ), nullptr ) )
  170. {
  171. // Global config flag to ignore PYTHONPATH & PYTHONHOME
  172. Py_IgnoreEnvironmentFlag = 1;
  173. // Extra insurance to ignore PYTHONPATH and PYTHONHOME
  174. wxSetEnv( wxT( "PYTHONPATH" ), wxEmptyString );
  175. wxSetEnv( wxT( "PYTHONHOME" ), wxEmptyString );
  176. // Now initialize Python Home via capi
  177. Py_SetPythonHome( pyHome.GetFullPath().c_str() );
  178. }
  179. #else
  180. // Intended for msys2 but we could probably use the msvc equivalent code too
  181. // If our python.exe (in kicad/bin) exists, force our kicad python environment
  182. wxString kipython = FindKicadFile( "python.exe" );
  183. // we need only the path:
  184. wxFileName fn( kipython );
  185. kipython = fn.GetPath();
  186. // If our python install is existing inside kicad, use it
  187. // Note: this is useful only when another python version is installed
  188. if( wxDirExists( kipython ) )
  189. {
  190. // clear any PYTHONPATH and PYTHONHOME env var definition: the default
  191. // values work fine inside Kicad:
  192. wxSetEnv( wxT( "PYTHONPATH" ), wxEmptyString );
  193. wxSetEnv( wxT( "PYTHONHOME" ), wxEmptyString );
  194. // Add our python executable path in first position:
  195. wxString ppath;
  196. wxGetEnv( wxT( "PATH" ), &ppath );
  197. kipython << wxT( ";" ) << ppath;
  198. wxSetEnv( wxT( "PATH" ), kipython );
  199. }
  200. #endif
  201. #elif defined( __WXMAC__ )
  202. // Prevent Mac builds from generating JIT versions as this will break
  203. // the package signing
  204. wxSetEnv( wxT( "PYTHONDONTWRITEBYTECODE" ), wxT( "1" ) );
  205. // Add default paths to PYTHONPATH
  206. wxString pypath;
  207. // Bundle scripting folder (<kicad.app>/Contents/SharedSupport/scripting)
  208. pypath += PATHS::GetOSXKicadDataDir() + wxT( "/scripting" );
  209. // $(KICAD_PATH)/scripting/plugins is always added in kicadplugins.i
  210. if( wxGetenv( "KICAD_PATH" ) != nullptr )
  211. {
  212. pypath += wxT( ":" ) + wxString( wxGetenv("KICAD_PATH") );
  213. }
  214. // OSX_BUNDLE_PYTHON_SITE_PACKAGES_DIR is provided via the build system.
  215. pypath += wxT( ":" ) + Pgm().GetExecutablePath() + wxT( OSX_BUNDLE_PYTHON_SITE_PACKAGES_DIR );
  216. // Original content of $PYTHONPATH
  217. if( wxGetenv( wxT( "PYTHONPATH" ) ) != nullptr )
  218. {
  219. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  220. }
  221. // Hack for run from build dir option
  222. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  223. {
  224. pypath = wxString( wxT( PYTHON_SITE_PACKAGE_PATH ) ) + wxT( "/../:" )
  225. + wxT( PYTHON_SITE_PACKAGE_PATH ) + wxT( ":" ) + wxT( PYTHON_DEST );
  226. }
  227. // set $PYTHONPATH
  228. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  229. wxString pyhome;
  230. pyhome += Pgm().GetExecutablePath() +
  231. wxT( "Contents/Frameworks/Python.framework/Versions/Current" );
  232. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  233. {
  234. pyhome = wxString( wxT( PYTHON_SITE_PACKAGE_PATH ) ) + wxT( "/../../../" );
  235. }
  236. // set $PYTHONHOME
  237. wxSetEnv( wxT( "PYTHONHOME" ), pyhome );
  238. #else
  239. wxString pypath;
  240. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  241. {
  242. // When running from build dir, python module gets built next to Pcbnew binary
  243. pypath = Pgm().GetExecutablePath() + wxT( "../pcbnew" );
  244. }
  245. else
  246. {
  247. // PYTHON_DEST is the scripts install dir as determined by the build system.
  248. pypath = Pgm().GetExecutablePath() + wxT( "../" PYTHON_DEST );
  249. }
  250. if( !wxIsEmpty( wxGetenv( wxT( "PYTHONPATH" ) ) ) )
  251. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  252. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  253. #endif
  254. wxFileName path( PyPluginsPath( SCRIPTING::PATH_TYPE::USER ) + wxT( "/" ) );
  255. // Ensure the user plugin path exists, and create it if not.
  256. // However, if it cannot be created, this is not a fatal error.
  257. if( !path.DirExists() && !path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
  258. wxLogError( _( "Could not create user scripting path %s." ), path.GetPath() );
  259. return true;
  260. }
  261. wxString PyEscapeString( const wxString& aSource )
  262. {
  263. wxString converted;
  264. for( wxUniChar c: aSource )
  265. {
  266. if( c == '\\' )
  267. converted += "\\\\";
  268. else if( c == '\'' )
  269. converted += "\\\'";
  270. else if( c == '\"' )
  271. converted += "\\\"";
  272. else
  273. converted += c;
  274. }
  275. return converted;
  276. }
  277. void UpdatePythonEnvVar( const wxString& aVar, const wxString& aValue )
  278. {
  279. char cmd[1024];
  280. // Ensure the interpreter is initialized before we try to interact with it.
  281. if( !Py_IsInitialized() )
  282. return;
  283. wxLogTrace( traceEnvVars, "UpdatePythonEnvVar: Updating Python variable %s = %s",
  284. aVar, aValue );
  285. wxString escapedVar = PyEscapeString( aVar );
  286. wxString escapedVal = PyEscapeString( aValue );
  287. snprintf( cmd, sizeof( cmd ),
  288. "# coding=utf-8\n" // The values could potentially be UTF8.
  289. "import os\n"
  290. "os.environ[\"%s\"]=\"%s\"\n",
  291. TO_UTF8( escapedVar ),
  292. TO_UTF8( escapedVal ) );
  293. PyLOCK lock;
  294. int retv = PyRun_SimpleString( cmd );
  295. if( retv != 0 )
  296. wxLogError( "Python error %d running command:\n\n`%s`", retv, cmd );
  297. }
  298. wxString PyStringToWx( PyObject* aString )
  299. {
  300. wxString ret;
  301. if( !aString )
  302. return ret;
  303. const char* str_res = nullptr;
  304. PyObject* temp_bytes = PyUnicode_AsEncodedString( aString, "UTF-8", "strict" );
  305. if( temp_bytes != nullptr )
  306. {
  307. str_res = PyBytes_AS_STRING( temp_bytes );
  308. ret = From_UTF8( str_res );
  309. Py_DECREF( temp_bytes );
  310. }
  311. else
  312. {
  313. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  314. }
  315. return ret;
  316. }
  317. wxArrayString PyArrayStringToWx( PyObject* aArrayString )
  318. {
  319. wxArrayString ret;
  320. if( !aArrayString )
  321. return ret;
  322. int list_size = PyList_Size( aArrayString );
  323. for( int n = 0; n < list_size; n++ )
  324. {
  325. PyObject* element = PyList_GetItem( aArrayString, n );
  326. if( element )
  327. {
  328. const char* str_res = nullptr;
  329. PyObject* temp_bytes = PyUnicode_AsEncodedString( element, "UTF-8", "strict" );
  330. if( temp_bytes != nullptr )
  331. {
  332. str_res = PyBytes_AS_STRING( temp_bytes );
  333. ret.Add( From_UTF8( str_res ), 1 );
  334. Py_DECREF( temp_bytes );
  335. }
  336. else
  337. {
  338. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  339. }
  340. }
  341. }
  342. return ret;
  343. }
  344. wxString PyErrStringWithTraceback()
  345. {
  346. wxString err;
  347. if( !PyErr_Occurred() )
  348. return err;
  349. PyObject* type;
  350. PyObject* value;
  351. PyObject* traceback;
  352. PyErr_Fetch( &type, &value, &traceback );
  353. PyErr_NormalizeException( &type, &value, &traceback );
  354. if( traceback == nullptr )
  355. {
  356. traceback = Py_None;
  357. Py_INCREF( traceback );
  358. }
  359. PyException_SetTraceback( value, traceback );
  360. PyObject* tracebackModuleString = PyUnicode_FromString( "traceback" );
  361. PyObject* tracebackModule = PyImport_Import( tracebackModuleString );
  362. Py_DECREF( tracebackModuleString );
  363. PyObject* formatException = PyObject_GetAttrString( tracebackModule,
  364. "format_exception" );
  365. Py_DECREF( tracebackModule );
  366. PyObject* args = Py_BuildValue( "(O,O,O)", type, value, traceback );
  367. PyObject* result = PyObject_CallObject( formatException, args );
  368. Py_XDECREF( formatException );
  369. Py_XDECREF( args );
  370. Py_XDECREF( type );
  371. Py_XDECREF( value );
  372. Py_XDECREF( traceback );
  373. wxArrayString res = PyArrayStringToWx( result );
  374. for( unsigned i = 0; i<res.Count(); i++ )
  375. {
  376. err += res[i] + wxT( "\n" );
  377. }
  378. PyErr_Clear();
  379. return err;
  380. }
  381. /**
  382. * Find the Python scripting path.
  383. */
  384. wxString SCRIPTING::PyScriptingPath( PATH_TYPE aPathType )
  385. {
  386. wxString path;
  387. //@todo This should this be a user configurable variable eg KISCRIPT?
  388. switch( aPathType )
  389. {
  390. case STOCK:
  391. path = PATHS::GetStockScriptingPath();
  392. break;
  393. case USER:
  394. path = PATHS::GetUserScriptingPath();
  395. break;
  396. case THIRDPARTY:
  397. {
  398. const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
  399. if( std::optional<wxString> v = ENV_VAR::GetVersionedEnvVarValue( env,
  400. wxT( "3RD_PARTY" ) ) )
  401. {
  402. path = *v;
  403. }
  404. else
  405. {
  406. path = PATHS::GetDefault3rdPartyPath();
  407. }
  408. break;
  409. }
  410. }
  411. wxFileName scriptPath( path );
  412. scriptPath.MakeAbsolute();
  413. // Convert '\' to '/' in path, because later python script read \n or \r
  414. // as escaped sequence, and create issues, when calling it by PyRun_SimpleString() method.
  415. // It can happen on Windows.
  416. path = scriptPath.GetFullPath();
  417. path.Replace( '\\', '/' );
  418. return path;
  419. }
  420. wxString SCRIPTING::PyPluginsPath( PATH_TYPE aPathType )
  421. {
  422. // Note we are using unix path separator, because window separator sometimes
  423. // creates issues when passing a command string to a python method by PyRun_SimpleString
  424. return PyScriptingPath( aPathType ) + '/' + "plugins";
  425. }