AppTextEditor.py 16 KB

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