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.

600 lines
16 KiB

7 years ago
7 years ago
7 years ago
3 years ago
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 (C) 1992-2022 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. #include <cstdlib>
  30. #include <cstring>
  31. #include <Python.h>
  32. #include <string>
  33. #include <eda_base_frame.h>
  34. #include <gal/color4d.h>
  35. #include <gestfich.h>
  36. #include <trace_helpers.h>
  37. #include <string_utils.h>
  38. #include <macros.h>
  39. #include <kiface_ids.h>
  40. #include <paths.h>
  41. #include <pgm_base.h>
  42. #include <wx_filename.h>
  43. #include <settings/settings_manager.h>
  44. #include <kiplatform/environment.h>
  45. #include <wx/app.h>
  46. #include <wx/regex.h>
  47. #include <wx/utils.h>
  48. #include <config.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. // set $PYTHONPATH
  222. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  223. wxString pyhome;
  224. pyhome += Pgm().GetExecutablePath() +
  225. wxT( "Contents/Frameworks/Python.framework/Versions/Current" );
  226. // set $PYTHONHOME
  227. wxSetEnv( wxT( "PYTHONHOME" ), pyhome );
  228. #else
  229. wxString pypath;
  230. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  231. {
  232. // When running from build dir, python module gets built next to Pcbnew binary
  233. pypath = Pgm().GetExecutablePath() + wxT( "../pcbnew" );
  234. }
  235. else
  236. {
  237. // PYTHON_DEST is the scripts install dir as determined by the build system.
  238. pypath = Pgm().GetExecutablePath() + wxT( "../" PYTHON_DEST );
  239. }
  240. if( !wxIsEmpty( wxGetenv( wxT( "PYTHONPATH" ) ) ) )
  241. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  242. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  243. #endif
  244. wxFileName path( PyPluginsPath( SCRIPTING::PATH_TYPE::USER ) + wxT( "/" ) );
  245. // Ensure the user plugin path exists, and create it if not.
  246. // However, if it cannot be created, this is not a fatal error.
  247. if( !path.DirExists() && !path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
  248. wxLogError( _( "Could not create user scripting path %s." ), path.GetPath() );
  249. return true;
  250. }
  251. /**
  252. * Run a python method from the Pcbnew module.
  253. *
  254. * @param aMethodName is the name of the method (like "pcbnew.myfunction" )
  255. * @param aNames will contain the returned string
  256. */
  257. static void RunPythonMethodWithReturnedString( const char* aMethodName, wxString& aNames )
  258. {
  259. aNames.Clear();
  260. PyLOCK lock;
  261. PyErr_Clear();
  262. PyObject* builtins = PyImport_ImportModule( "pcbnew" );
  263. wxASSERT( builtins );
  264. if( !builtins ) // Something is wrong in pcbnew.py module (incorrect version?)
  265. return;
  266. PyObject* globals = PyDict_New();
  267. PyDict_SetItemString( globals, "pcbnew", builtins );
  268. Py_DECREF( builtins );
  269. // Build the python code
  270. std::string cmd = "result = " + std::string( aMethodName ) + "()";
  271. // Execute the python code and get the returned data
  272. PyObject* localDict = PyDict_New();
  273. PyObject* pobj = PyRun_String( cmd.c_str(), Py_file_input, globals, localDict );
  274. Py_DECREF( globals );
  275. if( pobj )
  276. {
  277. PyObject* str = PyDict_GetItemString(localDict, "result" );
  278. const char* str_res = nullptr;
  279. if(str)
  280. {
  281. PyObject* temp_bytes = PyUnicode_AsEncodedString( str, "UTF-8", "strict" );
  282. if( temp_bytes != nullptr )
  283. {
  284. str_res = PyBytes_AS_STRING( temp_bytes );
  285. aNames = FROM_UTF8( str_res );
  286. Py_DECREF( temp_bytes );
  287. }
  288. else
  289. {
  290. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  291. }
  292. }
  293. else
  294. {
  295. aNames = wxString();
  296. }
  297. Py_DECREF( pobj );
  298. }
  299. Py_DECREF( localDict );
  300. if( PyErr_Occurred() )
  301. wxLogMessage( PyErrStringWithTraceback() );
  302. }
  303. wxString PyEscapeString( const wxString& aSource )
  304. {
  305. wxString converted;
  306. for( wxUniChar c: aSource )
  307. {
  308. if( c == '\\' )
  309. converted += "\\\\";
  310. else if( c == '\'' )
  311. converted += "\\\'";
  312. else if( c == '\"' )
  313. converted += "\\\"";
  314. else
  315. converted += c;
  316. }
  317. return converted;
  318. }
  319. void UpdatePythonEnvVar( const wxString& aVar, const wxString& aValue )
  320. {
  321. char cmd[1024];
  322. // Ensure the interpreter is initialized before we try to interact with it.
  323. if( !Py_IsInitialized() )
  324. return;
  325. wxLogTrace( traceEnvVars, "UpdatePythonEnvVar: Updating Python variable %s = %s",
  326. aVar, aValue );
  327. wxString escapedVar = PyEscapeString( aVar );
  328. wxString escapedVal = PyEscapeString( aValue );
  329. snprintf( cmd, sizeof( cmd ),
  330. "# coding=utf-8\n" // The values could potentially be UTF8.
  331. "import os\n"
  332. "os.environ[\"%s\"]=\"%s\"\n",
  333. TO_UTF8( escapedVar ),
  334. TO_UTF8( escapedVal ) );
  335. PyLOCK lock;
  336. int retv = PyRun_SimpleString( cmd );
  337. if( retv != 0 )
  338. wxLogError( "Python error %d running command:\n\n`%s`", retv, cmd );
  339. }
  340. wxString PyStringToWx( PyObject* aString )
  341. {
  342. wxString ret;
  343. if( !aString )
  344. return ret;
  345. const char* str_res = nullptr;
  346. PyObject* temp_bytes = PyUnicode_AsEncodedString( aString, "UTF-8", "strict" );
  347. if( temp_bytes != nullptr )
  348. {
  349. str_res = PyBytes_AS_STRING( temp_bytes );
  350. ret = FROM_UTF8( str_res );
  351. Py_DECREF( temp_bytes );
  352. }
  353. else
  354. {
  355. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  356. }
  357. return ret;
  358. }
  359. wxArrayString PyArrayStringToWx( PyObject* aArrayString )
  360. {
  361. wxArrayString ret;
  362. if( !aArrayString )
  363. return ret;
  364. int list_size = PyList_Size( aArrayString );
  365. for( int n = 0; n < list_size; n++ )
  366. {
  367. PyObject* element = PyList_GetItem( aArrayString, n );
  368. if( element )
  369. {
  370. const char* str_res = nullptr;
  371. PyObject* temp_bytes = PyUnicode_AsEncodedString( element, "UTF-8", "strict" );
  372. if( temp_bytes != nullptr )
  373. {
  374. str_res = PyBytes_AS_STRING( temp_bytes );
  375. ret.Add( FROM_UTF8( str_res ), 1 );
  376. Py_DECREF( temp_bytes );
  377. }
  378. else
  379. {
  380. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  381. }
  382. }
  383. }
  384. return ret;
  385. }
  386. wxString PyErrStringWithTraceback()
  387. {
  388. wxString err;
  389. if( !PyErr_Occurred() )
  390. return err;
  391. PyObject* type;
  392. PyObject* value;
  393. PyObject* traceback;
  394. PyErr_Fetch( &type, &value, &traceback );
  395. PyErr_NormalizeException( &type, &value, &traceback );
  396. if( traceback == nullptr )
  397. {
  398. traceback = Py_None;
  399. Py_INCREF( traceback );
  400. }
  401. PyException_SetTraceback( value, traceback );
  402. PyObject* tracebackModuleString = PyUnicode_FromString( "traceback" );
  403. PyObject* tracebackModule = PyImport_Import( tracebackModuleString );
  404. Py_DECREF( tracebackModuleString );
  405. PyObject* formatException = PyObject_GetAttrString( tracebackModule,
  406. "format_exception" );
  407. Py_DECREF( tracebackModule );
  408. PyObject* args = Py_BuildValue( "(O,O,O)", type, value, traceback );
  409. PyObject* result = PyObject_CallObject( formatException, args );
  410. Py_XDECREF( formatException );
  411. Py_XDECREF( args );
  412. Py_XDECREF( type );
  413. Py_XDECREF( value );
  414. Py_XDECREF( traceback );
  415. wxArrayString res = PyArrayStringToWx( result );
  416. for( unsigned i = 0; i<res.Count(); i++ )
  417. {
  418. err += res[i] + wxT( "\n" );
  419. }
  420. PyErr_Clear();
  421. return err;
  422. }
  423. /**
  424. * Find the Python scripting path.
  425. */
  426. wxString SCRIPTING::PyScriptingPath( PATH_TYPE aPathType )
  427. {
  428. wxString path;
  429. //@todo This should this be a user configurable variable eg KISCRIPT?
  430. switch( aPathType )
  431. {
  432. case STOCK:
  433. path = PATHS::GetStockScriptingPath();
  434. break;
  435. case USER:
  436. path = PATHS::GetUserScriptingPath();
  437. break;
  438. case THIRDPARTY:
  439. const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
  440. auto it = env.find( "KICAD7_3RD_PARTY" );
  441. if( it != env.end() && !it->second.GetValue().IsEmpty() )
  442. path = it->second.GetValue();
  443. else
  444. path = PATHS::GetDefault3rdPartyPath();
  445. break;
  446. }
  447. wxFileName scriptPath( path );
  448. scriptPath.MakeAbsolute();
  449. // Convert '\' to '/' in path, because later python script read \n or \r
  450. // as escaped sequence, and create issues, when calling it by PyRun_SimpleString() method.
  451. // It can happen on Windows.
  452. path = scriptPath.GetFullPath();
  453. path.Replace( '\\', '/' );
  454. return path;
  455. }
  456. wxString SCRIPTING::PyPluginsPath( PATH_TYPE aPathType )
  457. {
  458. // Note we are using unix path separator, because window separator sometimes
  459. // creates issues when passing a command string to a python method by PyRun_SimpleString
  460. return PyScriptingPath( aPathType ) + '/' + "plugins";
  461. }