ToolShell.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 Qt
  9. from PyQt5.QtGui import QTextCursor
  10. from PyQt5.QtWidgets import QVBoxLayout, QWidget
  11. from flatcamGUI.GUIElements import _BrowserTextEdit, _ExpandableTextEdit
  12. import html
  13. import sys
  14. import tkinter as tk
  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, app, *args):
  28. QWidget.__init__(self, *args)
  29. self._browser = _BrowserTextEdit(version=version, app=app)
  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_processing(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(_("...processing..."))
  57. else:
  58. self._edit.setPlainText('%s [%s]' % (_("...processing..."), detail))
  59. self._edit.setDisabled(True)
  60. self._edit.setFocus()
  61. def close_processing(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', 'raw')
  76. if style != 'raw':
  77. text = html.escape(text)
  78. text = text.replace('\n', '<br/>')
  79. else:
  80. text = text.replace('\n', '<br>')
  81. text = text.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
  82. idx = text.find(']')
  83. mtype = text[:idx+1].upper()
  84. mtype = mtype.replace('_NOTCL', '')
  85. body = text[idx+1:]
  86. if style == 'in':
  87. text = '<span style="font-weight: bold;">%s</span>' % text
  88. elif style == 'err':
  89. text = '<span style="font-weight: bold; color: red;">%s</span>'\
  90. '<span style="font-weight: bold;">%s</span>'\
  91. %(mtype, body)
  92. elif style == 'warning':
  93. # text = '<span style="font-weight: bold; color: #f4b642;">%s</span>' % text
  94. text = '<span style="font-weight: bold; color: #f4b642;">%s</span>' \
  95. '<span style="font-weight: bold;">%s</span>' \
  96. % (mtype, body)
  97. elif style == 'success':
  98. # text = '<span style="font-weight: bold; color: #15b300;">%s</span>' % text
  99. text = '<span style="font-weight: bold; color: #15b300;">%s</span>' \
  100. '<span style="font-weight: bold;">%s</span>' \
  101. % (mtype, body)
  102. elif style == 'selected':
  103. text = ''
  104. elif style == 'raw':
  105. text = text
  106. else:
  107. # without span <br/> is ignored!!!
  108. text = '<span>%s</span>' % text
  109. scrollbar = self._browser.verticalScrollBar()
  110. old_value = scrollbar.value()
  111. # scrollattheend = old_value == scrollbar.maximum()
  112. self._browser.moveCursor(QTextCursor.End)
  113. self._browser.insertHtml(text)
  114. """TODO When user enters second line to the input, and input is resized, scrollbar changes its position
  115. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  116. To fix it correctly, scroll to the bottom, if before input has been resized,
  117. scrollbar was in the bottom, and remove next line
  118. """
  119. scrollattheend = True
  120. if scrollattheend:
  121. scrollbar.setValue(scrollbar.maximum())
  122. else:
  123. scrollbar.setValue(old_value)
  124. def exec_current_command(self):
  125. """
  126. Save current command in the history. Append it to the log. Clear edit line
  127. Re-implement in the child classes to actually execute command
  128. """
  129. text = str(self._edit.toPlainText())
  130. # in Windows replace all backslash symbols '\' with '\\' slash because Windows paths are made with backslash
  131. # and in Python single slash is the escape symbol
  132. if sys.platform == 'win32':
  133. text = text.replace('\\', '\\\\')
  134. self._append_to_browser('in', '> ' + text + '\n')
  135. if len(self._history) < 2 or self._history[-2] != text: # don't insert duplicating items
  136. try:
  137. if text[-1] == '\n':
  138. self._history.insert(-1, text[:-1])
  139. else:
  140. self._history.insert(-1, text)
  141. except IndexError:
  142. return
  143. self._historyIndex = len(self._history) - 1
  144. self._history[-1] = ''
  145. self._edit.clear()
  146. if not text[-1] == '\n':
  147. text += '\n'
  148. self.child_exec_command(text)
  149. def child_exec_command(self, text):
  150. """
  151. Re-implement in the child classes
  152. """
  153. pass
  154. def add_line_break_to_input(self):
  155. self._edit.textCursor().insertText('\n')
  156. def append_output(self, text):
  157. """
  158. Append text to output widget
  159. """
  160. self._append_to_browser('out', text)
  161. def append_raw(self, text):
  162. """
  163. Append text to output widget as it is
  164. """
  165. self._append_to_browser('raw', text)
  166. def append_success(self, text):
  167. """Append text to output widget
  168. """
  169. self._append_to_browser('success', text)
  170. def append_selected(self, text):
  171. """Append text to output widget
  172. """
  173. self._append_to_browser('selected', text)
  174. def append_warning(self, text):
  175. """Append text to output widget
  176. """
  177. self._append_to_browser('warning', text)
  178. def append_error(self, text):
  179. """Append error text to output widget. Text is drawn with red background
  180. """
  181. self._append_to_browser('err', text)
  182. def is_command_complete(self, text):
  183. """
  184. Executed by _ExpandableTextEdit. Reimplement this function in the child classes.
  185. """
  186. return True
  187. def browser(self):
  188. return self._browser
  189. def _on_history_next(self):
  190. """
  191. Down pressed, show next item from the history
  192. """
  193. if (self._historyIndex + 1) < len(self._history):
  194. self._historyIndex += 1
  195. self._edit.setPlainText(self._history[self._historyIndex])
  196. self._edit.moveCursor(QTextCursor.End)
  197. def _on_history_prev(self):
  198. """
  199. Up pressed, show previous item from the history
  200. """
  201. if self._historyIndex > 0:
  202. if self._historyIndex == (len(self._history) - 1):
  203. self._history[-1] = self._edit.toPlainText()
  204. self._historyIndex -= 1
  205. self._edit.setPlainText(self._history[self._historyIndex])
  206. self._edit.moveCursor(QTextCursor.End)
  207. class FCShell(TermWidget):
  208. def __init__(self, sysShell, version, *args):
  209. """
  210. :param sysShell: When instantiated the sysShell will be actually the FlatCAMApp.App() class
  211. :param version: FlatCAM version string
  212. :param args: Parameters passed to the TermWidget parent class
  213. """
  214. TermWidget.__init__(self, version, *args, app=sysShell)
  215. self._sysShell = sysShell
  216. def is_command_complete(self, text):
  217. def skipQuotes(txt):
  218. quote = txt[0]
  219. text_val = txt[1:]
  220. endIndex = str(text_val).index(quote)
  221. return text[endIndex:]
  222. while text:
  223. if text[0] in ('"', "'"):
  224. try:
  225. text = skipQuotes(text)
  226. except ValueError:
  227. return False
  228. text = text[1:]
  229. return True
  230. def child_exec_command(self, text):
  231. self.exec_command(text)
  232. def exec_command(self, text, no_echo=False):
  233. """
  234. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  235. Also handles execution in separated threads
  236. :param text: FlatCAM TclCommand with parameters
  237. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  238. will create crashes of the _Expandable_Edit widget
  239. :return: output if there was any
  240. """
  241. self._sysShell.report_usage('exec_command')
  242. return self.exec_command_test(text, False, no_echo=no_echo)
  243. def exec_command_test(self, text, reraise=True, no_echo=False):
  244. """
  245. Same as exec_command(...) with additional control over exceptions.
  246. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  247. :param text: Input command
  248. :param reraise: Re-raise TclError exceptions in Python (mostly for unittests).
  249. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  250. will create crashes of the _Expandable_Edit widget
  251. :return: Output from the command
  252. """
  253. tcl_command_string = str(text)
  254. try:
  255. if no_echo is False:
  256. self.open_processing() # Disables input box.
  257. result = self._sysShell.tcl.eval(str(tcl_command_string))
  258. if result != 'None' and no_echo is False:
  259. self.append_output(result + '\n')
  260. except tk.TclError as e:
  261. # This will display more precise answer if something in TCL shell fails
  262. result = self._sysShell.tcl.eval("set errorInfo")
  263. self._sysShell.log.error("Exec command Exception: %s" % (result + '\n'))
  264. if no_echo is False:
  265. self.append_error('ERROR: ' + result + '\n')
  266. # Show error in console and just return or in test raise exception
  267. if reraise:
  268. raise e
  269. finally:
  270. if no_echo is False:
  271. self.close_processing()
  272. pass
  273. return result
  274. # """
  275. # Code below is unsused. Saved for later.
  276. # """
  277. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  278. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  279. # self.log.debug(parts)
  280. # try:
  281. # if parts[0] not in commands:
  282. # self.shell.append_error("Unknown command\n")
  283. # return
  284. #
  285. # #import inspect
  286. # #inspect.getargspec(someMethod)
  287. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  288. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  289. # self.shell.append_error(
  290. # "Command %s takes %d arguments. %d given.\n" %
  291. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  292. # )
  293. # return
  294. #
  295. # cmdfcn = commands[parts[0]]["fcn"]
  296. # cmdconv = commands[parts[0]]["converters"]
  297. # if len(parts) - 1 > 0:
  298. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  299. # else:
  300. # retval = cmdfcn()
  301. # retfcn = commands[parts[0]]["retfcn"]
  302. # if retval and retfcn(retval):
  303. # self.shell.append_output(retfcn(retval) + "\n")
  304. #
  305. # except Exception as e:
  306. # #self.shell.append_error(''.join(traceback.format_exc()))
  307. # #self.shell.append_error("?\n")
  308. # self.shell.append_error(str(e) + "\n")