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.

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