FlatCAMTextEditor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. "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);;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. doc = SimpleDocTemplate(
  189. filename,
  190. pagesize=page_size,
  191. bottomMargin=0.4 * inch,
  192. topMargin=0.6 * inch,
  193. rightMargin=0.8 * inch,
  194. leftMargin=0.8 * inch)
  195. P = Paragraph(lined_gcode, styleN)
  196. story.append(P)
  197. doc.build(
  198. story,
  199. )
  200. else:
  201. with open(filename, 'w') as f:
  202. for line in my_gcode:
  203. f.write(line)
  204. except FileNotFoundError:
  205. self.app.inform.emit('[WARNING] %s' % _("No such file or directory"))
  206. return
  207. except PermissionError:
  208. self.app.inform.emit('[WARNING] %s' %
  209. _("Permission denied, saving not possible.\n"
  210. "Most likely another app is holding the file open and not accessible."))
  211. return
  212. # Just for adding it to the recent files list.
  213. if self.app.defaults["global_open_style"] is False:
  214. self.app.file_opened.emit("cncjob", filename)
  215. self.app.file_saved.emit("cncjob", filename)
  216. self.app.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  217. if callback is not None:
  218. callback()
  219. def handleFindGCode(self):
  220. self.app.report_usage("handleFindGCode()")
  221. flags = QtGui.QTextDocument.FindCaseSensitively
  222. text_to_be_found = self.entryFind.get_value()
  223. r = self.code_editor.find(str(text_to_be_found), flags)
  224. if r is False:
  225. self.code_editor.moveCursor(QtGui.QTextCursor.Start)
  226. r = self.code_editor.find(str(text_to_be_found), flags)
  227. def handleReplaceGCode(self):
  228. self.app.report_usage("handleReplaceGCode()")
  229. old = self.entryFind.get_value()
  230. new = self.entryReplace.get_value()
  231. if self.sel_all_cb.isChecked():
  232. while True:
  233. cursor = self.code_editor.textCursor()
  234. cursor.beginEditBlock()
  235. flags = QtGui.QTextDocument.FindCaseSensitively
  236. # self.ui.editor is the QPlainTextEdit
  237. r = self.code_editor.find(str(old), flags)
  238. if r:
  239. qc = self.code_editor.textCursor()
  240. if qc.hasSelection():
  241. qc.insertText(new)
  242. else:
  243. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  244. break
  245. # Mark end of undo block
  246. cursor.endEditBlock()
  247. else:
  248. cursor = self.code_editor.textCursor()
  249. cursor.beginEditBlock()
  250. qc = self.code_editor.textCursor()
  251. if qc.hasSelection():
  252. qc.insertText(new)
  253. # Mark end of undo block
  254. cursor.endEditBlock()
  255. def handleCopyAll(self):
  256. text = self.code_editor.toPlainText()
  257. self.app.clipboard.setText(text)
  258. self.app.inform.emit(_("Code Editor content copied to clipboard ..."))
  259. # def closeEvent(self, QCloseEvent):
  260. # super().closeEvent(QCloseEvent)