ToolShell.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 AppGUI.GUIElements import _BrowserTextEdit, _ExpandableTextEdit
  12. import html
  13. import sys
  14. import traceback
  15. import tkinter as tk
  16. import tclCommands
  17. import gettext
  18. import AppTranslation as fcTranslate
  19. import builtins
  20. fcTranslate.apply_language('strings')
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. class TermWidget(QWidget):
  24. """
  25. Widget which represents terminal. It only displays text and allows to enter text.
  26. All high level logic should be implemented by client classes
  27. User pressed Enter. Client class should decide, if command must be executed or user may continue edit it
  28. """
  29. def __init__(self, version, app, *args):
  30. QWidget.__init__(self, *args)
  31. self._browser = _BrowserTextEdit(version=version, app=app)
  32. self._browser.setStyleSheet("font: 9pt \"Courier\";")
  33. self._browser.setReadOnly(True)
  34. self._browser.document().setDefaultStyleSheet(
  35. self._browser.document().defaultStyleSheet() +
  36. "span {white-space:pre;}")
  37. self._edit = _ExpandableTextEdit(self, self)
  38. self._edit.historyNext.connect(self._on_history_next)
  39. self._edit.historyPrev.connect(self._on_history_prev)
  40. self._edit.setFocus()
  41. self.setFocusProxy(self._edit)
  42. layout = QVBoxLayout(self)
  43. layout.setSpacing(0)
  44. layout.setContentsMargins(0, 0, 0, 0)
  45. layout.addWidget(self._browser)
  46. layout.addWidget(self._edit)
  47. self._history = [''] # current empty line
  48. self._historyIndex = 0
  49. def open_processing(self, detail=None):
  50. """
  51. Open processing and disable using shell commands again until all commands are finished
  52. :param detail: text detail about what is currently called from TCL to python
  53. :return: None
  54. """
  55. self._edit.setTextColor(Qt.white)
  56. self._edit.setTextBackgroundColor(Qt.darkGreen)
  57. if detail is None:
  58. self._edit.setPlainText(_("...processing..."))
  59. else:
  60. self._edit.setPlainText('%s [%s]' % (_("...processing..."), detail))
  61. self._edit.setDisabled(True)
  62. self._edit.setFocus()
  63. def close_processing(self):
  64. """
  65. Close processing and enable using shell commands again
  66. :return:
  67. """
  68. self._edit.setTextColor(Qt.black)
  69. self._edit.setTextBackgroundColor(Qt.white)
  70. self._edit.setPlainText('')
  71. self._edit.setDisabled(False)
  72. self._edit.setFocus()
  73. def _append_to_browser(self, style, text):
  74. """
  75. Convert text to HTML for inserting it to browser
  76. """
  77. assert style in ('in', 'out', 'err', 'warning', 'success', 'selected', 'raw')
  78. if style != 'raw':
  79. text = html.escape(text)
  80. text = text.replace('\n', '<br/>')
  81. else:
  82. text = text.replace('\n', '<br>')
  83. text = text.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
  84. idx = text.find(']')
  85. mtype = text[:idx+1].upper()
  86. mtype = mtype.replace('_NOTCL', '')
  87. body = text[idx+1:]
  88. if style.lower() == 'in':
  89. text = '<span style="font-weight: bold;">%s</span>' % text
  90. elif style.lower() == 'err':
  91. text = '<span style="font-weight: bold; color: red;">%s</span>'\
  92. '<span style="font-weight: bold;">%s</span>'\
  93. % (mtype, body)
  94. elif style.lower() == 'warning':
  95. # text = '<span style="font-weight: bold; color: #f4b642;">%s</span>' % text
  96. text = '<span style="font-weight: bold; color: #f4b642;">%s</span>' \
  97. '<span style="font-weight: bold;">%s</span>' \
  98. % (mtype, body)
  99. elif style.lower() == 'success':
  100. # text = '<span style="font-weight: bold; color: #15b300;">%s</span>' % text
  101. text = '<span style="font-weight: bold; color: #15b300;">%s</span>' \
  102. '<span style="font-weight: bold;">%s</span>' \
  103. % (mtype, body)
  104. elif style.lower() == 'selected':
  105. text = ''
  106. elif style.lower() == 'raw':
  107. text = text
  108. else:
  109. # without span <br/> is ignored!!!
  110. text = '<span>%s</span>' % text
  111. scrollbar = self._browser.verticalScrollBar()
  112. old_value = scrollbar.value()
  113. # scrollattheend = old_value == scrollbar.maximum()
  114. self._browser.moveCursor(QTextCursor.End)
  115. self._browser.insertHtml(text)
  116. """TODO When user enters second line to the input, and input is resized, scrollbar changes its position
  117. and stops moving. As quick fix of this problem, now we always scroll down when add new text.
  118. To fix it correctly, scroll to the bottom, if before input has been resized,
  119. scrollbar was in the bottom, and remove next line
  120. """
  121. scrollattheend = True
  122. if scrollattheend:
  123. scrollbar.setValue(scrollbar.maximum())
  124. else:
  125. scrollbar.setValue(old_value)
  126. def exec_current_command(self):
  127. """
  128. Save current command in the history. Append it to the log. Clear edit line
  129. Re-implement in the child classes to actually execute command
  130. """
  131. text = str(self._edit.toPlainText())
  132. # in Windows replace all backslash symbols '\' with '\\' slash because Windows paths are made with backslash
  133. # and in Python single slash is the escape symbol
  134. if sys.platform == 'win32':
  135. text = text.replace('\\', '\\\\')
  136. self._append_to_browser('in', '> ' + text + '\n')
  137. if len(self._history) < 2 or self._history[-2] != text: # don't insert duplicating items
  138. try:
  139. if text[-1] == '\n':
  140. self._history.insert(-1, text[:-1])
  141. else:
  142. self._history.insert(-1, text)
  143. except IndexError:
  144. return
  145. self._historyIndex = len(self._history) - 1
  146. self._history[-1] = ''
  147. self._edit.clear()
  148. if not text[-1] == '\n':
  149. text += '\n'
  150. self.child_exec_command(text)
  151. def child_exec_command(self, text):
  152. """
  153. Re-implement in the child classes
  154. """
  155. pass
  156. def add_line_break_to_input(self):
  157. self._edit.textCursor().insertText('\n')
  158. def append_output(self, text):
  159. """
  160. Append text to output widget
  161. """
  162. self._append_to_browser('out', text)
  163. def append_raw(self, text):
  164. """
  165. Append text to output widget as it is
  166. """
  167. self._append_to_browser('raw', text)
  168. def append_success(self, text):
  169. """Append text to output widget
  170. """
  171. self._append_to_browser('success', text)
  172. def append_selected(self, text):
  173. """Append text to output widget
  174. """
  175. self._append_to_browser('selected', text)
  176. def append_warning(self, text):
  177. """Append text to output widget
  178. """
  179. self._append_to_browser('warning', text)
  180. def append_error(self, text):
  181. """Append error text to output widget. Text is drawn with red background
  182. """
  183. self._append_to_browser('err', text)
  184. def is_command_complete(self, text):
  185. """
  186. Executed by _ExpandableTextEdit. Re-implement this function in the child classes.
  187. """
  188. return True
  189. def browser(self):
  190. return self._browser
  191. def _on_history_next(self):
  192. """
  193. Down pressed, show next item from the history
  194. """
  195. if (self._historyIndex + 1) < len(self._history):
  196. self._historyIndex += 1
  197. self._edit.setPlainText(self._history[self._historyIndex])
  198. self._edit.moveCursor(QTextCursor.End)
  199. def _on_history_prev(self):
  200. """
  201. Up pressed, show previous item from the history
  202. """
  203. if self._historyIndex > 0:
  204. if self._historyIndex == (len(self._history) - 1):
  205. self._history[-1] = self._edit.toPlainText()
  206. self._historyIndex -= 1
  207. self._edit.setPlainText(self._history[self._historyIndex])
  208. self._edit.moveCursor(QTextCursor.End)
  209. class FCShell(TermWidget):
  210. def __init__(self, app, version, *args):
  211. """
  212. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  213. :param app: When instantiated the sysShell will be actually the FlatCAMApp.App() class
  214. :param version: FlatCAM version string
  215. :param args: Parameters passed to the TermWidget parent class
  216. """
  217. TermWidget.__init__(self, version, *args, app=app)
  218. self.app = app
  219. self.tcl_commands_storage = {}
  220. self.tcl = None
  221. self.init_tcl()
  222. self._edit.set_model_data(self.app.myKeywords)
  223. self.setWindowIcon(self.app.ui.app_icon)
  224. self.setWindowTitle("FlatCAM Shell")
  225. self.resize(*self.app.defaults["global_shell_shape"])
  226. self._append_to_browser('in', "FlatCAM %s - " % version)
  227. self.append_output('%s\n\n' % _("Type >help< to get started"))
  228. def init_tcl(self):
  229. if hasattr(self, 'tcl') and self.tcl is not None:
  230. # self.tcl = None
  231. # new object cannot be used here as it will not remember values created for next passes,
  232. # because tcl was executed in old instance of TCL
  233. pass
  234. else:
  235. self.tcl = tk.Tcl()
  236. self.setup_shell()
  237. def setup_shell(self):
  238. """
  239. Creates shell functions. Runs once at startup.
  240. :return: None
  241. """
  242. '''
  243. How to implement TCL shell commands:
  244. All parameters passed to command should be possible to set as None and test it afterwards.
  245. This is because we need to see error caused in tcl,
  246. if None value as default parameter is not allowed TCL will return empty error.
  247. Use:
  248. def mycommand(name=None,...):
  249. Test it like this:
  250. if name is None:
  251. self.raise_tcl_error('Argument name is missing.')
  252. When error occurred, always use raise_tcl_error, never return "some text" on error,
  253. otherwise we will miss it and processing will silently continue.
  254. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  255. which is caught in exec_command and displayed in TCL shell console with red background.
  256. Error in console is displayed with TCL trace.
  257. This behavior works only within main thread,
  258. errors with promissed tasks can be catched and detected only with log.
  259. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  260. TCL shell.
  261. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  262. '''
  263. # Import/overwrite tcl commands as objects of TclCommand descendants
  264. # This modifies the variable 'self.tcl_commands_storage'.
  265. tclCommands.register_all_commands(self.app, self.tcl_commands_storage)
  266. # Add commands to the tcl interpreter
  267. for cmd in self.tcl_commands_storage:
  268. self.tcl.createcommand(cmd, self.tcl_commands_storage[cmd]['fcn'])
  269. # Make the tcl puts function return instead of print to stdout
  270. self.tcl.eval('''
  271. rename puts original_puts
  272. proc puts {args} {
  273. if {[llength $args] == 1} {
  274. return "[lindex $args 0]"
  275. } else {
  276. eval original_puts $args
  277. }
  278. }
  279. ''')
  280. def is_command_complete(self, text):
  281. # def skipQuotes(txt):
  282. # quote = txt[0]
  283. # text_val = txt[1:]
  284. # endIndex = str(text_val).index(quote)
  285. # return text[endIndex:]
  286. # I'm disabling this because I need to be able to load paths that have spaces by
  287. # enclosing them in quotes --- Marius Stanciu
  288. # while text:
  289. # if text[0] in ('"', "'"):
  290. # try:
  291. # text = skipQuotes(text)
  292. # except ValueError:
  293. # return False
  294. # text = text[1:]
  295. return True
  296. def child_exec_command(self, text):
  297. self.exec_command(text)
  298. def exec_command(self, text, no_echo=False):
  299. """
  300. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  301. Also handles execution in separated threads
  302. :param text: FlatCAM TclCommand with parameters
  303. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  304. will create crashes of the _Expandable_Edit widget
  305. :return: output if there was any
  306. """
  307. self.app.defaults.report_usage('exec_command')
  308. return self.exec_command_test(text, False, no_echo=no_echo)
  309. def exec_command_test(self, text, reraise=True, no_echo=False):
  310. """
  311. Same as exec_command(...) with additional control over exceptions.
  312. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  313. :param text: Input command
  314. :param reraise: Re-raise TclError exceptions in Python (mostly for unittests).
  315. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  316. will create crashes of the _Expandable_Edit widget
  317. :return: Output from the command
  318. """
  319. tcl_command_string = str(text)
  320. try:
  321. if no_echo is False:
  322. self.open_processing() # Disables input box.
  323. result = self.tcl.eval(str(tcl_command_string))
  324. if result != 'None' and no_echo is False:
  325. self.append_output(result + '\n')
  326. except tk.TclError as e:
  327. # This will display more precise answer if something in TCL shell fails
  328. result = self.tcl.eval("set errorInfo")
  329. self.app.log.error("Exception on Tcl Command execution: %s" % (result + '\n'))
  330. if no_echo is False:
  331. self.append_error('ERROR Report: ' + result + '\n')
  332. # Show error in console and just return or in test raise exception
  333. if reraise:
  334. raise e
  335. finally:
  336. if no_echo is False:
  337. self.close_processing()
  338. pass
  339. return result
  340. def raise_tcl_unknown_error(self, unknownException):
  341. """
  342. Raise exception if is different type than TclErrorException
  343. this is here mainly to show unknown errors inside TCL shell console.
  344. :param unknownException:
  345. :return:
  346. """
  347. if not isinstance(unknownException, self.TclErrorException):
  348. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  349. else:
  350. raise unknownException
  351. def display_tcl_error(self, error, error_info=None):
  352. """
  353. Escape bracket [ with '\' otherwise there is error
  354. "ERROR: missing close-bracket" instead of real error
  355. :param error: it may be text or exception
  356. :param error_info: Some informations about the error
  357. :return: None
  358. """
  359. if isinstance(error, Exception):
  360. exc_type, exc_value, exc_traceback = error_info
  361. if not isinstance(error, self.TclErrorException):
  362. show_trace = 1
  363. else:
  364. show_trace = int(self.app.defaults['global_verbose_error_level'])
  365. if show_trace > 0:
  366. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  367. trc_formated = []
  368. for a in reversed(trc):
  369. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  370. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  371. else:
  372. text = "%s" % error
  373. else:
  374. text = error
  375. text = text.replace('[', '\\[').replace('"', '\\"')
  376. self.tcl.eval('return -code error "%s"' % text)
  377. def raise_tcl_error(self, text):
  378. """
  379. This method pass exception from python into TCL as error, so we get stacktrace and reason
  380. :param text: text of error
  381. :return: raise exception
  382. """
  383. self.display_tcl_error(text)
  384. raise self.TclErrorException(text)
  385. class TclErrorException(Exception):
  386. """
  387. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  388. """
  389. pass
  390. # """
  391. # Code below is unsused. Saved for later.
  392. # """
  393. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  394. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  395. # self.log.debug(parts)
  396. # try:
  397. # if parts[0] not in commands:
  398. # self.shell.append_error("Unknown command\n")
  399. # return
  400. #
  401. # #import inspect
  402. # #inspect.getargspec(someMethod)
  403. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  404. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  405. # self.shell.append_error(
  406. # "Command %s takes %d arguments. %d given.\n" %
  407. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  408. # )
  409. # return
  410. #
  411. # cmdfcn = commands[parts[0]]["fcn"]
  412. # cmdconv = commands[parts[0]]["converters"]
  413. # if len(parts) - 1 > 0:
  414. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  415. # else:
  416. # retval = cmdfcn()
  417. # retfcn = commands[parts[0]]["retfcn"]
  418. # if retval and retfcn(retval):
  419. # self.shell.append_output(retfcn(retval) + "\n")
  420. #
  421. # except Exception as e:
  422. # #self.shell.append_error(''.join(traceback.format_exc()))
  423. # #self.shell.append_error("?\n")
  424. # self.shell.append_error(str(e) + "\n")