appGCodeEditor.py 32 KB

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