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.

260 lines
9.9 KiB

  1. # -*- coding: utf-8 -*-
  2. """KiCad Python Shell.
  3. This module provides the python shell for KiCad.
  4. KiCad starts the shell once, by calling makePcbnewShellWindow() the
  5. first time it is opened, subsequently the shell window is just hidden
  6. or shown, as per user requirements.
  7. IF makePcbnewShellWindow() is called again, a second/third shell window
  8. can be created.
  9. Note:
  10. **DO NOT** import pcbnew module if not called from Pcbnew: on msys2 it creates a serious issue:
  11. the python script import is broken because the pcbnew application is not running, and for instance
  12. Pgm() returns a nullptr and Kicad crashes when Pgm is invoked.
  13. """
  14. import wx
  15. import sys
  16. import os
  17. import pcbnew
  18. from wx.py import crust, version, dispatcher
  19. from .kicad_pyeditor import KiCadEditorNotebookFrame
  20. from .kicad_pyeditor import KiCadEditorNotebook
  21. class KiCadPyShell(KiCadEditorNotebookFrame):
  22. def __init__(self, parent):
  23. # Search if a pcbnew frame is open, because import pcbnew can be made only if it exists.
  24. # frame names are "SchematicFrame" and "PcbFrame"
  25. #
  26. # Note we must do this before the KiCadEditorNotebookFrame __init__ call because it ends up calling _setup back on us
  27. frame = wx.FindWindowByName( "PcbFrame" )
  28. self.isPcbframe = frame is not None
  29. KiCadEditorNotebookFrame.__init__(self, parent)
  30. def _setup_startup(self):
  31. if self.config_dir != "":
  32. """Initialise the startup script."""
  33. # Create filename for startup script.
  34. self.startup_file = os.path.join(self.config_dir,
  35. "PyShell_pcbnew_startup.py")
  36. self.execStartupScript = True
  37. # Check if startup script exists
  38. if not os.path.isfile(self.startup_file):
  39. # Not, so try to create a default.
  40. try:
  41. default_startup = open(self.startup_file, 'w')
  42. # provide the content for the default startup file.
  43. default_startup.write(
  44. "### DEFAULT STARTUP FILE FOR KiCad Python Shell\n" +
  45. "# Enter any Python code you would like to execute when" +
  46. " the PCBNEW python shell first runs.\n" +
  47. "\n" +
  48. "# For example, uncomment the following lines to import the current board\n" +
  49. "\n" +
  50. "# import pcbnew\n" +
  51. "# import eeschema\n" +
  52. "# board = pcbnew.GetBoard()\n" +
  53. "# sch = eeschema.GetSchematic()\n")
  54. default_startup.close()
  55. except:
  56. pass
  57. else:
  58. self.startup_file = ""
  59. self.execStartupScript = False
  60. def _setup(self):
  61. """
  62. Setup prior to first buffer creation.
  63. Called automatically by base class during init.
  64. """
  65. self.notebook = KiCadEditorNotebook(parent=self.parent)
  66. intro = 'Py %s' % version.VERSION
  67. intro += """\n\nDeprecation Notice:\n
  68. This SWIG-based Python interface to the PCB editor is deprecated and will be removed
  69. in a future version of KiCad. Please plan to move to the new IPC API and/or make
  70. use of the kicad-cli tool for your KiCad automation needs.\n\n"""
  71. import types
  72. import builtins
  73. module = types.ModuleType('__main__')
  74. module.__dict__['__builtins__'] = builtins
  75. namespace = module.__dict__.copy()
  76. '''
  77. Import pcbnew **only** if the board editor exists, to avoid strange behavior if not.
  78. pcbnew.SETTINGS_MANAGER should be in fact called only if the python console is created
  79. from the board editor, and if created from schematic editor, should use something like
  80. eeschema.SETTINGS_MANAGER
  81. '''
  82. if self.isPcbframe:
  83. import pcbnew
  84. self.config_dir = pcbnew.SETTINGS_MANAGER.GetUserSettingsPath()
  85. else:
  86. self.config_dir = ""
  87. self.dataDir = self.config_dir
  88. self._setup_startup()
  89. self.history_file = os.path.join(self.config_dir,
  90. "PyShell_pcbnew.history")
  91. self.config = None
  92. # self.config_file = os.path.join(self.config_dir,
  93. # "PyShell_pcbnew.cfg")
  94. # self.config = wx.FileConfig(localFilename=self.config_file)
  95. # self.config.SetRecordDefaults(True)
  96. self.autoSaveSettings = False
  97. self.autoSaveHistory = False
  98. self.LoadSettings()
  99. self.crust = crust.Crust(parent=self.notebook,
  100. intro=intro, locals=namespace,
  101. rootLabel="locals()",
  102. startupScript=self.startup_file,
  103. execStartupScript=self.execStartupScript)
  104. self.crust._CheckShouldSplit()
  105. self.shell = self.crust.shell
  106. # Override the filling so that status messages go to the status bar.
  107. self.crust.filling.tree.setStatusText = self.parent.SetStatusText
  108. # Override the shell so that status messages go to the status bar.
  109. self.shell.setStatusText = self.parent.SetStatusText
  110. # Fix a problem with the sash shrinking to nothing.
  111. self.crust.filling.SetSashPosition(200)
  112. self.notebook.AddPage(page=self.crust, text='*Shell*', select=True)
  113. self.setEditor(self.crust.editor)
  114. self.crust.editor.SetFocus()
  115. self.LoadHistory()
  116. def OnAbout(self, event):
  117. """Display an About window."""
  118. title = 'About : KiCad - Python Shell'
  119. text = "Enhanced Python Shell for KiCad\n\n" + \
  120. "KiCad Revision: %s\n" % pcbnew.FullVersion() + \
  121. "Platform: %s\n" % sys.platform + \
  122. "Python Version: %s\n" % sys.version.split()[0] + \
  123. "wxPython Version: %s\n" % wx.VERSION_STRING + \
  124. ("\t(%s)\n" % ", ".join(wx.PlatformInfo[1:]))
  125. dialog = wx.MessageDialog(self.parent, text, title,
  126. wx.OK | wx.ICON_INFORMATION)
  127. dialog.ShowModal()
  128. dialog.Destroy()
  129. def EditStartupScript(self):
  130. """Open a Edit buffer of the startup script file."""
  131. self.bufferCreate(filename=self.startup_file)
  132. def LoadSettings(self):
  133. """Load settings for the shell."""
  134. if self.config is not None:
  135. KiCadEditorNotebookFrame.LoadSettings(self.parent, self.config)
  136. self.autoSaveSettings = \
  137. self.config.ReadBool('Options/AutoSaveSettings', False)
  138. self.execStartupScript = \
  139. self.config.ReadBool('Options/ExecStartupScript', True)
  140. self.autoSaveHistory = \
  141. self.config.ReadBool('Options/AutoSaveHistory', False)
  142. self.hideFoldingMargin = \
  143. self.config.ReadBool('Options/HideFoldingMargin', True)
  144. def SaveSettings(self, force=False):
  145. """
  146. Save settings for the shell.
  147. Arguments:
  148. force -- False - Autosaving. True - Manual Saving.
  149. """
  150. if self.config is not None:
  151. # always save these
  152. self.config.WriteBool('Options/AutoSaveSettings',
  153. self.autoSaveSettings)
  154. if self.autoSaveSettings or force:
  155. KiCadEditorNotebookFrame.SaveSettings(self, self.config)
  156. self.config.WriteBool('Options/AutoSaveHistory',
  157. self.autoSaveHistory)
  158. self.config.WriteBool('Options/ExecStartupScript',
  159. self.execStartupScript)
  160. self.config.WriteBool('Options/HideFoldingMargin',
  161. self.hideFoldingMargin)
  162. if self.autoSaveHistory:
  163. self.SaveHistory()
  164. def DoSaveSettings(self):
  165. """Menu function to trigger saving the shells settings."""
  166. if self.config is not None:
  167. self.SaveSettings(force=True)
  168. self.config.Flush()
  169. def SaveHistory(self):
  170. """Save shell history to the shell history file."""
  171. if self.dataDir:
  172. try:
  173. name = self.history_file
  174. f = file(name, 'w')
  175. hist = []
  176. enc = wx.GetDefaultPyEncoding()
  177. for h in self.shell.history:
  178. if isinstance(h, unicode):
  179. h = h.encode(enc)
  180. hist.append(h)
  181. hist = '\x00\n'.join(hist)
  182. f.write(hist)
  183. f.close()
  184. except:
  185. d = wx.MessageDialog(self, "Error saving history file.",
  186. "Error", wx.ICON_EXCLAMATION | wx.OK)
  187. d.ShowModal()
  188. d.Destroy()
  189. raise
  190. def LoadHistory(self):
  191. """Load shell history from the shell history file."""
  192. if self.dataDir:
  193. name = self.history_file
  194. if os.path.exists(name):
  195. try:
  196. f = file(name, 'U')
  197. hist = f.read()
  198. f.close()
  199. self.shell.history = hist.split('\x00\n')
  200. dispatcher.send(signal="Shell.loadHistory",
  201. history=self.shell.history)
  202. except:
  203. d = wx.MessageDialog(self,
  204. "Error loading history file!",
  205. "Error", wx.ICON_EXCLAMATION | wx.OK)
  206. d.ShowModal()
  207. d.Destroy()
  208. def makePcbnewShellWindow(parentid):
  209. """
  210. Create a new Shell Window and return its handle.
  211. Arguments:
  212. parent -- The parent window to attach to.
  213. Returns:
  214. The handle to the new window.
  215. """
  216. parent = wx.FindWindowById( parentid )
  217. frmname = parent.GetName()
  218. return KiCadPyShell(parent)