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.

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