AppTextEditor.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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.button_update_code = QtWidgets.QToolButton()
  85. self.button_update_code.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  86. self.button_update_code.setToolTip(_("Save changes internally."))
  87. self.button_update_code.hide()
  88. self.buttonOpen = FCButton(_('Open Code'))
  89. self.buttonOpen.setIcon(QtGui.QIcon(self.app.resource_location + '/folder32_bis.png'))
  90. self.buttonOpen.setToolTip(_("Will open a text file in the editor."))
  91. self.buttonOpen.setMinimumWidth(100)
  92. self.buttonSave = FCButton(_('Save Code'))
  93. self.buttonSave.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  94. self.buttonSave.setToolTip(_("Will save the text in the editor into a file."))
  95. self.buttonSave.setMinimumWidth(100)
  96. self.buttonRun = FCButton(_('Run Code'))
  97. self.buttonRun.setToolTip(_("Will run the TCL commands found in the text file, one by one."))
  98. self.buttonRun.setMinimumWidth(100)
  99. self.buttonRun.hide()
  100. editor_hlay_1 = QtWidgets.QHBoxLayout()
  101. # cnc_tab_lay_1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  102. editor_hlay_1.addWidget(self.buttonFind)
  103. editor_hlay_1.addWidget(self.entryFind)
  104. editor_hlay_1.addWidget(self.buttonReplace)
  105. editor_hlay_1.addWidget(self.entryReplace)
  106. editor_hlay_1.addWidget(self.sel_all_cb)
  107. editor_hlay_1.addWidget(self.button_copy_all)
  108. editor_hlay_1.addWidget(self.button_update_code)
  109. self.work_editor_layout.addLayout(editor_hlay_1, 1, 0, 1, 5)
  110. editor_hlay_2 = QtWidgets.QHBoxLayout()
  111. editor_hlay_2.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  112. editor_hlay_2.addWidget(self.buttonPreview)
  113. editor_hlay_2.addWidget(self.buttonPrint)
  114. self.work_editor_layout.addLayout(editor_hlay_2, 2, 0, 1, 1, QtCore.Qt.AlignLeft)
  115. cnc_tab_lay_4 = QtWidgets.QHBoxLayout()
  116. cnc_tab_lay_4.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  117. cnc_tab_lay_4.addWidget(self.buttonOpen)
  118. cnc_tab_lay_4.addWidget(self.buttonSave)
  119. cnc_tab_lay_4.addWidget(self.buttonRun)
  120. self.work_editor_layout.addLayout(cnc_tab_lay_4, 2, 4, 1, 1)
  121. # #################################################################################
  122. # ################### SIGNALS #####################################################
  123. # #################################################################################
  124. self.code_editor.textChanged.connect(self.handleTextChanged)
  125. self.buttonOpen.clicked.connect(self.handleOpen)
  126. self.buttonSave.clicked.connect(self.handleSaveGCode)
  127. self.buttonPrint.clicked.connect(self.handlePrint)
  128. self.buttonPreview.clicked.connect(self.handlePreview)
  129. self.buttonFind.clicked.connect(self.handleFindGCode)
  130. self.buttonReplace.clicked.connect(self.handleReplaceGCode)
  131. self.button_copy_all.clicked.connect(self.handleCopyAll)
  132. self.code_editor.set_model_data(self.app.myKeywords)
  133. self.code_edited = ''
  134. def set_callback(self, callback):
  135. self.callback = callback
  136. def handlePrint(self):
  137. dialog = QtPrintSupport.QPrintDialog()
  138. if dialog.exec() == QtWidgets.QDialog.Accepted:
  139. self.code_editor.document().print_(dialog.printer())
  140. def handlePreview(self):
  141. dialog = QtPrintSupport.QPrintPreviewDialog()
  142. dialog.paintRequested.connect(self.code_editor.print)
  143. dialog.exec()
  144. def handleTextChanged(self):
  145. # enable = not self.ui.code_editor.document().isEmpty()
  146. # self.ui.buttonPrint.setEnabled(enable)
  147. # self.ui.buttonPreview.setEnabled(enable)
  148. self.buttonSave.setStyleSheet("QPushButton {color: red;}")
  149. self.buttonSave.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as_red.png'))
  150. def load_text(self, text, move_to_start=False, move_to_end=False, clear_text=True, as_html=False):
  151. self.code_editor.textChanged.disconnect()
  152. if clear_text:
  153. # first clear previous text in text editor (if any)
  154. self.code_editor.clear()
  155. self.code_editor.setReadOnly(False)
  156. if as_html is False:
  157. self.code_editor.setPlainText(text)
  158. else:
  159. self.code_editor.setHtml(text)
  160. if move_to_start:
  161. self.code_editor.moveCursor(QtGui.QTextCursor.Start)
  162. elif move_to_end:
  163. self.code_editor.moveCursor(QtGui.QTextCursor.End)
  164. self.code_editor.textChanged.connect(self.handleTextChanged)
  165. def handleOpen(self, filt=None):
  166. self.app.defaults.report_usage("handleOpen()")
  167. if filt:
  168. _filter_ = filt
  169. else:
  170. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  171. "All Files (*.*)"
  172. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  173. caption=_('Open file'), directory=self.app.get_last_folder(), filter=_filter_)
  174. if path:
  175. file = QtCore.QFile(path)
  176. if file.open(QtCore.QIODevice.ReadOnly):
  177. stream = QtCore.QTextStream(file)
  178. self.code_edited = stream.readAll()
  179. self.code_editor.setPlainText(self.code_edited)
  180. file.close()
  181. def handleSaveGCode(self, name=None, filt=None, callback=None):
  182. self.app.defaults.report_usage("handleSaveGCode()")
  183. if filt:
  184. _filter_ = filt
  185. else:
  186. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  187. "PDF Files (*.pdf);;All Files (*.*)"
  188. if name:
  189. obj_name = name
  190. else:
  191. try:
  192. obj_name = self.app.collection.get_active().options['name']
  193. except AttributeError:
  194. obj_name = 'file'
  195. if filt is None:
  196. _filter_ = "FlatConfig Files (*.FlatConfig);;PDF Files (*.pdf);;All Files (*.*)"
  197. try:
  198. filename = str(FCFileSaveDialog.get_saved_filename(
  199. caption=_("Export Code ..."),
  200. directory=self.app.defaults["global_last_folder"] + '/' + str(obj_name),
  201. ext_filter=_filter_
  202. )[0])
  203. except TypeError:
  204. filename = str(FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)[0])
  205. if filename == "":
  206. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  207. return
  208. else:
  209. try:
  210. my_gcode = self.code_editor.toPlainText()
  211. if filename.rpartition('.')[2].lower() == 'pdf':
  212. page_size = (
  213. self.app.plotcanvas.pagesize_dict[self.app.defaults['global_workspaceT']][0] * mm,
  214. self.app.plotcanvas.pagesize_dict[self.app.defaults['global_workspaceT']][1] * mm
  215. )
  216. # add new line after each line
  217. lined_gcode = my_gcode.replace("\n", "<br />")
  218. styles = getSampleStyleSheet()
  219. styleN = styles['Normal']
  220. # styleH = styles['Heading1']
  221. story = []
  222. if self.app.defaults['units'].lower() == 'mm':
  223. bmargin = self.app.defaults['global_tpdf_bmargin'] * mm
  224. tmargin = self.app.defaults['global_tpdf_tmargin'] * mm
  225. rmargin = self.app.defaults['global_tpdf_rmargin'] * mm
  226. lmargin = self.app.defaults['global_tpdf_lmargin'] * mm
  227. else:
  228. bmargin = self.app.defaults['global_tpdf_bmargin'] * inch
  229. tmargin = self.app.defaults['global_tpdf_tmargin'] * inch
  230. rmargin = self.app.defaults['global_tpdf_rmargin'] * inch
  231. lmargin = self.app.defaults['global_tpdf_lmargin'] * inch
  232. doc = SimpleDocTemplate(
  233. filename,
  234. pagesize=page_size,
  235. bottomMargin=bmargin,
  236. topMargin=tmargin,
  237. rightMargin=rmargin,
  238. leftMargin=lmargin)
  239. P = Paragraph(lined_gcode, styleN)
  240. story.append(P)
  241. doc.build(
  242. story,
  243. )
  244. else:
  245. with open(filename, 'w') as f:
  246. for line in my_gcode:
  247. f.write(line)
  248. self.buttonSave.setStyleSheet("")
  249. self.buttonSave.setIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  250. except FileNotFoundError:
  251. self.app.inform.emit('[WARNING] %s' % _("No such file or directory"))
  252. return
  253. except PermissionError:
  254. self.app.inform.emit('[WARNING] %s' %
  255. _("Permission denied, saving not possible.\n"
  256. "Most likely another app is holding the file open and not accessible."))
  257. return
  258. # Just for adding it to the recent files list.
  259. if self.app.defaults["global_open_style"] is False:
  260. self.app.file_opened.emit("cncjob", filename)
  261. self.app.file_saved.emit("cncjob", filename)
  262. self.app.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  263. if callback is not None:
  264. callback()
  265. def handleFindGCode(self):
  266. flags = QtGui.QTextDocument.FindCaseSensitively
  267. text_to_be_found = self.entryFind.get_value()
  268. r = self.code_editor.find(str(text_to_be_found), flags)
  269. if r is False:
  270. self.code_editor.moveCursor(QtGui.QTextCursor.Start)
  271. r = self.code_editor.find(str(text_to_be_found), flags)
  272. def handleReplaceGCode(self):
  273. old = self.entryFind.get_value()
  274. new = self.entryReplace.get_value()
  275. if self.sel_all_cb.isChecked():
  276. while True:
  277. cursor = self.code_editor.textCursor()
  278. cursor.beginEditBlock()
  279. flags = QtGui.QTextDocument.FindCaseSensitively
  280. # self.ui.editor is the QPlainTextEdit
  281. r = self.code_editor.find(str(old), flags)
  282. if r:
  283. qc = self.code_editor.textCursor()
  284. if qc.hasSelection():
  285. qc.insertText(new)
  286. else:
  287. self.code_editor.moveCursor(QtGui.QTextCursor.Start)
  288. break
  289. # Mark end of undo block
  290. cursor.endEditBlock()
  291. else:
  292. cursor = self.code_editor.textCursor()
  293. cursor.beginEditBlock()
  294. qc = self.code_editor.textCursor()
  295. if qc.hasSelection():
  296. qc.insertText(new)
  297. # Mark end of undo block
  298. cursor.endEditBlock()
  299. def handleCopyAll(self):
  300. text = self.code_editor.toPlainText()
  301. self.app.clipboard.setText(text)
  302. self.app.inform.emit(_("Content copied to clipboard ..."))
  303. # def closeEvent(self, QCloseEvent):
  304. # super().closeEvent(QCloseEvent)