appGCodeEditor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 07/22/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from appEditors.AppTextEditor import AppTextEditor
  8. from appObjects.FlatCAMCNCJob import CNCJobObject
  9. from appGUI.GUIElements import FCTextArea, FCEntry, FCButton
  10. from PyQt5 import QtWidgets, QtCore, QtGui
  11. # from io import StringIO
  12. import logging
  13. import gettext
  14. import appTranslation as fcTranslate
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. log = logging.getLogger('base')
  20. class AppGCodeEditor(QtCore.QObject):
  21. def __init__(self, app, parent=None):
  22. super().__init__(parent=parent)
  23. self.app = app
  24. self.plain_text = ''
  25. self.callback = lambda x: None
  26. self.ui = AppGCodeEditorUI(app=self.app)
  27. self.gcode_obj = None
  28. self.code_edited = ''
  29. def set_ui(self):
  30. """
  31. :return:
  32. :rtype:
  33. """
  34. # #############################################################################################################
  35. # ############# ADD a new TAB in the PLot Tab Area
  36. # #############################################################################################################
  37. self.ui.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  38. # add the tab if it was closed
  39. self.app.ui.plot_tab_area.addTab(self.ui.gcode_editor_tab, '%s' % _("Code Editor"))
  40. self.ui.gcode_editor_tab.setObjectName('code_editor_tab')
  41. # delete the absolute and relative position and messages in the infobar
  42. self.app.ui.position_label.setText("")
  43. self.app.ui.rel_position_label.setText("")
  44. self.ui.gcode_editor_tab.code_editor.completer_enable = False
  45. self.ui.gcode_editor_tab.buttonRun.hide()
  46. # Switch plot_area to CNCJob tab
  47. self.app.ui.plot_tab_area.setCurrentWidget(self.ui.gcode_editor_tab)
  48. self.ui.gcode_editor_tab.t_frame.hide()
  49. self.ui.gcode_editor_tab.t_frame.show()
  50. self.app.proc_container.view.set_idle()
  51. # #############################################################################################################
  52. # #############################################################################################################
  53. self.ui.append_text.set_value(self.app.defaults["cncjob_append"])
  54. self.ui.prepend_text.set_value(self.app.defaults["cncjob_prepend"])
  55. # #################################################################################
  56. # ################### SIGNALS #####################################################
  57. # #################################################################################
  58. self.ui.update_gcode_button.clicked.connect(self.insert_gcode)
  59. self.ui.exit_editor_button.clicked.connect(self.update_fcgcode)
  60. def build_ui(self):
  61. """
  62. :return:
  63. :rtype:
  64. """
  65. # Remove anything else in the GUI Selected Tab
  66. self.app.ui.selected_scroll_area.takeWidget()
  67. # Put ourselves in the GUI Selected Tab
  68. self.app.ui.selected_scroll_area.setWidget(self.ui.edit_widget)
  69. # Switch notebook to Selected page
  70. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  71. def ui_connect(self):
  72. """
  73. :return:
  74. :rtype:
  75. """
  76. pass
  77. def ui_disconnect(self):
  78. """
  79. :return:
  80. :rtype:
  81. """
  82. pass
  83. def handleTextChanged(self):
  84. """
  85. :return:
  86. :rtype:
  87. """
  88. # enable = not self.ui.code_editor.document().isEmpty()
  89. # self.ui.buttonPrint.setEnabled(enable)
  90. # self.ui.buttonPreview.setEnabled(enable)
  91. self.buttonSave.setStyleSheet("QPushButton {color: red;}")
  92. self.buttonSave.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as_red.png'))
  93. def insert_gcode(self):
  94. """
  95. :return:
  96. :rtype:
  97. """
  98. pass
  99. def edit_fcgcode(self, cnc_obj):
  100. """
  101. :param cnc_obj:
  102. :type cnc_obj:
  103. :return:
  104. :rtype:
  105. """
  106. assert isinstance(cnc_obj, CNCJobObject)
  107. self.gcode_obj = cnc_obj
  108. gcode_text = self.gcode_obj.source_file
  109. self.set_ui()
  110. self.build_ui()
  111. # then append the text from GCode to the text editor
  112. self.ui.gcode_editor_tab.load_text(gcode_text, move_to_start=True, clear_text=True)
  113. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  114. def update_fcgcode(self):
  115. """
  116. :return:
  117. :rtype:
  118. """
  119. preamble = str(self.ui.prepend_text.get_value())
  120. postamble = str(self.ui.append_text.get_value())
  121. my_gcode = self.ui.gcode_editor_tab.code_editor.toPlainText()
  122. self.gcode_obj.source_file = my_gcode
  123. self.ui.gcode_editor_tab.buttonSave.setStyleSheet("")
  124. self.ui.gcode_editor_tab.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  125. def on_open_gcode(self):
  126. """
  127. :return:
  128. :rtype:
  129. """
  130. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  131. "All Files (*.*)"
  132. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  133. caption=_('Open file'), directory=self.app.get_last_folder(), filter=_filter_)
  134. if path:
  135. file = QtCore.QFile(path)
  136. if file.open(QtCore.QIODevice.ReadOnly):
  137. stream = QtCore.QTextStream(file)
  138. self.code_edited = stream.readAll()
  139. self.ui.gcode_editor_tab.load_text(self.code_edited, move_to_start=True, clear_text=True)
  140. file.close()
  141. class AppGCodeEditorUI:
  142. def __init__(self, app):
  143. self.app = app
  144. # Number of decimals used by tools in this class
  145. self.decimals = self.app.decimals
  146. # ## Current application units in Upper Case
  147. self.units = self.app.defaults['units'].upper()
  148. # self.setSizePolicy(
  149. # QtWidgets.QSizePolicy.MinimumExpanding,
  150. # QtWidgets.QSizePolicy.MinimumExpanding
  151. # )
  152. self.gcode_editor_tab = None
  153. self.edit_widget = QtWidgets.QWidget()
  154. # ## Box for custom widgets
  155. # This gets populated in offspring implementations.
  156. layout = QtWidgets.QVBoxLayout()
  157. self.edit_widget.setLayout(layout)
  158. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  159. # this way I can hide/show the frame
  160. self.edit_frame = QtWidgets.QFrame()
  161. self.edit_frame.setContentsMargins(0, 0, 0, 0)
  162. layout.addWidget(self.edit_frame)
  163. self.edit_box = QtWidgets.QVBoxLayout()
  164. self.edit_box.setContentsMargins(0, 0, 0, 0)
  165. self.edit_frame.setLayout(self.edit_box)
  166. # ## Page Title box (spacing between children)
  167. self.title_box = QtWidgets.QHBoxLayout()
  168. self.edit_box.addLayout(self.title_box)
  169. # ## Page Title icon
  170. pixmap = QtGui.QPixmap(self.app.resource_location + '/flatcam_icon32.png')
  171. self.icon = QtWidgets.QLabel()
  172. self.icon.setPixmap(pixmap)
  173. self.title_box.addWidget(self.icon, stretch=0)
  174. # ## Title label
  175. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('GCode Editor'))
  176. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  177. self.title_box.addWidget(self.title_label, stretch=1)
  178. # ## Object name
  179. self.name_box = QtWidgets.QHBoxLayout()
  180. self.edit_box.addLayout(self.name_box)
  181. name_label = QtWidgets.QLabel(_("Name:"))
  182. self.name_box.addWidget(name_label)
  183. self.name_entry = FCEntry()
  184. self.name_box.addWidget(self.name_entry)
  185. # Prepend text to GCode
  186. prependlabel = QtWidgets.QLabel('%s:' % _('Prepend to CNC Code'))
  187. prependlabel.setToolTip(
  188. _("Type here any G-Code commands you would\n"
  189. "like to add at the beginning of the G-Code file.")
  190. )
  191. self.edit_box.addWidget(prependlabel)
  192. self.prepend_text = FCTextArea()
  193. self.prepend_text.setPlaceholderText(
  194. _("Type here any G-Code commands you would\n"
  195. "like to add at the beginning of the G-Code file.")
  196. )
  197. self.edit_box.addWidget(self.prepend_text)
  198. # Append text to GCode
  199. appendlabel = QtWidgets.QLabel('%s:' % _('Append to CNC Code'))
  200. appendlabel.setToolTip(
  201. _("Type here any G-Code commands you would\n"
  202. "like to append to the generated file.\n"
  203. "I.e.: M2 (End of program)")
  204. )
  205. self.edit_box.addWidget(appendlabel)
  206. self.append_text = FCTextArea()
  207. self.append_text.setPlaceholderText(
  208. _("Type here any G-Code commands you would\n"
  209. "like to append to the generated file.\n"
  210. "I.e.: M2 (End of program)")
  211. )
  212. self.edit_box.addWidget(self.append_text)
  213. h_lay = QtWidgets.QHBoxLayout()
  214. h_lay.setAlignment(QtCore.Qt.AlignVCenter)
  215. self.edit_box.addLayout(h_lay)
  216. # GO Button
  217. self.update_gcode_button = FCButton(_('Update Code'))
  218. # self.update_gcode_button.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  219. self.update_gcode_button.setToolTip(
  220. _("Update the Gcode in the Editor with the values\n"
  221. "in the 'Prepend' and 'Append' text boxes.")
  222. )
  223. h_lay.addWidget(self.update_gcode_button)
  224. layout.addStretch()
  225. # Editor
  226. self.exit_editor_button = FCButton(_('Exit Editor'))
  227. self.exit_editor_button.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  228. self.exit_editor_button.setToolTip(
  229. _("Exit from Editor.")
  230. )
  231. self.exit_editor_button.setStyleSheet("""
  232. QPushButton
  233. {
  234. font-weight: bold;
  235. }
  236. """)
  237. layout.addWidget(self.exit_editor_button)
  238. # ############################ FINSIHED GUI ##################################################################
  239. # #############################################################################################################
  240. def confirmation_message(self, accepted, minval, maxval):
  241. if accepted is False:
  242. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  243. self.decimals,
  244. minval,
  245. self.decimals,
  246. maxval), False)
  247. else:
  248. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  249. def confirmation_message_int(self, accepted, minval, maxval):
  250. if accepted is False:
  251. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  252. (_("Edited value is out of range"), minval, maxval), False)
  253. else:
  254. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)