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.

459 lines
12 KiB

  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-2016 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 <stdlib.h>
  30. #include <string.h>
  31. #include <fctsys.h>
  32. #include <wxstruct.h>
  33. #include <common.h>
  34. #include <gal/color4d.h>
  35. #include <macros.h>
  36. #include <pgm_base.h>
  37. /* init functions defined by swig */
  38. extern "C" void init_kicad( void );
  39. extern "C" void init_pcbnew( void );
  40. #define EXTRA_PYTHON_MODULES 10 // this is the number of python
  41. // modules that we want to add into the list
  42. /* python inittab that links module names to module init functions
  43. * we will rebuild it to include the original python modules plus
  44. * our own ones
  45. */
  46. struct _inittab* SwigImportInittab;
  47. static int SwigNumModules = 0;
  48. static bool wxPythonLoaded = false; // true if the wxPython scripting layer was successfully loaded
  49. bool IsWxPythonLoaded()
  50. {
  51. return wxPythonLoaded;
  52. }
  53. /* Add a name + initfuction to our SwigImportInittab */
  54. static void swigAddModule( const char* name, void (* initfunc)() )
  55. {
  56. SwigImportInittab[SwigNumModules].name = (char*) name;
  57. SwigImportInittab[SwigNumModules].initfunc = initfunc;
  58. SwigNumModules++;
  59. SwigImportInittab[SwigNumModules].name = (char*) 0;
  60. SwigImportInittab[SwigNumModules].initfunc = 0;
  61. }
  62. /* Add the builtin python modules */
  63. static void swigAddBuiltin()
  64. {
  65. int i = 0;
  66. /* discover the length of the pyimport inittab */
  67. while( PyImport_Inittab[i].name )
  68. i++;
  69. /* allocate memory for the python module table */
  70. SwigImportInittab = (struct _inittab*) malloc(
  71. sizeof(struct _inittab) * (i + EXTRA_PYTHON_MODULES) );
  72. /* copy all pre-existing python modules into our newly created table */
  73. i = 0;
  74. while( PyImport_Inittab[i].name )
  75. {
  76. swigAddModule( PyImport_Inittab[i].name, PyImport_Inittab[i].initfunc );
  77. i++;
  78. }
  79. }
  80. /* Function swigAddModules
  81. * adds the internal modules we offer to the python scripting, so they will be
  82. * available to the scripts we run.
  83. *
  84. */
  85. static void swigAddModules()
  86. {
  87. swigAddModule( "_pcbnew", init_pcbnew );
  88. // finally it seems better to include all in just one module
  89. // but in case we needed to include any other modules,
  90. // it must be done like this:
  91. // swigAddModule( "_kicad", init_kicad );
  92. }
  93. /* Function swigSwitchPythonBuiltin
  94. * switches python module table to our built one .
  95. *
  96. */
  97. static void swigSwitchPythonBuiltin()
  98. {
  99. PyImport_Inittab = SwigImportInittab;
  100. }
  101. /* Function pcbnewInitPythonScripting
  102. * Initializes all the python environment and publish our interface inside it
  103. * initializes all the wxpython interface, and returns the python thread control structure
  104. *
  105. */
  106. PyThreadState* g_PythonMainTState;
  107. bool pcbnewInitPythonScripting( const char * aUserScriptingPath )
  108. {
  109. swigAddBuiltin(); // add builtin functions
  110. swigAddModules(); // add our own modules
  111. swigSwitchPythonBuiltin(); // switch the python builtin modules to our new list
  112. Py_Initialize();
  113. #ifdef KICAD_SCRIPTING_WXPYTHON
  114. PyEval_InitThreads();
  115. #ifndef __WINDOWS__ // import wxversion.py currently not working under winbuilder, and not useful.
  116. char cmd[1024];
  117. // Make sure that that the correct version of wxPython is loaded. In systems where there
  118. // are different versions of wxPython installed this can lead to select wrong wxPython
  119. // version being selected.
  120. snprintf( cmd, sizeof(cmd), "import wxversion; wxversion.select('%s')", WXPYTHON_VERSION );
  121. int retv = PyRun_SimpleString( cmd );
  122. if( retv != 0 )
  123. {
  124. wxLogError( wxT( "Python error %d occurred running string `%s`" ), retv, cmd );
  125. PyErr_Print();
  126. Py_Finalize();
  127. return false;
  128. }
  129. #endif // ifndef __WINDOWS__
  130. // Load the wxPython core API. Imports the wx._core_ module and sets a
  131. // local pointer to a function table located there. The pointer is used
  132. // internally by the rest of the API functions.
  133. if( !wxPyCoreAPI_IMPORT() )
  134. {
  135. wxLogError( wxT( "***** Error importing the wxPython API! *****" ) );
  136. PyErr_Print();
  137. Py_Finalize();
  138. return false;
  139. }
  140. wxPythonLoaded = true;
  141. // Save the current Python thread state and release the
  142. // Global Interpreter Lock.
  143. g_PythonMainTState = wxPyBeginAllowThreads();
  144. #endif // ifdef KICAD_SCRIPTING_WXPYTHON
  145. // load pcbnew inside python, and load all the user plugins, TODO: add system wide plugins
  146. {
  147. char loadCmd[1024];
  148. PyLOCK lock;
  149. snprintf( loadCmd, sizeof(loadCmd), "import sys, traceback\n"
  150. "sys.path.append(\".\")\n"
  151. "import pcbnew\n"
  152. "pcbnew.LoadPlugins(\"%s\")", aUserScriptingPath );
  153. PyRun_SimpleString( loadCmd );
  154. }
  155. return true;
  156. }
  157. /**
  158. * this function runs a python method from pcbnew module, which returns a string
  159. * @param aMethodName is the name of the method (like "pcbnew.myfunction" )
  160. * @param aNames will contains the returned string
  161. */
  162. static void pcbnewRunPythonMethodWithReturnedString( const char* aMethodName, wxString& aNames )
  163. {
  164. aNames.Clear();
  165. PyLOCK lock;
  166. PyErr_Clear();
  167. PyObject* builtins = PyImport_ImportModule( "pcbnew" );
  168. wxASSERT( builtins );
  169. if( !builtins ) // Something is wrong in pcbnew.py module (incorrect version?)
  170. return;
  171. PyObject* globals = PyDict_New();
  172. PyDict_SetItemString( globals, "pcbnew", builtins );
  173. Py_DECREF( builtins );
  174. // Build the python code
  175. char cmd[1024];
  176. snprintf( cmd, sizeof(cmd), "result = %s()", aMethodName );
  177. // Execute the python code and get the returned data
  178. PyObject* localDict = PyDict_New();
  179. PyObject* pobj = PyRun_String( cmd, Py_file_input, globals, localDict);
  180. Py_DECREF( globals );
  181. if( pobj )
  182. {
  183. PyObject* str = PyDict_GetItemString(localDict, "result" );
  184. const char* str_res = str ? PyString_AsString( str ) : 0;
  185. aNames = FROM_UTF8( str_res );
  186. Py_DECREF( pobj );
  187. }
  188. Py_DECREF( localDict );
  189. if( PyErr_Occurred() )
  190. wxLogMessage(PyErrStringWithTraceback());
  191. }
  192. void pcbnewGetUnloadableScriptNames( wxString& aNames )
  193. {
  194. pcbnewRunPythonMethodWithReturnedString( "pcbnew.GetUnLoadableWizards", aNames );
  195. }
  196. void pcbnewGetScriptsSearchPaths( wxString& aNames )
  197. {
  198. pcbnewRunPythonMethodWithReturnedString( "pcbnew.GetWizardsSearchPaths", aNames );
  199. }
  200. void pcbnewGetWizardsBackTrace( wxString& aNames )
  201. {
  202. pcbnewRunPythonMethodWithReturnedString( "pcbnew.GetWizardsBackTrace", aNames );
  203. }
  204. void pcbnewFinishPythonScripting()
  205. {
  206. #ifdef KICAD_SCRIPTING_WXPYTHON
  207. wxPyEndAllowThreads( g_PythonMainTState );
  208. #endif
  209. Py_Finalize();
  210. }
  211. #if defined( KICAD_SCRIPTING_WXPYTHON )
  212. void RedirectStdio()
  213. {
  214. // This is a helpful little tidbit to help debugging and such. It
  215. // redirects Python's stdout and stderr to a window that will popup
  216. // only on demand when something is printed, like a traceback.
  217. const char* python_redirect =
  218. "import sys\n"
  219. "import wx\n"
  220. "output = wx.PyOnDemandOutputWindow()\n"
  221. "sys.stderr = output\n";
  222. PyLOCK lock;
  223. PyRun_SimpleString( python_redirect );
  224. }
  225. wxWindow* CreatePythonShellWindow( wxWindow* parent, const wxString& aFramenameId )
  226. {
  227. const char* pcbnew_pyshell =
  228. "import kicad_pyshell\n"
  229. "\n"
  230. "def makeWindow(parent):\n"
  231. " return kicad_pyshell.makePcbnewShellWindow(parent)\n"
  232. "\n";
  233. wxWindow* window = NULL;
  234. PyObject* result;
  235. // As always, first grab the GIL
  236. PyLOCK lock;
  237. // Now make a dictionary to serve as the global namespace when the code is
  238. // executed. Put a reference to the builtins module in it.
  239. PyObject* globals = PyDict_New();
  240. PyObject* builtins = PyImport_ImportModule( "__builtin__" );
  241. PyDict_SetItemString( globals, "__builtins__", builtins );
  242. Py_DECREF( builtins );
  243. // Execute the code to make the makeWindow function we defined above
  244. result = PyRun_String( pcbnew_pyshell, Py_file_input, globals, globals );
  245. // Was there an exception?
  246. if( !result )
  247. {
  248. PyErr_Print();
  249. return NULL;
  250. }
  251. Py_DECREF( result );
  252. // Now there should be an object named 'makeWindow' in the dictionary that
  253. // we can grab a pointer to:
  254. PyObject* func = PyDict_GetItemString( globals, "makeWindow" );
  255. wxASSERT( PyCallable_Check( func ) );
  256. // Now build an argument tuple and call the Python function. Notice the
  257. // use of another wxPython API to take a wxWindows object and build a
  258. // wxPython object that wraps it.
  259. PyObject* arg = wxPyMake_wxObject( parent, false );
  260. wxASSERT( arg != NULL );
  261. PyObject* tuple = PyTuple_New( 1 );
  262. PyTuple_SET_ITEM( tuple, 0, arg );
  263. result = PyEval_CallObject( func, tuple );
  264. // Was there an exception?
  265. if( !result )
  266. PyErr_Print();
  267. else
  268. {
  269. // Otherwise, get the returned window out of Python-land and
  270. // into C++-ville...
  271. bool success = wxPyConvertSwigPtr( result, (void**) &window, "wxWindow" );
  272. (void) success;
  273. wxASSERT_MSG( success, "Returned object was not a wxWindow!" );
  274. Py_DECREF( result );
  275. window->SetName( aFramenameId );
  276. }
  277. // Release the python objects we still have
  278. Py_DECREF( globals );
  279. Py_DECREF( tuple );
  280. return window;
  281. }
  282. #endif
  283. wxArrayString PyArrayStringToWx( PyObject* aArrayString )
  284. {
  285. wxArrayString ret;
  286. if( !aArrayString )
  287. return ret;
  288. int list_size = PyList_Size( aArrayString );
  289. for( int n = 0; n < list_size; n++ )
  290. {
  291. PyObject* element = PyList_GetItem( aArrayString, n );
  292. if( element )
  293. ret.Add( FROM_UTF8( PyString_AsString( element ) ), 1 );
  294. }
  295. return ret;
  296. }
  297. wxString PyErrStringWithTraceback()
  298. {
  299. wxString err;
  300. if( !PyErr_Occurred() )
  301. return err;
  302. PyObject* type;
  303. PyObject* value;
  304. PyObject* traceback;
  305. PyErr_Fetch( &type, &value, &traceback );
  306. PyObject* tracebackModuleString = PyString_FromString( "traceback" );
  307. PyObject* tracebackModule = PyImport_Import( tracebackModuleString );
  308. Py_DECREF( tracebackModuleString );
  309. PyObject* formatException = PyObject_GetAttrString( tracebackModule,
  310. "format_exception" );
  311. Py_DECREF( tracebackModule );
  312. PyObject* args = Py_BuildValue( "(O,O,O)", type, value, traceback );
  313. PyObject* result = PyObject_CallObject( formatException, args );
  314. Py_XDECREF( formatException );
  315. Py_XDECREF( args );
  316. Py_XDECREF( type );
  317. Py_XDECREF( value );
  318. Py_XDECREF( traceback );
  319. wxArrayString res = PyArrayStringToWx( result );
  320. for( unsigned i = 0; i<res.Count(); i++ )
  321. {
  322. err += res[i] + wxT( "\n" );
  323. }
  324. PyErr_Clear();
  325. return err;
  326. }
  327. /**
  328. * Find the Python scripting path
  329. */
  330. wxString PyScriptingPath()
  331. {
  332. wxString path;
  333. //TODO should this be a user configurable variable eg KISCRIPT ?
  334. #if defined( __WXMAC__ )
  335. path = GetOSXKicadDataDir() + wxT( "/scripting" );
  336. #else
  337. path = Pgm().GetExecutablePath() + wxT( "../share/kicad/scripting" );
  338. #endif
  339. wxFileName scriptPath( path );
  340. scriptPath.MakeAbsolute();
  341. return scriptPath.GetFullPath();
  342. }
  343. wxString PyPluginsPath()
  344. {
  345. return PyScriptingPath() + wxFileName::GetPathSeparator() + "plugins";
  346. }