appGCodeEditor.py 11 KB

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