FlatCAMTextEditor.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 10/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from flatcamGUI.GUIElements import *
  8. from PyQt5 import QtPrintSupport
  9. from reportlab.platypus import SimpleDocTemplate, Paragraph
  10. from reportlab.lib.styles import getSampleStyleSheet
  11. from reportlab.lib.units import inch, mm
  12. from io import StringIO
  13. import gettext
  14. import FlatCAMTranslation as fcTranslate
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. class TextEditor(QtWidgets.QWidget):
  20. def __init__(self, app, text=None, plain_text=None):
  21. super().__init__()
  22. self.app = app
  23. self.setSizePolicy(
  24. QtWidgets.QSizePolicy.MinimumExpanding,
  25. QtWidgets.QSizePolicy.MinimumExpanding
  26. )
  27. self.main_editor_layout = QtWidgets.QVBoxLayout(self)
  28. self.main_editor_layout.setContentsMargins(0, 0, 0, 0)
  29. self.t_frame = QtWidgets.QFrame()
  30. self.t_frame.setContentsMargins(0, 0, 0, 0)
  31. self.main_editor_layout.addWidget(self.t_frame)
  32. self.work_editor_layout = QtWidgets.QGridLayout(self.t_frame)
  33. self.work_editor_layout.setContentsMargins(2, 2, 2, 2)
  34. self.t_frame.setLayout(self.work_editor_layout)
  35. if plain_text:
  36. self.editor_class = FCTextAreaLineNumber()
  37. self.code_editor = self.editor_class.edit
  38. stylesheet = """
  39. QPlainTextEdit { selection-background-color:yellow;
  40. selection-color:black;
  41. }
  42. """
  43. self.work_editor_layout.addWidget(self.editor_class, 0, 0, 1, 5)
  44. else:
  45. self.code_editor = FCTextAreaExtended()
  46. stylesheet = """
  47. QTextEdit { selection-background-color:yellow;
  48. selection-color:black;
  49. }
  50. """
  51. self.work_editor_layout.addWidget(self.code_editor, 0, 0, 1, 5)
  52. self.code_editor.setStyleSheet(stylesheet)
  53. if text:
  54. self.code_editor.setPlainText(text)
  55. self.buttonPreview = QtWidgets.QPushButton(_('Print Preview'))
  56. self.buttonPreview.setToolTip(_("Open a OS standard Preview Print window."))
  57. self.buttonPreview.setMinimumWidth(100)
  58. self.buttonPrint = QtWidgets.QPushButton(_('Print Code'))
  59. self.buttonPrint.setToolTip(_("Open a OS standard Print window."))
  60. self.buttonFind = QtWidgets.QPushButton(_('Find in Code'))
  61. self.buttonFind.setToolTip(_("Will search and highlight in yellow the string in the Find box."))
  62. self.buttonFind.setMinimumWidth(100)
  63. self.entryFind = FCEntry()
  64. self.entryFind.setToolTip(_("Find box. Enter here the strings to be searched in the text."))
  65. self.buttonReplace = QtWidgets.QPushButton(_('Replace With'))
  66. self.buttonReplace.setToolTip(_("Will replace the string from the Find box with the one in the Replace box."))
  67. self.buttonReplace.setMinimumWidth(100)
  68. self.entryReplace = FCEntry()
  69. self.entryReplace.setToolTip(_("String to replace the one in the Find box throughout the text."))
  70. self.sel_all_cb = QtWidgets.QCheckBox(_('All'))
  71. self.sel_all_cb.setToolTip(_("When checked it will replace all instances in the 'Find' box\n"
  72. "with the text in the 'Replace' box.."))
  73. self.button_copy_all = QtWidgets.QPushButton(_('Copy All'))
  74. self.button_copy_all.setToolTip(_("Will copy all the text in the Code Editor to the clipboard."))
  75. self.button_copy_all.setMinimumWidth(100)
  76. self.buttonOpen = QtWidgets.QPushButton(_('Open Code'))
  77. self.buttonOpen.setToolTip(_("Will open a text file in the editor."))
  78. self.buttonSave = QtWidgets.QPushButton(_('Save Code'))
  79. self.buttonSave.setToolTip(_("Will save the text in the editor into a file."))
  80. self.buttonRun = QtWidgets.QPushButton(_('Run Code'))
  81. self.buttonRun.setToolTip(_("Will run the TCL commands found in the text file, one by one."))
  82. self.buttonRun.hide()
  83. editor_hlay_1 = QtWidgets.QHBoxLayout()
  84. # cnc_tab_lay_1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  85. editor_hlay_1.addWidget(self.buttonFind)
  86. editor_hlay_1.addWidget(self.entryFind)
  87. editor_hlay_1.addWidget(self.buttonReplace)
  88. editor_hlay_1.addWidget(self.entryReplace)
  89. editor_hlay_1.addWidget(self.sel_all_cb)
  90. editor_hlay_1.addWidget(self.button_copy_all)
  91. self.work_editor_layout.addLayout(editor_hlay_1, 1, 0, 1, 5)
  92. editor_hlay_2 = QtWidgets.QHBoxLayout()
  93. editor_hlay_2.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  94. editor_hlay_2.addWidget(self.buttonPreview)
  95. editor_hlay_2.addWidget(self.buttonPrint)
  96. self.work_editor_layout.addLayout(editor_hlay_2, 2, 0, 1, 1, QtCore.Qt.AlignLeft)
  97. cnc_tab_lay_4 = QtWidgets.QHBoxLayout()
  98. cnc_tab_lay_4.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  99. cnc_tab_lay_4.addWidget(self.buttonOpen)
  100. cnc_tab_lay_4.addWidget(self.buttonSave)
  101. cnc_tab_lay_4.addWidget(self.buttonRun)
  102. self.work_editor_layout.addLayout(cnc_tab_lay_4, 2, 4, 1, 1)
  103. # #################################################################################
  104. # ################### SIGNALS #####################################################
  105. # #################################################################################
  106. self.code_editor.textChanged.connect(self.handleTextChanged)
  107. self.buttonOpen.clicked.connect(self.handleOpen)
  108. self.buttonSave.clicked.connect(self.handleSaveGCode)
  109. self.buttonPrint.clicked.connect(self.handlePrint)
  110. self.buttonPreview.clicked.connect(self.handlePreview)
  111. self.buttonFind.clicked.connect(self.handleFindGCode)
  112. self.buttonReplace.clicked.connect(self.handleReplaceGCode)
  113. self.button_copy_all.clicked.connect(self.handleCopyAll)
  114. self.code_editor.set_model_data(self.app.myKeywords)
  115. self.code_edited = ''
  116. def handlePrint(self):
  117. self.app.report_usage("handlePrint()")
  118. dialog = QtPrintSupport.QPrintDialog()
  119. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  120. self.code_editor.document().print_(dialog.printer())
  121. def handlePreview(self):
  122. self.app.report_usage("handlePreview()")
  123. dialog = QtPrintSupport.QPrintPreviewDialog()
  124. dialog.paintRequested.connect(self.code_editor.print_)
  125. dialog.exec_()
  126. def handleTextChanged(self):
  127. # enable = not self.ui.code_editor.document().isEmpty()
  128. # self.ui.buttonPrint.setEnabled(enable)
  129. # self.ui.buttonPreview.setEnabled(enable)
  130. pass
  131. def handleOpen(self, filt=None):
  132. self.app.report_usage("handleOpen()")
  133. if filt:
  134. _filter_ = filt
  135. else:
  136. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  137. "All Files (*.*)"
  138. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  139. caption=_('Open file'), directory=self.app.get_last_folder(), filter=_filter_)
  140. if path:
  141. file = QtCore.QFile(path)
  142. if file.open(QtCore.QIODevice.ReadOnly):
  143. stream = QtCore.QTextStream(file)
  144. self.code_edited = stream.readAll()
  145. self.code_editor.setPlainText(self.code_edited)
  146. file.close()
  147. def handleSaveGCode(self, name=None, filt=None, callback=None):
  148. self.app.report_usage("handleSaveGCode()")
  149. if filt:
  150. _filter_ = filt
  151. else:
  152. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  153. "PDF Files (*.pdf);;All Files (*.*)"
  154. if name:
  155. obj_name = name
  156. else:
  157. try:
  158. obj_name = self.app.collection.get_active().options['name']
  159. except AttributeError:
  160. obj_name = 'file'
  161. if filt is None:
  162. _filter_ = "FlatConfig Files (*.FlatConfig);;PDF Files (*.pdf);;All Files (*.*)"
  163. try:
  164. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  165. caption=_("Export Code ..."),
  166. directory=self.app.defaults["global_last_folder"] + '/' + str(obj_name),
  167. filter=_filter_
  168. )[0])
  169. except TypeError:
  170. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Code ..."), filter=_filter_)[0])
  171. if filename == "":
  172. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Code cancelled."))
  173. return
  174. else:
  175. try:
  176. my_gcode = self.code_editor.toPlainText()
  177. if filename.rpartition('.')[2].lower() == 'pdf':
  178. page_size = (
  179. self.app.plotcanvas.pagesize_dict[self.app.defaults['global_workspaceT']][0] * mm,
  180. self.app.plotcanvas.pagesize_dict[self.app.defaults['global_workspaceT']][1] * mm
  181. )
  182. # add new line after each line
  183. lined_gcode = my_gcode.replace("\n", "<br />")
  184. styles = getSampleStyleSheet()
  185. styleN = styles['Normal']
  186. styleH = styles['Heading1']
  187. story = []
  188. if self.app.defaults['units'].lower() == 'mm':
  189. bmargin = self.app.defaults['global_tpdf_bmargin'] * mm
  190. tmargin = self.app.defaults['global_tpdf_tmargin'] * mm
  191. rmargin = self.app.defaults['global_tpdf_rmargin'] * mm
  192. lmargin = self.app.defaults['global_tpdf_lmargin'] * mm
  193. else:
  194. bmargin = self.app.defaults['global_tpdf_bmargin'] * inch
  195. tmargin = self.app.defaults['global_tpdf_tmargin'] * inch
  196. rmargin = self.app.defaults['global_tpdf_rmargin'] * inch
  197. lmargin = self.app.defaults['global_tpdf_lmargin'] * inch
  198. doc = SimpleDocTemplate(
  199. filename,
  200. pagesize=page_size,
  201. bottomMargin=bmargin,
  202. topMargin=tmargin,
  203. rightMargin=rmargin,
  204. leftMargin=lmargin)
  205. P = Paragraph(lined_gcode, styleN)
  206. story.append(P)
  207. doc.build(
  208. story,
  209. )
  210. else:
  211. with open(filename, 'w') as f:
  212. for line in my_gcode:
  213. f.write(line)
  214. except FileNotFoundError:
  215. self.app.inform.emit('[WARNING] %s' % _("No such file or directory"))
  216. return
  217. except PermissionError:
  218. self.app.inform.emit('[WARNING] %s' %
  219. _("Permission denied, saving not possible.\n"
  220. "Most likely another app is holding the file open and not accessible."))
  221. return
  222. # Just for adding it to the recent files list.
  223. if self.app.defaults["global_open_style"] is False:
  224. self.app.file_opened.emit("cncjob", filename)
  225. self.app.file_saved.emit("cncjob", filename)
  226. self.app.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  227. if callback is not None:
  228. callback()
  229. def handleFindGCode(self):
  230. self.app.report_usage("handleFindGCode()")
  231. flags = QtGui.QTextDocument.FindCaseSensitively
  232. text_to_be_found = self.entryFind.get_value()
  233. r = self.code_editor.find(str(text_to_be_found), flags)
  234. if r is False:
  235. self.code_editor.moveCursor(QtGui.QTextCursor.Start)
  236. r = self.code_editor.find(str(text_to_be_found), flags)
  237. def handleReplaceGCode(self):
  238. self.app.report_usage("handleReplaceGCode()")
  239. old = self.entryFind.get_value()
  240. new = self.entryReplace.get_value()
  241. if self.sel_all_cb.isChecked():
  242. while True:
  243. cursor = self.code_editor.textCursor()
  244. cursor.beginEditBlock()
  245. flags = QtGui.QTextDocument.FindCaseSensitively
  246. # self.ui.editor is the QPlainTextEdit
  247. r = self.code_editor.find(str(old), flags)
  248. if r:
  249. qc = self.code_editor.textCursor()
  250. if qc.hasSelection():
  251. qc.insertText(new)
  252. else:
  253. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  254. break
  255. # Mark end of undo block
  256. cursor.endEditBlock()
  257. else:
  258. cursor = self.code_editor.textCursor()
  259. cursor.beginEditBlock()
  260. qc = self.code_editor.textCursor()
  261. if qc.hasSelection():
  262. qc.insertText(new)
  263. # Mark end of undo block
  264. cursor.endEditBlock()
  265. def handleCopyAll(self):
  266. text = self.code_editor.toPlainText()
  267. self.app.clipboard.setText(text)
  268. self.app.inform.emit(_("Code Editor content copied to clipboard ..."))
  269. # def closeEvent(self, QCloseEvent):
  270. # super().closeEvent(QCloseEvent)