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.

498 lines
13 KiB

7 years ago
7 years ago
7 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-2021 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 <sstream>
  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 <settings/settings_manager.h>
  43. #include <kiplatform/environment.h>
  44. #include <wx/app.h>
  45. #include <config.h>
  46. SCRIPTING::SCRIPTING()
  47. {
  48. scriptingSetup();
  49. pybind11::initialize_interpreter();
  50. // Save the current Python thread state and release the Global Interpreter Lock.
  51. m_python_thread_state = PyEval_SaveThread();
  52. }
  53. SCRIPTING::~SCRIPTING()
  54. {
  55. PyEval_RestoreThread( m_python_thread_state );
  56. try
  57. {
  58. pybind11::finalize_interpreter();
  59. }
  60. catch( const std::runtime_error& exc )
  61. {
  62. wxLogError( wxT( "Run time error '%s' occurred closing Python scripting" ), exc.what() );
  63. }
  64. }
  65. bool SCRIPTING::IsWxAvailable()
  66. {
  67. #ifdef KICAD_SCRIPTING_WXPYTHON
  68. return true;
  69. #else
  70. return false;
  71. #endif
  72. }
  73. bool SCRIPTING::IsModuleLoaded( std::string& aModule )
  74. {
  75. PyLOCK lock;
  76. using namespace pybind11::literals;
  77. auto locals = pybind11::dict( "modulename"_a = aModule );
  78. pybind11::exec( R"(
  79. import sys
  80. loaded = False
  81. if modulename in sys.modules:
  82. loaded = True
  83. )", pybind11::globals(), locals );
  84. return locals["loaded"].cast<bool>();
  85. }
  86. bool SCRIPTING::scriptingSetup()
  87. {
  88. #if defined( __WINDOWS__ )
  89. #ifdef _MSC_VER
  90. // Under vcpkg/msvc, we need to explicitly set the python home or else it'll start consuming
  91. // system python registry keys and the like instead of the Python distributed with KiCad.
  92. // We are going to follow the "unix" layout for the msvc/vcpkg distributions so executable
  93. // files are in the /root/bin path and the Python library files are in the
  94. // /root/lib/python3(/Lib,/DLLs) path(s).
  95. wxFileName pyHome;
  96. pyHome.Assign( Pgm().GetExecutablePath() );
  97. pyHome.Normalize();
  98. // MUST be called before Py_Initialize so it will to create valid default lib paths
  99. if( !wxGetEnv( wxT( "KICAD_USE_EXTERNAL_PYTHONHOME" ), nullptr ) )
  100. {
  101. Py_SetPythonHome( pyHome.GetFullPath().c_str() );
  102. }
  103. #else
  104. // Intended for msys2 but we could probably use the msvc equivalent code too
  105. // If our python.exe (in kicad/bin) exists, force our kicad python environment
  106. wxString kipython = FindKicadFile( "python.exe" );
  107. // we need only the path:
  108. wxFileName fn( kipython );
  109. kipython = fn.GetPath();
  110. // If our python install is existing inside kicad, use it
  111. // Note: this is useful only when another python version is installed
  112. if( wxDirExists( kipython ) )
  113. {
  114. // clear any PYTHONPATH and PYTHONHOME env var definition: the default
  115. // values work fine inside Kicad:
  116. wxSetEnv( wxT( "PYTHONPATH" ), wxEmptyString );
  117. wxSetEnv( wxT( "PYTHONHOME" ), wxEmptyString );
  118. // Add our python executable path in first position:
  119. wxString ppath;
  120. wxGetEnv( wxT( "PATH" ), &ppath );
  121. kipython << wxT( ";" ) << ppath;
  122. wxSetEnv( wxT( "PATH" ), kipython );
  123. }
  124. #endif
  125. #elif defined( __WXMAC__ )
  126. // Add default paths to PYTHONPATH
  127. wxString pypath;
  128. // Bundle scripting folder (<kicad.app>/Contents/SharedSupport/scripting)
  129. pypath += PATHS::GetOSXKicadDataDir() + wxT( "/scripting" );
  130. // $(KICAD_PATH)/scripting/plugins is always added in kicadplugins.i
  131. if( wxGetenv("KICAD_PATH") != nullptr )
  132. {
  133. pypath += wxT( ":" ) + wxString( wxGetenv("KICAD_PATH") );
  134. }
  135. // OSX_BUNDLE_PYTHON_SITE_PACKAGES_DIR is provided via the build system.
  136. pypath += wxT( ":" ) + Pgm().GetExecutablePath() + wxT( OSX_BUNDLE_PYTHON_SITE_PACKAGES_DIR );
  137. // Original content of $PYTHONPATH
  138. if( wxGetenv( wxT( "PYTHONPATH" ) ) != nullptr )
  139. {
  140. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  141. }
  142. // set $PYTHONPATH
  143. wxSetEnv( "PYTHONPATH", pypath );
  144. wxString pyhome;
  145. pyhome += Pgm().GetExecutablePath() +
  146. wxT( "Contents/Frameworks/Python.framework/Versions/Current" );
  147. // set $PYTHONHOME
  148. wxSetEnv( "PYTHONHOME", pyhome );
  149. #else
  150. wxString pypath;
  151. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  152. {
  153. // When running from build dir, python module gets built next to Pcbnew binary
  154. pypath = Pgm().GetExecutablePath() + wxT( "../pcbnew" );
  155. }
  156. else
  157. {
  158. // PYTHON_DEST is the scripts install dir as determined by the build system.
  159. pypath = Pgm().GetExecutablePath() + wxT( "../" PYTHON_DEST );
  160. }
  161. if( !wxIsEmpty( wxGetenv( wxT( "PYTHONPATH" ) ) ) )
  162. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  163. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  164. #endif
  165. wxFileName path( PyPluginsPath( SCRIPTING::PATH_TYPE::USER ) + wxT( "/" ) );
  166. // Ensure the user plugin path exists, and create it if not.
  167. // However, if it cannot be created, this is not a fatal error.
  168. if( !path.DirExists() && !path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
  169. wxLogError( _( "Could not create user scripting path %s." ), path.GetPath() );
  170. return true;
  171. }
  172. /**
  173. * Run a python method from the Pcbnew module.
  174. *
  175. * @param aMethodName is the name of the method (like "pcbnew.myfunction" )
  176. * @param aNames will contain the returned string
  177. */
  178. static void RunPythonMethodWithReturnedString( const char* aMethodName, wxString& aNames )
  179. {
  180. aNames.Clear();
  181. PyLOCK lock;
  182. PyErr_Clear();
  183. PyObject* builtins = PyImport_ImportModule( "pcbnew" );
  184. wxASSERT( builtins );
  185. if( !builtins ) // Something is wrong in pcbnew.py module (incorrect version?)
  186. return;
  187. PyObject* globals = PyDict_New();
  188. PyDict_SetItemString( globals, "pcbnew", builtins );
  189. Py_DECREF( builtins );
  190. // Build the python code
  191. char cmd[1024];
  192. snprintf( cmd, sizeof(cmd), "result = %s()", aMethodName );
  193. // Execute the python code and get the returned data
  194. PyObject* localDict = PyDict_New();
  195. PyObject* pobj = PyRun_String( cmd, Py_file_input, globals, localDict);
  196. Py_DECREF( globals );
  197. if( pobj )
  198. {
  199. PyObject* str = PyDict_GetItemString(localDict, "result" );
  200. const char* str_res = nullptr;
  201. if(str)
  202. {
  203. PyObject* temp_bytes = PyUnicode_AsEncodedString( str, "UTF-8", "strict" );
  204. if( temp_bytes != nullptr )
  205. {
  206. str_res = PyBytes_AS_STRING( temp_bytes );
  207. aNames = FROM_UTF8( str_res );
  208. Py_DECREF( temp_bytes );
  209. }
  210. else
  211. {
  212. wxLogMessage( "cannot encode Unicode python string" );
  213. }
  214. }
  215. else
  216. {
  217. aNames = wxString();
  218. }
  219. Py_DECREF( pobj );
  220. }
  221. Py_DECREF( localDict );
  222. if( PyErr_Occurred() )
  223. wxLogMessage( PyErrStringWithTraceback() );
  224. }
  225. wxString PyEscapeString( const wxString& aSource )
  226. {
  227. wxString converted;
  228. for( wxUniChar c: aSource )
  229. {
  230. if( c == '\\' )
  231. converted += "\\\\";
  232. else if( c == '\'' )
  233. converted += "\\\'";
  234. else if( c == '\"' )
  235. converted += "\\\"";
  236. else
  237. converted += c;
  238. }
  239. return converted;
  240. }
  241. void UpdatePythonEnvVar( const wxString& aVar, const wxString& aValue )
  242. {
  243. char cmd[1024];
  244. // Ensure the interpreter is initialized before we try to interact with it.
  245. if( !Py_IsInitialized() )
  246. return;
  247. wxLogTrace( traceEnvVars, "UpdatePythonEnvVar: Updating Python variable %s = %s",
  248. aVar, aValue );
  249. wxString escapedVar = PyEscapeString( aVar );
  250. wxString escapedVal = PyEscapeString( aValue );
  251. snprintf( cmd, sizeof( cmd ),
  252. "# coding=utf-8\n" // The values could potentially be UTF8.
  253. "import os\n"
  254. "os.environ[\"%s\"]=\"%s\"\n",
  255. TO_UTF8( escapedVar ),
  256. TO_UTF8( escapedVal ) );
  257. PyLOCK lock;
  258. int retv = PyRun_SimpleString( cmd );
  259. if( retv != 0 )
  260. wxLogError( "Python error %d running command:\n\n`%s`", retv, cmd );
  261. }
  262. wxString PyStringToWx( PyObject* aString )
  263. {
  264. wxString ret;
  265. if( !aString )
  266. return ret;
  267. const char* str_res = nullptr;
  268. PyObject* temp_bytes = PyUnicode_AsEncodedString( aString, "UTF-8", "strict" );
  269. if( temp_bytes != nullptr )
  270. {
  271. str_res = PyBytes_AS_STRING( temp_bytes );
  272. ret = FROM_UTF8( str_res );
  273. Py_DECREF( temp_bytes );
  274. }
  275. else
  276. {
  277. wxLogMessage( "cannot encode Unicode python string" );
  278. }
  279. return ret;
  280. }
  281. wxArrayString PyArrayStringToWx( PyObject* aArrayString )
  282. {
  283. wxArrayString ret;
  284. if( !aArrayString )
  285. return ret;
  286. int list_size = PyList_Size( aArrayString );
  287. for( int n = 0; n < list_size; n++ )
  288. {
  289. PyObject* element = PyList_GetItem( aArrayString, n );
  290. if( element )
  291. {
  292. const char* str_res = nullptr;
  293. PyObject* temp_bytes = PyUnicode_AsEncodedString( element, "UTF-8", "strict" );
  294. if( temp_bytes != nullptr )
  295. {
  296. str_res = PyBytes_AS_STRING( temp_bytes );
  297. ret.Add( FROM_UTF8( str_res ), 1 );
  298. Py_DECREF( temp_bytes );
  299. }
  300. else
  301. {
  302. wxLogMessage( "cannot encode Unicode python string" );
  303. }
  304. }
  305. }
  306. return ret;
  307. }
  308. wxString PyErrStringWithTraceback()
  309. {
  310. wxString err;
  311. if( !PyErr_Occurred() )
  312. return err;
  313. PyObject* type;
  314. PyObject* value;
  315. PyObject* traceback;
  316. PyErr_Fetch( &type, &value, &traceback );
  317. PyErr_NormalizeException( &type, &value, &traceback );
  318. if( traceback == nullptr )
  319. {
  320. traceback = Py_None;
  321. Py_INCREF( traceback );
  322. }
  323. PyException_SetTraceback( value, traceback );
  324. PyObject* tracebackModuleString = PyUnicode_FromString( "traceback" );
  325. PyObject* tracebackModule = PyImport_Import( tracebackModuleString );
  326. Py_DECREF( tracebackModuleString );
  327. PyObject* formatException = PyObject_GetAttrString( tracebackModule,
  328. "format_exception" );
  329. Py_DECREF( tracebackModule );
  330. PyObject* args = Py_BuildValue( "(O,O,O)", type, value, traceback );
  331. PyObject* result = PyObject_CallObject( formatException, args );
  332. Py_XDECREF( formatException );
  333. Py_XDECREF( args );
  334. Py_XDECREF( type );
  335. Py_XDECREF( value );
  336. Py_XDECREF( traceback );
  337. wxArrayString res = PyArrayStringToWx( result );
  338. for( unsigned i = 0; i<res.Count(); i++ )
  339. {
  340. err += res[i] + wxT( "\n" );
  341. }
  342. PyErr_Clear();
  343. return err;
  344. }
  345. /**
  346. * Find the Python scripting path.
  347. */
  348. wxString SCRIPTING::PyScriptingPath( PATH_TYPE aPathType )
  349. {
  350. wxString path;
  351. //@todo This should this be a user configurable variable eg KISCRIPT?
  352. switch( aPathType )
  353. {
  354. case STOCK:
  355. path = PATHS::GetStockScriptingPath();
  356. break;
  357. case USER:
  358. path = PATHS::GetUserScriptingPath();
  359. break;
  360. case THIRDPARTY:
  361. const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
  362. auto it = env.find( "KICAD6_3RD_PARTY" );
  363. if( it != env.end() && !it->second.GetValue().IsEmpty() )
  364. path = it->second.GetValue();
  365. else
  366. path = PATHS::GetDefault3rdPartyPath();
  367. break;
  368. }
  369. wxFileName scriptPath( path );
  370. scriptPath.MakeAbsolute();
  371. // Convert '\' to '/' in path, because later python script read \n or \r
  372. // as escaped sequence, and create issues, when calling it by PyRun_SimpleString() method.
  373. // It can happen on Windows.
  374. path = scriptPath.GetFullPath();
  375. path.Replace( '\\', '/' );
  376. return path;
  377. }
  378. wxString SCRIPTING::PyPluginsPath( PATH_TYPE aPathType )
  379. {
  380. // Note we are using unix path separator, because window separator sometimes
  381. // creates issues when passing a command string to a python method by PyRun_SimpleString
  382. return PyScriptingPath( aPathType ) + '/' + "plugins";
  383. }