appGCodeEditor.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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, FCTable
  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.decimals = self.app.decimals
  25. self.plain_text = ''
  26. self.callback = lambda x: None
  27. self.ui = AppGCodeEditorUI(app=self.app)
  28. self.edited_obj_name = ""
  29. self.gcode_obj = None
  30. self.code_edited = ''
  31. # store the status of the editor so the Delete at object level will not work until the edit is finished
  32. self.editor_active = False
  33. log.debug("Initialization of the GCode Editor is finished ...")
  34. def set_ui(self):
  35. """
  36. :return:
  37. :rtype:
  38. """
  39. self.decimals = self.app.decimals
  40. # #############################################################################################################
  41. # ############# ADD a new TAB in the PLot Tab Area
  42. # #############################################################################################################
  43. self.ui.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  44. self.edit_area = self.ui.gcode_editor_tab.code_editor
  45. # add the tab if it was closed
  46. self.app.ui.plot_tab_area.addTab(self.ui.gcode_editor_tab, '%s' % _("Code Editor"))
  47. self.ui.gcode_editor_tab.setObjectName('gcode_editor_tab')
  48. # delete the absolute and relative position and messages in the infobar
  49. self.app.ui.position_label.setText("")
  50. self.app.ui.rel_position_label.setText("")
  51. self.ui.gcode_editor_tab.code_editor.completer_enable = False
  52. self.ui.gcode_editor_tab.buttonRun.hide()
  53. # Switch plot_area to CNCJob tab
  54. self.app.ui.plot_tab_area.setCurrentWidget(self.ui.gcode_editor_tab)
  55. self.ui.gcode_editor_tab.t_frame.hide()
  56. self.ui.gcode_editor_tab.t_frame.show()
  57. self.app.proc_container.view.set_idle()
  58. # #############################################################################################################
  59. # #############################################################################################################
  60. self.ui.append_text.set_value(self.app.defaults["cncjob_append"])
  61. self.ui.prepend_text.set_value(self.app.defaults["cncjob_prepend"])
  62. # Remove anything else in the GUI Selected Tab
  63. self.app.ui.selected_scroll_area.takeWidget()
  64. # Put ourselves in the GUI Selected Tab
  65. self.app.ui.selected_scroll_area.setWidget(self.ui.edit_widget)
  66. # Switch notebook to Selected page
  67. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  68. # make a new name for the new Excellon object (the one with edited content)
  69. self.edited_obj_name = self.gcode_obj.options['name']
  70. self.ui.name_entry.set_value(self.edited_obj_name)
  71. # #################################################################################
  72. # ################### SIGNALS #####################################################
  73. # #################################################################################
  74. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  75. self.ui.update_gcode_button.clicked.connect(self.insert_gcode)
  76. self.ui.exit_editor_button.clicked.connect(lambda: self.app.editor2object())
  77. def build_ui(self):
  78. """
  79. :return:
  80. :rtype:
  81. """
  82. self.ui_disconnect()
  83. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  84. self.ui.cnc_tools_table.hide()
  85. if self.gcode_obj.cnc_tools:
  86. self.ui.cnc_tools_table.show()
  87. self.build_cnc_tools_table()
  88. self.ui.exc_cnc_tools_table.hide()
  89. if self.gcode_obj.exc_cnc_tools:
  90. self.ui.exc_cnc_tools_table.show()
  91. self.build_excellon_cnc_tools()
  92. self.ui_connect()
  93. def build_cnc_tools_table(self):
  94. tool_idx = 0
  95. row_no = 0
  96. n = len(self.gcode_obj.cnc_tools) + 3
  97. self.ui.cnc_tools_table.setRowCount(n)
  98. # add the All Gcode selection
  99. allgcode_item = QtWidgets.QTableWidgetItem('%s' % _("All GCode"))
  100. allgcode_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  101. self.ui.cnc_tools_table.setItem(row_no, 1, allgcode_item)
  102. row_no += 1
  103. # add the Header Gcode selection
  104. header_item = QtWidgets.QTableWidgetItem('%s' % _("Header GCode"))
  105. header_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  106. self.ui.cnc_tools_table.setItem(row_no, 1, header_item)
  107. row_no += 1
  108. # add the Start Gcode selection
  109. start_item = QtWidgets.QTableWidgetItem('%s' % _("Start GCode"))
  110. start_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  111. self.ui.cnc_tools_table.setItem(row_no, 1, start_item)
  112. for dia_key, dia_value in self.gcode_obj.cnc_tools.items():
  113. tool_idx += 1
  114. row_no += 1
  115. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  116. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  117. self.ui.cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  118. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  119. offset_txt = list(str(dia_value['offset']))
  120. offset_txt[0] = offset_txt[0].upper()
  121. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  122. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  123. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  124. t_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  125. dia_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  126. offset_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  127. type_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  128. tool_type_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  129. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  130. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  131. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  132. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  133. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  134. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  135. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  136. self.ui.cnc_tools_table.resizeColumnsToContents()
  137. self.ui.cnc_tools_table.resizeRowsToContents()
  138. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  139. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  140. vertical_header.hide()
  141. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  142. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  143. horizontal_header.setMinimumSectionSize(10)
  144. horizontal_header.setDefaultSectionSize(70)
  145. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  146. horizontal_header.resizeSection(0, 20)
  147. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  148. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  149. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  150. horizontal_header.resizeSection(4, 40)
  151. # horizontal_header.setStretchLastSection(True)
  152. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  153. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  154. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  155. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  156. # self.ui.geo_tools_table.setSortingEnabled(True)
  157. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  158. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  159. def build_excellon_cnc_tools(self):
  160. """
  161. :return:
  162. :rtype:
  163. """
  164. tool_idx = 0
  165. row_no = 0
  166. n = len(self.gcode_obj.exc_cnc_tools) + 3
  167. self.ui.exc_cnc_tools_table.setRowCount(n)
  168. # add the All Gcode selection
  169. allgcode_item = QtWidgets.QTableWidgetItem('%s' % _("All GCode"))
  170. allgcode_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  171. self.ui.exc_cnc_tools_table.setItem(row_no, 1, allgcode_item)
  172. row_no += 1
  173. # add the Header Gcode selection
  174. header_item = QtWidgets.QTableWidgetItem('%s' % _("Header GCode"))
  175. header_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  176. self.ui.exc_cnc_tools_table.setItem(row_no, 1, header_item)
  177. row_no += 1
  178. # add the Start Gcode selection
  179. start_item = QtWidgets.QTableWidgetItem('%s' % _("Start GCode"))
  180. start_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  181. self.ui.exc_cnc_tools_table.setItem(row_no, 1, start_item)
  182. for tooldia_key, dia_value in self.gcode_obj.exc_cnc_tools.items():
  183. tool_idx += 1
  184. row_no += 1
  185. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  186. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  187. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  188. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  189. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (
  190. self.decimals, float(dia_value['offset']) + float(dia_value['data']['tools_drill_cutz'])))
  191. t_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  192. dia_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  193. nr_drills_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  194. nr_slots_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  195. cutz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  196. self.ui.exc_cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  197. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  198. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  199. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  200. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  201. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  202. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  203. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  204. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  205. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  206. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  207. vertical_header.hide()
  208. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  209. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  210. horizontal_header.setMinimumSectionSize(10)
  211. horizontal_header.setDefaultSectionSize(70)
  212. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  213. horizontal_header.resizeSection(0, 20)
  214. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  215. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  216. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  217. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  218. # horizontal_header.setStretchLastSection(True)
  219. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  220. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  221. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  222. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  223. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  224. def ui_connect(self):
  225. """
  226. :return:
  227. :rtype:
  228. """
  229. # rows selected
  230. if self.gcode_obj.cnc_tools:
  231. self.ui.cnc_tools_table.clicked.connect(self.on_row_selection_change)
  232. self.ui.cnc_tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  233. if self.gcode_obj.exc_cnc_tools:
  234. self.ui.exc_cnc_tools_table.clicked.connect(self.on_row_selection_change)
  235. self.ui.exc_cnc_tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  236. def ui_disconnect(self):
  237. """
  238. :return:
  239. :rtype:
  240. """
  241. # rows selected
  242. if self.gcode_obj.cnc_tools:
  243. try:
  244. self.ui.cnc_tools_table.clicked.disconnect(self.on_row_selection_change)
  245. except (TypeError, AttributeError):
  246. pass
  247. try:
  248. self.ui.cnc_tools_table.horizontalHeader().sectionClicked.disconnect(self.on_toggle_all_rows)
  249. except (TypeError, AttributeError):
  250. pass
  251. if self.gcode_obj.exc_cnc_tools:
  252. try:
  253. self.ui.exc_cnc_tools_table.clicked.disconnect(self.on_row_selection_change)
  254. except (TypeError, AttributeError):
  255. pass
  256. try:
  257. self.ui.exc_cnc_tools_table.horizontalHeader().sectionClicked.disconnect(self.on_toggle_all_rows)
  258. except (TypeError, AttributeError):
  259. pass
  260. def on_row_selection_change(self):
  261. """
  262. :return:
  263. :rtype:
  264. """
  265. flags = QtGui.QTextDocument.FindCaseSensitively
  266. self.edit_area.moveCursor(QtGui.QTextCursor.Start)
  267. if self.gcode_obj.cnc_tools:
  268. t_table = self.ui.cnc_tools_table
  269. elif self.gcode_obj.exc_cnc_tools:
  270. t_table = self.ui.exc_cnc_tools_table
  271. else:
  272. return
  273. sel_model = t_table.selectionModel()
  274. sel_indexes = sel_model.selectedIndexes()
  275. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  276. sel_rows = set()
  277. for idx in sel_indexes:
  278. sel_rows.add(idx.row())
  279. if 0 in sel_rows:
  280. self.edit_area.selectAll()
  281. return
  282. if 1 in sel_rows:
  283. text_to_be_found = self.gcode_obj.gc_header
  284. text_list = [x for x in text_to_be_found.split("\n") if x != '']
  285. self.edit_area.find(str(text_list[0]), flags)
  286. my_text_cursor = self.edit_area.textCursor()
  287. start_sel = my_text_cursor.selectionStart()
  288. end_sel = 0
  289. while True:
  290. f = self.edit_area.find(str(text_list[-1]), flags)
  291. if f is False:
  292. break
  293. my_text_cursor = self.edit_area.textCursor()
  294. end_sel = my_text_cursor.selectionEnd()
  295. my_text_cursor.setPosition(start_sel)
  296. my_text_cursor.setPosition(end_sel, QtGui.QTextCursor.KeepAnchor)
  297. self.edit_area.setTextCursor(my_text_cursor)
  298. if 2 in sel_rows:
  299. text_to_be_found = self.gcode_obj.gc_start
  300. text_list = [x for x in text_to_be_found.split("\n") if x != '']
  301. self.edit_area.find(str(text_list[0]), flags)
  302. my_text_cursor = self.edit_area.textCursor()
  303. start_sel = my_text_cursor.selectionStart()
  304. end_sel = 0
  305. while True:
  306. f = self.edit_area.find(str(text_list[-1]), flags)
  307. if f is False:
  308. break
  309. my_text_cursor = self.edit_area.textCursor()
  310. end_sel = my_text_cursor.selectionEnd()
  311. my_text_cursor.setPosition(start_sel)
  312. my_text_cursor.setPosition(end_sel, QtGui.QTextCursor.KeepAnchor)
  313. self.edit_area.setTextCursor(my_text_cursor)
  314. for row in sel_rows:
  315. # those are special rows treated before so we except them
  316. if row not in [0, 1, 2]:
  317. tool_no = int(t_table.item(row, 0).text())
  318. if self.gcode_obj.cnc_tools:
  319. text_to_be_found = self.gcode_obj.cnc_tools[tool_no]['gcode']
  320. elif self.gcode_obj.exc_cnc_tools:
  321. tool_dia = float(t_table.item(row, 1).text())
  322. text_to_be_found = self.gcode_obj.exc_cnc_tools[tool_dia]['gcode']
  323. else:
  324. return
  325. text_list = [x for x in text_to_be_found.split("\n") if x != '']
  326. # self.edit_area.find(str(text_list[0]), flags)
  327. # my_text_cursor = self.edit_area.textCursor()
  328. # start_sel = my_text_cursor.selectionStart()
  329. found_tool = self.edit_area.find('T%d' % tool_no, flags)
  330. if found_tool is False:
  331. return
  332. my_text_cursor = self.edit_area.textCursor()
  333. tool_pos = my_text_cursor.selectionStart()
  334. my_text_cursor.setPosition(tool_pos)
  335. f = self.edit_area.find(str(text_list[0]), flags)
  336. if f is False:
  337. return
  338. my_text_cursor = self.edit_area.textCursor()
  339. start_sel = my_text_cursor.selectionStart()
  340. end_sel = 0
  341. while True:
  342. f = self.edit_area.find(str(text_list[-1]), flags)
  343. m6 = self.edit_area.find('M6', flags)
  344. if f is False or m6:
  345. break
  346. my_text_cursor = self.edit_area.textCursor()
  347. end_sel = my_text_cursor.selectionEnd()
  348. my_text_cursor.setPosition(start_sel)
  349. my_text_cursor.setPosition(end_sel, QtGui.QTextCursor.KeepAnchor)
  350. self.edit_area.setTextCursor(my_text_cursor)
  351. def on_toggle_all_rows(self):
  352. """
  353. :return:
  354. :rtype:
  355. """
  356. if self.gcode_obj.cnc_tools:
  357. t_table = self.ui.cnc_tools_table
  358. elif self.gcode_obj.exc_cnc_tools:
  359. t_table = self.ui.exc_cnc_tools_table
  360. else:
  361. return
  362. sel_model = t_table.selectionModel()
  363. sel_indexes = sel_model.selectedIndexes()
  364. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  365. sel_rows = set()
  366. for idx in sel_indexes:
  367. sel_rows.add(idx.row())
  368. if len(sel_rows) == t_table.rowCount():
  369. t_table.clearSelection()
  370. my_text_cursor = self.edit_area.textCursor()
  371. my_text_cursor.clearSelection()
  372. else:
  373. t_table.selectAll()
  374. def handleTextChanged(self):
  375. """
  376. :return:
  377. :rtype:
  378. """
  379. # enable = not self.ui.code_editor.document().isEmpty()
  380. # self.ui.buttonPrint.setEnabled(enable)
  381. # self.ui.buttonPreview.setEnabled(enable)
  382. self.buttonSave.setStyleSheet("QPushButton {color: red;}")
  383. self.buttonSave.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as_red.png'))
  384. def insert_gcode(self):
  385. """
  386. :return:
  387. :rtype:
  388. """
  389. pass
  390. def edit_fcgcode(self, cnc_obj):
  391. """
  392. :param cnc_obj:
  393. :type cnc_obj:
  394. :return:
  395. :rtype:
  396. """
  397. assert isinstance(cnc_obj, CNCJobObject)
  398. self.gcode_obj = cnc_obj
  399. gcode_text = self.gcode_obj.source_file
  400. self.set_ui()
  401. self.build_ui()
  402. # then append the text from GCode to the text editor
  403. self.ui.gcode_editor_tab.load_text(gcode_text, move_to_start=True, clear_text=True)
  404. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  405. def update_fcgcode(self, edited_obj):
  406. """
  407. :return:
  408. :rtype:
  409. """
  410. preamble = str(self.ui.prepend_text.get_value())
  411. postamble = str(self.ui.append_text.get_value())
  412. my_gcode = self.ui.gcode_editor_tab.code_editor.toPlainText()
  413. self.gcode_obj.source_file = my_gcode
  414. self.ui.gcode_editor_tab.buttonSave.setStyleSheet("")
  415. self.ui.gcode_editor_tab.buttonSave.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  416. def on_open_gcode(self):
  417. """
  418. :return:
  419. :rtype:
  420. """
  421. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  422. "All Files (*.*)"
  423. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  424. caption=_('Open file'), directory=self.app.get_last_folder(), filter=_filter_)
  425. if path:
  426. file = QtCore.QFile(path)
  427. if file.open(QtCore.QIODevice.ReadOnly):
  428. stream = QtCore.QTextStream(file)
  429. self.code_edited = stream.readAll()
  430. self.ui.gcode_editor_tab.load_text(self.code_edited, move_to_start=True, clear_text=True)
  431. file.close()
  432. def on_name_activate(self):
  433. self.edited_obj_name = self.ui.name_entry.get_value()
  434. class AppGCodeEditorUI:
  435. def __init__(self, app):
  436. self.app = app
  437. # Number of decimals used by tools in this class
  438. self.decimals = self.app.decimals
  439. # ## Current application units in Upper Case
  440. self.units = self.app.defaults['units'].upper()
  441. # self.setSizePolicy(
  442. # QtWidgets.QSizePolicy.MinimumExpanding,
  443. # QtWidgets.QSizePolicy.MinimumExpanding
  444. # )
  445. self.gcode_editor_tab = None
  446. self.edit_widget = QtWidgets.QWidget()
  447. # ## Box for custom widgets
  448. # This gets populated in offspring implementations.
  449. layout = QtWidgets.QVBoxLayout()
  450. self.edit_widget.setLayout(layout)
  451. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  452. # this way I can hide/show the frame
  453. self.edit_frame = QtWidgets.QFrame()
  454. self.edit_frame.setContentsMargins(0, 0, 0, 0)
  455. layout.addWidget(self.edit_frame)
  456. self.edit_box = QtWidgets.QVBoxLayout()
  457. self.edit_box.setContentsMargins(0, 0, 0, 0)
  458. self.edit_frame.setLayout(self.edit_box)
  459. # ## Page Title box (spacing between children)
  460. self.title_box = QtWidgets.QHBoxLayout()
  461. self.edit_box.addLayout(self.title_box)
  462. # ## Page Title icon
  463. pixmap = QtGui.QPixmap(self.app.resource_location + '/flatcam_icon32.png')
  464. self.icon = QtWidgets.QLabel()
  465. self.icon.setPixmap(pixmap)
  466. self.title_box.addWidget(self.icon, stretch=0)
  467. # ## Title label
  468. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('GCode Editor'))
  469. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  470. self.title_box.addWidget(self.title_label, stretch=1)
  471. # ## Object name
  472. self.name_box = QtWidgets.QHBoxLayout()
  473. self.edit_box.addLayout(self.name_box)
  474. name_label = QtWidgets.QLabel(_("Name:"))
  475. self.name_box.addWidget(name_label)
  476. self.name_entry = FCEntry()
  477. self.name_box.addWidget(self.name_entry)
  478. separator_line = QtWidgets.QFrame()
  479. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  480. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  481. self.edit_box.addWidget(separator_line)
  482. # CNC Tools Table when made out of Geometry
  483. self.cnc_tools_table = FCTable()
  484. self.cnc_tools_table.setSortingEnabled(False)
  485. self.cnc_tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  486. self.edit_box.addWidget(self.cnc_tools_table)
  487. self.cnc_tools_table.setColumnCount(6)
  488. self.cnc_tools_table.setColumnWidth(0, 20)
  489. self.cnc_tools_table.setHorizontalHeaderLabels(['#', _('Dia'), _('Offset'), _('Type'), _('TT'), ''])
  490. self.cnc_tools_table.setColumnHidden(5, True)
  491. # CNC Tools Table when made out of Excellon
  492. self.exc_cnc_tools_table = FCTable()
  493. self.exc_cnc_tools_table.setSortingEnabled(False)
  494. self.exc_cnc_tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  495. self.edit_box.addWidget(self.exc_cnc_tools_table)
  496. self.exc_cnc_tools_table.setColumnCount(6)
  497. self.exc_cnc_tools_table.setColumnWidth(0, 20)
  498. self.exc_cnc_tools_table.setHorizontalHeaderLabels(['#', _('Dia'), _('Drills'), _('Slots'), '', _("Cut Z")])
  499. self.exc_cnc_tools_table.setColumnHidden(4, True)
  500. separator_line = QtWidgets.QFrame()
  501. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  502. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  503. self.edit_box.addWidget(separator_line)
  504. # Prepend text to GCode
  505. prependlabel = QtWidgets.QLabel('%s:' % _('Prepend to CNC Code'))
  506. prependlabel.setToolTip(
  507. _("Type here any G-Code commands you would\n"
  508. "like to add at the beginning of the G-Code file.")
  509. )
  510. self.edit_box.addWidget(prependlabel)
  511. self.prepend_text = FCTextArea()
  512. self.prepend_text.setPlaceholderText(
  513. _("Type here any G-Code commands you would\n"
  514. "like to add at the beginning of the G-Code file.")
  515. )
  516. self.edit_box.addWidget(self.prepend_text)
  517. # Append text to GCode
  518. appendlabel = QtWidgets.QLabel('%s:' % _('Append to CNC Code'))
  519. appendlabel.setToolTip(
  520. _("Type here any G-Code commands you would\n"
  521. "like to append to the generated file.\n"
  522. "I.e.: M2 (End of program)")
  523. )
  524. self.edit_box.addWidget(appendlabel)
  525. self.append_text = FCTextArea()
  526. self.append_text.setPlaceholderText(
  527. _("Type here any G-Code commands you would\n"
  528. "like to append to the generated file.\n"
  529. "I.e.: M2 (End of program)")
  530. )
  531. self.edit_box.addWidget(self.append_text)
  532. h_lay = QtWidgets.QHBoxLayout()
  533. h_lay.setAlignment(QtCore.Qt.AlignVCenter)
  534. self.edit_box.addLayout(h_lay)
  535. # GO Button
  536. self.update_gcode_button = FCButton(_('Update Code'))
  537. # self.update_gcode_button.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  538. self.update_gcode_button.setToolTip(
  539. _("Update the Gcode in the Editor with the values\n"
  540. "in the 'Prepend' and 'Append' text boxes.")
  541. )
  542. h_lay.addWidget(self.update_gcode_button)
  543. layout.addStretch()
  544. # Editor
  545. self.exit_editor_button = FCButton(_('Exit Editor'))
  546. self.exit_editor_button.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  547. self.exit_editor_button.setToolTip(
  548. _("Exit from Editor.")
  549. )
  550. self.exit_editor_button.setStyleSheet("""
  551. QPushButton
  552. {
  553. font-weight: bold;
  554. }
  555. """)
  556. layout.addWidget(self.exit_editor_button)
  557. # ############################ FINSIHED GUI ##################################################################
  558. # #############################################################################################################
  559. def confirmation_message(self, accepted, minval, maxval):
  560. if accepted is False:
  561. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  562. self.decimals,
  563. minval,
  564. self.decimals,
  565. maxval), False)
  566. else:
  567. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  568. def confirmation_message_int(self, accepted, minval, maxval):
  569. if accepted is False:
  570. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  571. (_("Edited value is out of range"), minval, maxval), False)
  572. else:
  573. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)