ToolShell.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. try:
  118. if text[-1] == '\n':
  119. self._history.insert(-1, text[:-1])
  120. else:
  121. self._history.insert(-1, text)
  122. except IndexError:
  123. return
  124. self._historyIndex = len(self._history) - 1
  125. self._history[-1] = ''
  126. self._edit.clear()
  127. if not text[-1] == '\n':
  128. text += '\n'
  129. self.child_exec_command(text)
  130. def child_exec_command(self, text):
  131. """
  132. Re-implement in the child classes
  133. """
  134. pass
  135. def add_line_break_to_input(self):
  136. self._edit.textCursor().insertText('\n')
  137. def append_output(self, text):
  138. """
  139. Append text to output widget
  140. """
  141. self._append_to_browser('out', text)
  142. def append_success(self, text):
  143. """Appent text to output widget
  144. """
  145. self._append_to_browser('success', text)
  146. def append_selected(self, text):
  147. """Appent text to output widget
  148. """
  149. self._append_to_browser('selected', text)
  150. def append_warning(self, text):
  151. """Appent text to output widget
  152. """
  153. self._append_to_browser('warning', text)
  154. def append_error(self, text):
  155. """Appent error text to output widget. Text is drawn with red background
  156. """
  157. self._append_to_browser('err', text)
  158. def is_command_complete(self, text):
  159. """
  160. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  161. """
  162. return True
  163. def browser(self):
  164. return self._browser
  165. def _on_history_next(self):
  166. """
  167. Down pressed, show next item from the history
  168. """
  169. if (self._historyIndex + 1) < len(self._history):
  170. self._historyIndex += 1
  171. self._edit.setPlainText(self._history[self._historyIndex])
  172. self._edit.moveCursor(QTextCursor.End)
  173. def _on_history_prev(self):
  174. """
  175. Up pressed, show previous item from the history
  176. """
  177. if self._historyIndex > 0:
  178. if self._historyIndex == (len(self._history) - 1):
  179. self._history[-1] = self._edit.toPlainText()
  180. self._historyIndex -= 1
  181. self._edit.setPlainText(self._history[self._historyIndex])
  182. self._edit.moveCursor(QTextCursor.End)
  183. class FCShell(TermWidget):
  184. def __init__(self, sysShell, version, *args):
  185. TermWidget.__init__(self, version, *args)
  186. self._sysShell = sysShell
  187. def is_command_complete(self, text):
  188. def skipQuotes(text):
  189. quote = text[0]
  190. text = text[1:]
  191. endIndex = str(text).index(quote)
  192. return text[endIndex:]
  193. while text:
  194. if text[0] in ('"', "'"):
  195. try:
  196. text = skipQuotes(text)
  197. except ValueError:
  198. return False
  199. text = text[1:]
  200. return True
  201. def child_exec_command(self, text):
  202. self._sysShell.exec_command(text)