FlatCAMScript.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from appEditors.FlatCAMTextEditor import TextEditor
  12. from appObjects.FlatCAMObj import *
  13. from appGUI.ObjectUI import *
  14. import tkinter as tk
  15. import sys
  16. from copy import deepcopy
  17. import gettext
  18. import appTranslation as fcTranslate
  19. import builtins
  20. fcTranslate.apply_language('strings')
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. class ScriptObject(FlatCAMObj):
  24. """
  25. Represents a TCL script object.
  26. """
  27. optionChanged = QtCore.pyqtSignal(str)
  28. ui_type = ScriptObjectUI
  29. def __init__(self, name):
  30. self.decimals = self.app.decimals
  31. log.debug("Creating a ScriptObject object...")
  32. FlatCAMObj.__init__(self, name)
  33. self.kind = "script"
  34. self.options.update({
  35. "plot": True,
  36. "type": 'Script',
  37. "source_file": '',
  38. })
  39. self.units = ''
  40. self.script_editor_tab = None
  41. self.ser_attrs = ['options', 'kind', 'source_file']
  42. self.source_file = ''
  43. self.script_code = ''
  44. self.units_found = self.app.defaults['units']
  45. def set_ui(self, ui):
  46. """
  47. Sets the Object UI in Selected Tab for the FlatCAM Script type of object.
  48. :param ui:
  49. :return:
  50. """
  51. FlatCAMObj.set_ui(self, ui)
  52. log.debug("ScriptObject.set_ui()")
  53. assert isinstance(self.ui, ScriptObjectUI), \
  54. "Expected a ScriptObjectUI, got %s" % type(self.ui)
  55. self.units = self.app.defaults['units'].upper()
  56. self.units_found = self.app.defaults['units']
  57. # Fill form fields only on object create
  58. self.to_form()
  59. # Show/Hide Advanced Options
  60. if self.app.defaults["global_app_level"] == 'b':
  61. self.ui.level.setText(_(
  62. '<span style="color:green;"><b>Basic</b></span>'
  63. ))
  64. else:
  65. self.ui.level.setText(_(
  66. '<span style="color:red;"><b>Advanced</b></span>'
  67. ))
  68. self.script_editor_tab = TextEditor(app=self.app, plain_text=True, parent=self.app.ui)
  69. # tab_here = False
  70. # # try to not add too many times a tab that it is already installed
  71. # for idx in range(self.app.ui.plot_tab_area.count()):
  72. # if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  73. # tab_here = True
  74. # break
  75. #
  76. # # add the tab if it is not already added
  77. # if tab_here is False:
  78. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  79. # self.script_editor_tab.setObjectName(self.options['name'])
  80. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  81. # self.script_editor_tab.setObjectName(self.options['name'])
  82. # first clear previous text in text editor (if any)
  83. # self.script_editor_tab.code_editor.clear()
  84. # self.script_editor_tab.code_editor.setReadOnly(False)
  85. self.ui.autocomplete_cb.set_value(self.app.defaults['script_autocompleter'])
  86. self.on_autocomplete_changed(state=self.app.defaults['script_autocompleter'])
  87. self.script_editor_tab.buttonRun.show()
  88. # Switch plot_area to Script Editor tab
  89. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  90. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  91. self.script_editor_tab.buttonOpen.clicked.disconnect()
  92. self.script_editor_tab.buttonOpen.clicked.connect(lambda: self.script_editor_tab.handleOpen(filt=flt))
  93. self.script_editor_tab.buttonSave.clicked.disconnect()
  94. self.script_editor_tab.buttonSave.clicked.connect(lambda: self.script_editor_tab.handleSaveGCode(filt=flt))
  95. self.script_editor_tab.buttonRun.clicked.connect(self.handle_run_code)
  96. self.script_editor_tab.handleTextChanged()
  97. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  98. self.ser_attrs = ['options', 'kind', 'source_file']
  99. # ---------------------------------------------------- #
  100. # ----------- LOAD THE TEXT SOURCE FILE -------------- #
  101. # ---------------------------------------------------- #
  102. self.app.proc_container.view.set_busy(_("Loading..."))
  103. self.script_editor_tab.t_frame.hide()
  104. try:
  105. self.script_editor_tab.code_editor.setPlainText(self.source_file)
  106. # for line in self.source_file.splitlines():
  107. # QtWidgets.QApplication.processEvents()
  108. # self.script_editor_tab.code_editor.append(line)
  109. except Exception as e:
  110. log.debug("ScriptObject.set_ui() --> %s" % str(e))
  111. self.script_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.End)
  112. self.script_editor_tab.t_frame.show()
  113. self.app.proc_container.view.set_idle()
  114. self.build_ui()
  115. def build_ui(self):
  116. FlatCAMObj.build_ui(self)
  117. tab_here = False
  118. # try to not add too many times a tab that it is already installed
  119. for idx in range(self.app.ui.plot_tab_area.count()):
  120. if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  121. tab_here = True
  122. break
  123. # add the tab if it is not already added
  124. if tab_here is False:
  125. self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  126. self.script_editor_tab.setObjectName(self.options['name'])
  127. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  128. def parse_file(self, filename):
  129. """
  130. Will set an attribute of the object, self.source_file, with the parsed data.
  131. :param filename: Tcl Script file to parse
  132. :return: None
  133. """
  134. with open(filename, "r") as opened_script:
  135. script_content = opened_script.readlines()
  136. script_content = ''.join(script_content)
  137. self.source_file = script_content
  138. def handle_run_code(self):
  139. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  140. # tries to print on a hidden widget, therefore show the dock if hidden
  141. if self.app.ui.shell_dock.isHidden():
  142. self.app.ui.shell_dock.show()
  143. self.app.shell.open_processing() # Disables input box.
  144. # make sure that the pixmaps are not updated when running this as they will crash
  145. # TODO find why the pixmaps load crash when run from this object (perhaps another thread?)
  146. self.app.ui.fcinfo.lock_pmaps = True
  147. self.script_code = self.script_editor_tab.code_editor.toPlainText()
  148. old_line = ''
  149. for tcl_command_line in self.script_code.splitlines():
  150. # do not process lines starting with '#' = comment and empty lines
  151. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  152. # id FlatCAM is run in Windows then replace all the slashes with
  153. # the UNIX style slash that TCL understands
  154. if sys.platform == 'win32':
  155. if "open" in tcl_command_line:
  156. tcl_command_line = tcl_command_line.replace('\\', '/')
  157. if old_line != '':
  158. new_command = old_line + tcl_command_line + '\n'
  159. else:
  160. new_command = tcl_command_line
  161. # execute the actual Tcl command
  162. try:
  163. result = self.app.shell.tcl.eval(str(new_command))
  164. if result != 'None':
  165. self.app.shell.append_output(result + '\n')
  166. old_line = ''
  167. except tk.TclError:
  168. old_line = old_line + tcl_command_line + '\n'
  169. except Exception as e:
  170. log.debug("ScriptObject.handleRunCode() --> %s" % str(e))
  171. if old_line != '':
  172. # it means that the script finished with an error
  173. result = self.app.shell.tcl.eval("set errorInfo")
  174. log.error("Exec command Exception: %s\n" % result)
  175. self.app.shell.append_error('ERROR: %s\n '% result)
  176. self.app.ui.fcinfo.lock_pmaps = False
  177. self.app.shell.close_processing()
  178. def on_autocomplete_changed(self, state):
  179. if state:
  180. self.script_editor_tab.code_editor.completer_enable = True
  181. else:
  182. self.script_editor_tab.code_editor.completer_enable = False
  183. def mirror(self, axis, point):
  184. pass
  185. def offset(self, vect):
  186. pass
  187. def rotate(self, angle, point):
  188. pass
  189. def scale(self, xfactor, yfactor=None, point=None):
  190. pass
  191. def skew(self, angle_x, angle_y, point):
  192. pass
  193. def buffer(self, distance, join, factor=None):
  194. pass
  195. def bounds(self, flatten=False):
  196. return None, None, None, None
  197. def to_dict(self):
  198. """
  199. Returns a representation of the object as a dictionary.
  200. Attributes to include are listed in ``self.ser_attrs``.
  201. :return: A dictionary-encoded copy of the object.
  202. :rtype: dict
  203. """
  204. d = {}
  205. for attr in self.ser_attrs:
  206. d[attr] = getattr(self, attr)
  207. return d
  208. def from_dict(self, d):
  209. """
  210. Sets object's attributes from a dictionary.
  211. Attributes to include are listed in ``self.ser_attrs``.
  212. This method will look only for only and all the
  213. attributes in ``self.ser_attrs``. They must all
  214. be present. Use only for deserializing saved
  215. objects.
  216. :param d: Dictionary of attributes to set in the object.
  217. :type d: dict
  218. :return: None
  219. """
  220. for attr in self.ser_attrs:
  221. setattr(self, attr, d[attr])