appGCodeEditor.py 32 KB

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