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.

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