ToolShell.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. # from PyQt5.QtCore import pyqtSignal
  9. from PyQt5.QtCore import Qt
  10. from PyQt5.QtGui import QTextCursor
  11. from PyQt5.QtWidgets import QVBoxLayout, QWidget
  12. from flatcamGUI.GUIElements import _BrowserTextEdit, _ExpandableTextEdit
  13. import html
  14. import sys
  15. import gettext
  16. import FlatCAMTranslation as fcTranslate
  17. import builtins
  18. fcTranslate.apply_language('strings')
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. class TermWidget(QWidget):
  22. """
  23. Widget which represents terminal. It only displays text and allows to enter text.
  24. All high level logic should be implemented by client classes
  25. User pressed Enter. Client class should decide, if command must be executed or user may continue edit it
  26. """
  27. def __init__(self, version, *args):
  28. QWidget.__init__(self, *args)
  29. self._browser = _BrowserTextEdit(version=version)
  30. self._browser.setStyleSheet("font: 9pt \"Courier\";")
  31. self._browser.setReadOnly(True)
  32. self._browser.document().setDefaultStyleSheet(
  33. self._browser.document().defaultStyleSheet() +
  34. "span {white-space:pre;}")
  35. self._edit = _ExpandableTextEdit(self, self)
  36. self._edit.historyNext.connect(self._on_history_next)
  37. self._edit.historyPrev.connect(self._on_history_prev)
  38. self._edit.setFocus()
  39. self.setFocusProxy(self._edit)
  40. layout = QVBoxLayout(self)
  41. layout.setSpacing(0)
  42. layout.setContentsMargins(0, 0, 0, 0)
  43. layout.addWidget(self._browser)
  44. layout.addWidget(self._edit)
  45. self._history = [''] # current empty line
  46. self._historyIndex = 0
  47. def open_proccessing(self, detail=None):
  48. """
  49. Open processing and disable using shell commands again until all commands are finished
  50. :param detail: text detail about what is currently called from TCL to python
  51. :return: None
  52. """
  53. self._edit.setTextColor(Qt.white)
  54. self._edit.setTextBackgroundColor(Qt.darkGreen)
  55. if detail is None:
  56. self._edit.setPlainText(_("...proccessing..."))
  57. else:
  58. self._edit.setPlainText('%s [%s]' % (_("...proccessing..."), detail))
  59. self._edit.setDisabled(True)
  60. self._edit.setFocus()
  61. def close_proccessing(self):
  62. """
  63. Close processing and enable using shell commands again
  64. :return:
  65. """
  66. self._edit.setTextColor(Qt.black)
  67. self._edit.setTextBackgroundColor(Qt.white)
  68. self._edit.setPlainText('')
  69. self._edit.setDisabled(False)
  70. self._edit.setFocus()
  71. def _append_to_browser(self, style, text):
  72. """
  73. Convert text to HTML for inserting it to browser
  74. """
  75. assert style in ('in', 'out', 'err', 'warning', 'success', 'selected')
  76. text = html.escape(text)
  77. text = text.replace('\n', '<br/>')
  78. if style == 'in':
  79. text = '<span style="font-weight: bold;">%s</span>' % text
  80. elif style == 'err':
  81. text = '<span style="font-weight: bold; color: red;">%s</span>' % text
  82. elif style == 'warning':
  83. text = '<span style="font-weight: bold; color: #f4b642;">%s</span>' % text
  84. elif style == 'success':
  85. text = '<span style="font-weight: bold; color: #084400;">%s</span>' % text
  86. elif style == 'selected':
  87. text = ''
  88. else:
  89. text = '<span>%s</span>' % text # without span <br/> is ignored!!!
  90. scrollbar = self._browser.verticalScrollBar()
  91. old_value = scrollbar.value()
  92. scrollattheend = old_value == scrollbar.maximum()
  93. self._browser.moveCursor(QTextCursor.End)
  94. self._browser.insertHtml(text)
  95. """TODO When user enters second line to the input, and input is resized, scrollbar changes its position
  96. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  97. To fix it correctly, scroll to the bottom, if before input has been resized,
  98. scrollbar was in the bottom, and remove next line
  99. """
  100. scrollattheend = True
  101. if scrollattheend:
  102. scrollbar.setValue(scrollbar.maximum())
  103. else:
  104. scrollbar.setValue(old_value)
  105. def exec_current_command(self):
  106. """
  107. Save current command in the history. Append it to the log. Clear edit line
  108. Re-implement in the child classes to actually execute command
  109. """
  110. text = str(self._edit.toPlainText())
  111. # in Windows replace all backslash symbols '\' with '\\' slash because Windows paths are made with backslash
  112. # and in Python single slash is the escape symbol
  113. if sys.platform == 'win32':
  114. text = text.replace('\\', '\\\\')
  115. self._append_to_browser('in', '> ' + text + '\n')
  116. if len(self._history) < 2 or self._history[-2] != text: # don't insert duplicating items
  117. if text[-1] == '\n':
  118. self._history.insert(-1, text[:-1])
  119. else:
  120. self._history.insert(-1, text)
  121. self._historyIndex = len(self._history) - 1
  122. self._history[-1] = ''
  123. self._edit.clear()
  124. if not text[-1] == '\n':
  125. text += '\n'
  126. self.child_exec_command(text)
  127. def child_exec_command(self, text):
  128. """
  129. Re-implement in the child classes
  130. """
  131. pass
  132. def add_line_break_to_input(self):
  133. self._edit.textCursor().insertText('\n')
  134. def append_output(self, text):
  135. """
  136. Append text to output widget
  137. """
  138. self._append_to_browser('out', text)
  139. def append_success(self, text):
  140. """Appent text to output widget
  141. """
  142. self._append_to_browser('success', text)
  143. def append_selected(self, text):
  144. """Appent text to output widget
  145. """
  146. self._append_to_browser('selected', text)
  147. def append_warning(self, text):
  148. """Appent text to output widget
  149. """
  150. self._append_to_browser('warning', text)
  151. def append_error(self, text):
  152. """Appent error text to output widget. Text is drawn with red background
  153. """
  154. self._append_to_browser('err', text)
  155. def is_command_complete(self, text):
  156. """
  157. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  158. """
  159. return True
  160. def browser(self):
  161. return self._browser
  162. def _on_history_next(self):
  163. """
  164. Down pressed, show next item from the history
  165. """
  166. if (self._historyIndex + 1) < len(self._history):
  167. self._historyIndex += 1
  168. self._edit.setPlainText(self._history[self._historyIndex])
  169. self._edit.moveCursor(QTextCursor.End)
  170. def _on_history_prev(self):
  171. """
  172. Up pressed, show previous item from the history
  173. """
  174. if self._historyIndex > 0:
  175. if self._historyIndex == (len(self._history) - 1):
  176. self._history[-1] = self._edit.toPlainText()
  177. self._historyIndex -= 1
  178. self._edit.setPlainText(self._history[self._historyIndex])
  179. self._edit.moveCursor(QTextCursor.End)
  180. class FCShell(TermWidget):
  181. def __init__(self, sysShell, version, *args):
  182. TermWidget.__init__(self, version, *args)
  183. self._sysShell = sysShell
  184. def is_command_complete(self, text):
  185. def skipQuotes(text):
  186. quote = text[0]
  187. text = text[1:]
  188. endIndex = str(text).index(quote)
  189. return text[endIndex:]
  190. while text:
  191. if text[0] in ('"', "'"):
  192. try:
  193. text = skipQuotes(text)
  194. except ValueError:
  195. return False
  196. text = text[1:]
  197. return True
  198. def child_exec_command(self, text):
  199. self._sysShell.exec_command(text)