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.

294 lines
8.2 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. /* init functions defined by swig */
  39. extern "C" void init_kicad( void );
  40. extern "C" void init_pcbnew( void );
  41. #define EXTRA_PYTHON_MODULES 10 // this is the number of python
  42. // modules that we want to add into the list
  43. /* python inittab that links module names to module init functions
  44. * we will rebuild it to include the original python modules plus
  45. * our own ones
  46. */
  47. struct _inittab *SwigImportInittab;
  48. static int SwigNumModules = 0;
  49. /* Add a name + initfuction to our SwigImportInittab */
  50. static void swigAddModule( const char* name, void (* initfunc)() )
  51. {
  52. SwigImportInittab[SwigNumModules].name = (char*) name;
  53. SwigImportInittab[SwigNumModules].initfunc = initfunc;
  54. SwigNumModules++;
  55. SwigImportInittab[SwigNumModules].name = (char*) 0;
  56. SwigImportInittab[SwigNumModules].initfunc = 0;
  57. }
  58. /* Add the builting python modules */
  59. static void swigAddBuiltin()
  60. {
  61. int i = 0;
  62. /* discover the length of the pyimport inittab */
  63. while( PyImport_Inittab[i].name )
  64. i++;
  65. /* allocate memory for the python module table */
  66. SwigImportInittab = (struct _inittab*) malloc(
  67. sizeof(struct _inittab)*(i+EXTRA_PYTHON_MODULES));
  68. /* copy all pre-existing python modules into our newly created table */
  69. i=0;
  70. while( PyImport_Inittab[i].name )
  71. {
  72. swigAddModule( PyImport_Inittab[i].name, PyImport_Inittab[i].initfunc );
  73. i++;
  74. }
  75. }
  76. /* Function swigAddModules
  77. * adds the internal modules we offer to the python scripting, so they will be
  78. * available to the scripts we run.
  79. *
  80. */
  81. static void swigAddModules()
  82. {
  83. swigAddModule( "_pcbnew", init_pcbnew );
  84. // finally it seems better to include all in just one module
  85. // but in case we needed to include any other modules,
  86. // it must be done like this:
  87. // swigAddModule("_kicad",init_kicad);
  88. }
  89. /* Function swigSwitchPythonBuiltin
  90. * switches python module table to our built one .
  91. *
  92. */
  93. static void swigSwitchPythonBuiltin()
  94. {
  95. PyImport_Inittab = SwigImportInittab;
  96. }
  97. /* Function pcbnewInitPythonScripting
  98. * Initializes all the python environment and publish our interface inside it
  99. * initializes all the wxpython interface, and returns the python thread control structure
  100. *
  101. */
  102. PyThreadState *g_PythonMainTState;
  103. bool pcbnewInitPythonScripting()
  104. {
  105. swigAddBuiltin(); // add builtin functions
  106. swigAddModules(); // add our own modules
  107. swigSwitchPythonBuiltin(); // switch the python builtin modules to our new list
  108. Py_Initialize();
  109. #ifdef KICAD_SCRIPTING_WXPYTHON
  110. PyEval_InitThreads();
  111. // Load the wxPython core API. Imports the wx._core_ module and sets a
  112. // local pointer to a function table located there. The pointer is used
  113. // internally by the rest of the API functions.
  114. if( ! wxPyCoreAPI_IMPORT() )
  115. {
  116. wxLogError(wxT("***** Error importing the wxPython API! *****"));
  117. PyErr_Print();
  118. Py_Finalize();
  119. return false;
  120. }
  121. // Save the current Python thread state and release the
  122. // Global Interpreter Lock.
  123. g_PythonMainTState = wxPyBeginAllowThreads();
  124. // load pcbnew inside python, and load all the user plugins, TODO: add system wide plugins
  125. PY_BLOCK_THREADS( blocked );
  126. #endif
  127. PyRun_SimpleString( "import sys\n"
  128. "sys.path.append(\".\")\n"
  129. "import pcbnew\n"
  130. "pcbnew.LoadPlugins()"
  131. );
  132. PY_UNBLOCK_THREADS( blocked );
  133. return true;
  134. }
  135. void pcbnewFinishPythonScripting()
  136. {
  137. #ifdef KICAD_SCRIPTING_WXPYTHON
  138. wxPyEndAllowThreads(g_PythonMainTState);
  139. #endif
  140. Py_Finalize();
  141. }
  142. #ifdef 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. c sys.stderr = output\n";
  153. PY_BLOCK_THREADS( blocked );
  154. PyRun_SimpleString( python_redirect );
  155. PY_UNBLOCK_THREADS( blocked );
  156. }
  157. wxWindow* CreatePythonShellWindow(wxWindow* parent)
  158. {
  159. const char* pycrust_panel = "\
  160. import wx\n\
  161. from wx.py import shell, version\n\
  162. \n\
  163. class PyCrustPanel(wx.Panel):\n\
  164. \tdef __init__(self, parent):\n\
  165. \t\twx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)\n\
  166. \t\t\n\
  167. \t\t\n\
  168. \t\tintro = \"Welcome To PyCrust %s - KiCAD Python Shell\" % version.VERSION\n\
  169. \t\tpycrust = shell.Shell(self, -1, introText=intro)\n\
  170. \t\t\n\
  171. \t\tsizer = wx.BoxSizer(wx.VERTICAL)\n\n\
  172. \t\tsizer.Add(pycrust, 1, wx.EXPAND|wx.BOTTOM|wx.LEFT|wx.RIGHT, 10)\n\n\
  173. \t\tself.SetSizer(sizer)\n\n\
  174. \n\
  175. def makeWindow(parent):\n\
  176. win = PyCrustPanel(parent)\n\
  177. return win\n\
  178. ";
  179. wxWindow* window = NULL;
  180. PyObject* result;
  181. // As always, first grab the GIL
  182. PY_BLOCK_THREADS( blocked );
  183. // Now make a dictionary to serve as the global namespace when the code is
  184. // executed. Put a reference to the builtins module in it.
  185. PyObject* globals = PyDict_New();
  186. PyObject* builtins = PyImport_ImportModule( "__builtin__" );
  187. PyDict_SetItemString( globals, "__builtins__", builtins );
  188. Py_DECREF(builtins);
  189. // Execute the code to make the makeWindow function we defined above
  190. result = PyRun_String( pycrust_panel, Py_file_input, globals, globals );
  191. // Was there an exception?
  192. if( !result )
  193. {
  194. PyErr_Print();
  195. PY_UNBLOCK_THREADS( blocked );
  196. return NULL;
  197. }
  198. Py_DECREF(result);
  199. // Now there should be an object named 'makeWindow' in the dictionary that
  200. // we can grab a pointer to:
  201. PyObject* func = PyDict_GetItemString( globals, "makeWindow" );
  202. wxASSERT( PyCallable_Check( func ) );
  203. // Now build an argument tuple and call the Python function. Notice the
  204. // use of another wxPython API to take a wxWindows object and build a
  205. // wxPython object that wraps it.
  206. PyObject* arg = wxPyMake_wxObject( parent, false );
  207. wxASSERT( arg != NULL );
  208. PyObject* tuple = PyTuple_New( 1 );
  209. PyTuple_SET_ITEM( tuple, 0, arg );
  210. result = PyEval_CallObject( func, tuple );
  211. // Was there an exception?
  212. if( !result )
  213. PyErr_Print();
  214. else
  215. {
  216. // Otherwise, get the returned window out of Python-land and
  217. // into C++-ville...
  218. bool success = wxPyConvertSwigPtr(result, (void**)&window, _T("wxWindow") );
  219. (void)success;
  220. wxASSERT_MSG(success, _T("Returned object was not a wxWindow!") );
  221. Py_DECREF(result);
  222. }
  223. // Release the python objects we still have
  224. Py_DECREF( globals );
  225. Py_DECREF( tuple );
  226. // Finally, after all Python stuff is done, release the GIL
  227. PY_UNBLOCK_THREADS( blocked );
  228. return window;
  229. }
  230. #endif