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.

576 lines
16 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. import traceback
  80. import sys
  81. sys_version = sys.version
  82. wx_version = ""
  83. exception_output = ""
  84. try:
  85. from wx import version
  86. wx_version = version()
  87. # Import wx modules that re-initialize wx globals, because they break wxPropertyGrid
  88. # (and probably some other stuff) if we let this happen after we already have started
  89. # mutating those globals.
  90. import wx.adv, wx.html, wx.richtext
  91. except Exception as e:
  92. exception_output = "".join(traceback.format_exc())
  93. )", pybind11::globals(), locals );
  94. const auto getLocal = [&]( const wxString& aName ) -> wxString
  95. {
  96. return wxString( locals[aName.ToStdString().c_str()].cast<std::string>().c_str(),
  97. wxConvUTF8 );
  98. };
  99. // e.g. "4.0.7 gtk3 (phoenix) wxWidgets 3.0.4"
  100. wxString version = getLocal( "wx_version" );
  101. int idx = version.Find( wxT( "wxWidgets " ) );
  102. if( idx == wxNOT_FOUND || version.IsEmpty() )
  103. {
  104. wxString msg = wxString::Format( wxT( "Could not determine wxWidgets version. "
  105. "Python plugins will not be available." ),
  106. version );
  107. msg << wxString::Format( wxT( "\n\nsys.version: '%s'" ), getLocal( "sys_version" ) );
  108. msg << wxString::Format( wxT( "\nwx.version(): '%s'" ), getLocal( "wx_version" ) );
  109. const wxString exception_output = getLocal( "exception_output" );
  110. if( !exception_output.IsEmpty() )
  111. msg << wxT( "\n\n" ) << exception_output;
  112. wxLogError( msg );
  113. available = false;
  114. }
  115. else
  116. {
  117. wxVersionInfo wxVI = wxGetLibraryVersionInfo();
  118. wxString wxVersion = wxString::Format( wxT( "%d.%d.%d" ),
  119. wxVI.GetMajor(), wxVI.GetMinor(), wxVI.GetMicro() );
  120. version = version.Mid( idx + 10 );
  121. long wxPy_major = 0;
  122. long wxPy_minor = 0;
  123. long wxPy_micro = 0;
  124. long wxPy_rev = 0;
  125. // Compile a regex to extract the wxPython version
  126. wxRegEx re( "([0-9]+)\\.([0-9]+)\\.?([0-9]+)?\\.?([0-9]+)?" );
  127. wxASSERT( re.IsValid() );
  128. if( re.Matches( version ) )
  129. {
  130. wxString v = re.GetMatch( version, 1 );
  131. if( !v.IsEmpty() )
  132. v.ToLong( &wxPy_major );
  133. v = re.GetMatch( version, 2 );
  134. if( !v.IsEmpty() )
  135. v.ToLong( &wxPy_minor );
  136. v = re.GetMatch( version, 3 );
  137. if( !v.IsEmpty() )
  138. v.ToLong( &wxPy_micro );
  139. v = re.GetMatch( version, 4 );
  140. if( !v.IsEmpty() )
  141. v.ToLong( &wxPy_rev );
  142. }
  143. if( ( wxVI.GetMajor() != wxPy_major ) || ( wxVI.GetMinor() != wxPy_minor ) )
  144. {
  145. wxString msg = wxT( "The wxPython library was compiled against wxWidgets %s but KiCad is "
  146. "using %s. Python plugins will not be available." );
  147. wxLogError( wxString::Format( msg, version, wxVersion ) );
  148. available = false;
  149. }
  150. }
  151. run = true;
  152. return available;
  153. #else
  154. return false;
  155. #endif
  156. }
  157. bool SCRIPTING::IsModuleLoaded( std::string& aModule )
  158. {
  159. PyLOCK lock;
  160. using namespace pybind11::literals;
  161. auto locals = pybind11::dict( "modulename"_a = aModule );
  162. pybind11::exec( R"(
  163. import sys
  164. loaded = False
  165. if modulename in sys.modules:
  166. loaded = True
  167. )", pybind11::globals(), locals );
  168. return locals["loaded"].cast<bool>();
  169. }
  170. bool SCRIPTING::scriptingSetup()
  171. {
  172. #if defined( __WINDOWS__ )
  173. #ifdef _MSC_VER
  174. // Under vcpkg/msvc, we need to explicitly set the python home or else it'll start consuming
  175. // system python registry keys and the like instead of the Python distributed with KiCad.
  176. // We are going to follow the "unix" layout for the msvc/vcpkg distributions so executable
  177. // files are in the /root/bin path and the Python library files are in the
  178. // /root/lib/python3(/Lib,/DLLs) path(s).
  179. wxFileName pyHome;
  180. pyHome.Assign( Pgm().GetExecutablePath() );
  181. // @warning Do we want to use our own ExpandEnvVarSubstitutions() here rather than depend
  182. // on wxFileName::Normalize() to expand environment variables.
  183. pyHome.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
  184. // MUST be called before Py_Initialize so it will to create valid default lib paths
  185. if( !wxGetEnv( wxT( "KICAD_USE_EXTERNAL_PYTHONHOME" ), nullptr ) )
  186. {
  187. // Global config flag to ignore PYTHONPATH & PYTHONHOME
  188. Py_IgnoreEnvironmentFlag = 1;
  189. // Extra insurance to ignore PYTHONPATH and PYTHONHOME
  190. wxSetEnv( wxT( "PYTHONPATH" ), wxEmptyString );
  191. wxSetEnv( wxT( "PYTHONHOME" ), wxEmptyString );
  192. // Now initialize Python Home via capi
  193. Py_SetPythonHome( pyHome.GetFullPath().c_str() );
  194. }
  195. #else
  196. // Intended for msys2 but we could probably use the msvc equivalent code too
  197. // If our python.exe (in kicad/bin) exists, force our kicad python environment
  198. wxString kipython = FindKicadFile( "python.exe" );
  199. // we need only the path:
  200. wxFileName fn( kipython );
  201. kipython = fn.GetPath();
  202. // If our python install is existing inside kicad, use it
  203. // Note: this is useful only when another python version is installed
  204. if( wxDirExists( kipython ) )
  205. {
  206. // clear any PYTHONPATH and PYTHONHOME env var definition: the default
  207. // values work fine inside Kicad:
  208. wxSetEnv( wxT( "PYTHONPATH" ), wxEmptyString );
  209. wxSetEnv( wxT( "PYTHONHOME" ), wxEmptyString );
  210. // Add our python executable path in first position:
  211. wxString ppath;
  212. wxGetEnv( wxT( "PATH" ), &ppath );
  213. kipython << wxT( ";" ) << ppath;
  214. wxSetEnv( wxT( "PATH" ), kipython );
  215. }
  216. #endif
  217. #elif defined( __WXMAC__ )
  218. // Prevent Mac builds from generating JIT versions as this will break
  219. // the package signing
  220. wxSetEnv( wxT( "PYTHONDONTWRITEBYTECODE" ), wxT( "1" ) );
  221. // Add default paths to PYTHONPATH
  222. wxString pypath;
  223. // Bundle scripting folder (<kicad.app>/Contents/SharedSupport/scripting)
  224. pypath += PATHS::GetOSXKicadDataDir() + wxT( "/scripting" );
  225. // $(KICAD_PATH)/scripting/plugins is always added in kicadplugins.i
  226. if( wxGetenv( "KICAD_PATH" ) != nullptr )
  227. {
  228. pypath += wxT( ":" ) + wxString( wxGetenv("KICAD_PATH") );
  229. }
  230. // OSX_BUNDLE_PYTHON_SITE_PACKAGES_DIR is provided via the build system.
  231. pypath += wxT( ":" ) + Pgm().GetExecutablePath() + wxT( OSX_BUNDLE_PYTHON_SITE_PACKAGES_DIR );
  232. // Original content of $PYTHONPATH
  233. if( wxGetenv( wxT( "PYTHONPATH" ) ) != nullptr )
  234. {
  235. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  236. }
  237. // Hack for run from build dir option
  238. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  239. {
  240. pypath = wxString( wxT( PYTHON_SITE_PACKAGE_PATH ) ) + wxT( "/../:" )
  241. + wxT( PYTHON_SITE_PACKAGE_PATH ) + wxT( ":" ) + wxT( PYTHON_DEST );
  242. }
  243. // set $PYTHONPATH
  244. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  245. wxString pyhome;
  246. pyhome += Pgm().GetExecutablePath() +
  247. wxT( "Contents/Frameworks/Python.framework/Versions/Current" );
  248. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  249. {
  250. pyhome = wxString( wxT( PYTHON_SITE_PACKAGE_PATH ) ) + wxT( "/../../../" );
  251. }
  252. // set $PYTHONHOME
  253. wxSetEnv( wxT( "PYTHONHOME" ), pyhome );
  254. #else
  255. wxString pypath;
  256. if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
  257. {
  258. // When running from build dir, python module gets built next to Pcbnew binary
  259. pypath = Pgm().GetExecutablePath() + wxT( "../pcbnew" );
  260. }
  261. else
  262. {
  263. // PYTHON_DEST is the scripts install dir as determined by the build system.
  264. pypath = Pgm().GetExecutablePath() + wxT( "../" PYTHON_DEST );
  265. }
  266. if( !wxIsEmpty( wxGetenv( wxT( "PYTHONPATH" ) ) ) )
  267. pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
  268. wxSetEnv( wxT( "PYTHONPATH" ), pypath );
  269. #endif
  270. wxFileName path( PyPluginsPath( SCRIPTING::PATH_TYPE::USER ) + wxT( "/" ) );
  271. // Ensure the user plugin path exists, and create it if not.
  272. // However, if it cannot be created, this is not a fatal error.
  273. if( !path.DirExists() && !path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
  274. wxLogError( _( "Could not create user scripting path %s." ), path.GetPath() );
  275. return true;
  276. }
  277. wxString PyEscapeString( const wxString& aSource )
  278. {
  279. wxString converted;
  280. for( wxUniChar c: aSource )
  281. {
  282. if( c == '\\' )
  283. converted += "\\\\";
  284. else if( c == '\'' )
  285. converted += "\\\'";
  286. else if( c == '\"' )
  287. converted += "\\\"";
  288. else
  289. converted += c;
  290. }
  291. return converted;
  292. }
  293. void UpdatePythonEnvVar( const wxString& aVar, const wxString& aValue )
  294. {
  295. char cmd[1024];
  296. // Ensure the interpreter is initialized before we try to interact with it.
  297. if( !Py_IsInitialized() )
  298. return;
  299. wxLogTrace( traceEnvVars, "UpdatePythonEnvVar: Updating Python variable %s = %s",
  300. aVar, aValue );
  301. wxString escapedVar = PyEscapeString( aVar );
  302. wxString escapedVal = PyEscapeString( aValue );
  303. snprintf( cmd, sizeof( cmd ),
  304. "# coding=utf-8\n" // The values could potentially be UTF8.
  305. "import os\n"
  306. "os.environ[\"%s\"]=\"%s\"\n",
  307. TO_UTF8( escapedVar ),
  308. TO_UTF8( escapedVal ) );
  309. PyLOCK lock;
  310. int retv = PyRun_SimpleString( cmd );
  311. if( retv != 0 )
  312. wxLogError( "Python error %d running command:\n\n`%s`", retv, cmd );
  313. }
  314. wxString PyStringToWx( PyObject* aString )
  315. {
  316. wxString ret;
  317. if( !aString )
  318. return ret;
  319. const char* str_res = nullptr;
  320. PyObject* temp_bytes = PyUnicode_AsEncodedString( aString, "UTF-8", "strict" );
  321. if( temp_bytes != nullptr )
  322. {
  323. str_res = PyBytes_AS_STRING( temp_bytes );
  324. ret = From_UTF8( str_res );
  325. Py_DECREF( temp_bytes );
  326. }
  327. else
  328. {
  329. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  330. }
  331. return ret;
  332. }
  333. wxArrayString PyArrayStringToWx( PyObject* aArrayString )
  334. {
  335. wxArrayString ret;
  336. if( !aArrayString )
  337. return ret;
  338. int list_size = PyList_Size( aArrayString );
  339. for( int n = 0; n < list_size; n++ )
  340. {
  341. PyObject* element = PyList_GetItem( aArrayString, n );
  342. if( element )
  343. {
  344. const char* str_res = nullptr;
  345. PyObject* temp_bytes = PyUnicode_AsEncodedString( element, "UTF-8", "strict" );
  346. if( temp_bytes != nullptr )
  347. {
  348. str_res = PyBytes_AS_STRING( temp_bytes );
  349. ret.Add( From_UTF8( str_res ), 1 );
  350. Py_DECREF( temp_bytes );
  351. }
  352. else
  353. {
  354. wxLogMessage( wxS( "cannot encode Unicode python string" ) );
  355. }
  356. }
  357. }
  358. return ret;
  359. }
  360. wxString PyErrStringWithTraceback()
  361. {
  362. wxString err;
  363. if( !PyErr_Occurred() )
  364. return err;
  365. PyObject* type;
  366. PyObject* value;
  367. PyObject* traceback;
  368. PyErr_Fetch( &type, &value, &traceback );
  369. PyErr_NormalizeException( &type, &value, &traceback );
  370. if( traceback == nullptr )
  371. {
  372. traceback = Py_None;
  373. Py_INCREF( traceback );
  374. }
  375. PyException_SetTraceback( value, traceback );
  376. PyObject* tracebackModuleString = PyUnicode_FromString( "traceback" );
  377. PyObject* tracebackModule = PyImport_Import( tracebackModuleString );
  378. Py_DECREF( tracebackModuleString );
  379. PyObject* formatException = PyObject_GetAttrString( tracebackModule,
  380. "format_exception" );
  381. Py_DECREF( tracebackModule );
  382. PyObject* args = Py_BuildValue( "(O,O,O)", type, value, traceback );
  383. PyObject* result = PyObject_CallObject( formatException, args );
  384. Py_XDECREF( formatException );
  385. Py_XDECREF( args );
  386. Py_XDECREF( type );
  387. Py_XDECREF( value );
  388. Py_XDECREF( traceback );
  389. wxArrayString res = PyArrayStringToWx( result );
  390. for( unsigned i = 0; i<res.Count(); i++ )
  391. {
  392. err += res[i] + wxT( "\n" );
  393. }
  394. PyErr_Clear();
  395. return err;
  396. }
  397. /**
  398. * Find the Python scripting path.
  399. */
  400. wxString SCRIPTING::PyScriptingPath( PATH_TYPE aPathType )
  401. {
  402. wxString path;
  403. //@todo This should this be a user configurable variable eg KISCRIPT?
  404. switch( aPathType )
  405. {
  406. case STOCK:
  407. path = PATHS::GetStockScriptingPath();
  408. break;
  409. case USER:
  410. path = PATHS::GetUserScriptingPath();
  411. break;
  412. case THIRDPARTY:
  413. {
  414. const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
  415. if( std::optional<wxString> v = ENV_VAR::GetVersionedEnvVarValue( env,
  416. wxT( "3RD_PARTY" ) ) )
  417. {
  418. path = *v;
  419. }
  420. else
  421. {
  422. path = PATHS::GetDefault3rdPartyPath();
  423. }
  424. break;
  425. }
  426. }
  427. wxFileName scriptPath( path );
  428. scriptPath.MakeAbsolute();
  429. // Convert '\' to '/' in path, because later python script read \n or \r
  430. // as escaped sequence, and create issues, when calling it by PyRun_SimpleString() method.
  431. // It can happen on Windows.
  432. path = scriptPath.GetFullPath();
  433. path.Replace( '\\', '/' );
  434. return path;
  435. }
  436. wxString SCRIPTING::PyPluginsPath( PATH_TYPE aPathType )
  437. {
  438. // Note we are using unix path separator, because window separator sometimes
  439. // creates issues when passing a command string to a python method by PyRun_SimpleString
  440. return PyScriptingPath( aPathType ) + '/' + "plugins";
  441. }