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 AppGUI 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.init_tcl()
  221. self._edit.set_model_data(self.app.myKeywords)
  222. self.setWindowIcon(self.app.ui.app_icon)
  223. self.setWindowTitle("FlatCAM Shell")
  224. self.resize(*self.app.defaults["global_shell_shape"])
  225. self._append_to_browser('in', "FlatCAM %s - " % version)
  226. self.append_output('%s\n\n' % _("Type >help< to get started"))
  227. def init_tcl(self):
  228. if hasattr(self, 'tcl') and self.tcl is not None:
  229. # self.tcl = None
  230. # new object cannot be used here as it will not remember values created for next passes,
  231. # because tcl was executed in old instance of TCL
  232. pass
  233. else:
  234. self.tcl = tk.Tcl()
  235. self.setup_shell()
  236. def setup_shell(self):
  237. """
  238. Creates shell functions. Runs once at startup.
  239. :return: None
  240. """
  241. '''
  242. How to implement TCL shell commands:
  243. All parameters passed to command should be possible to set as None and test it afterwards.
  244. This is because we need to see error caused in tcl,
  245. if None value as default parameter is not allowed TCL will return empty error.
  246. Use:
  247. def mycommand(name=None,...):
  248. Test it like this:
  249. if name is None:
  250. self.raise_tcl_error('Argument name is missing.')
  251. When error occurred, always use raise_tcl_error, never return "some text" on error,
  252. otherwise we will miss it and processing will silently continue.
  253. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  254. which is caught in exec_command and displayed in TCL shell console with red background.
  255. Error in console is displayed with TCL trace.
  256. This behavior works only within main thread,
  257. errors with promissed tasks can be catched and detected only with log.
  258. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  259. TCL shell.
  260. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  261. '''
  262. # Import/overwrite tcl commands as objects of TclCommand descendants
  263. # This modifies the variable 'self.tcl_commands_storage'.
  264. tclCommands.register_all_commands(self.app, self.tcl_commands_storage)
  265. # Add commands to the tcl interpreter
  266. for cmd in self.tcl_commands_storage:
  267. self.tcl.createcommand(cmd, self.tcl_commands_storage[cmd]['fcn'])
  268. # Make the tcl puts function return instead of print to stdout
  269. self.tcl.eval('''
  270. rename puts original_puts
  271. proc puts {args} {
  272. if {[llength $args] == 1} {
  273. return "[lindex $args 0]"
  274. } else {
  275. eval original_puts $args
  276. }
  277. }
  278. ''')
  279. def is_command_complete(self, text):
  280. def skipQuotes(txt):
  281. quote = txt[0]
  282. text_val = txt[1:]
  283. endIndex = str(text_val).index(quote)
  284. return text[endIndex:]
  285. # I'm disabling this because I need to be able to load paths that have spaces by
  286. # enclosing them in quotes --- Marius Stanciu
  287. # while text:
  288. # if text[0] in ('"', "'"):
  289. # try:
  290. # text = skipQuotes(text)
  291. # except ValueError:
  292. # return False
  293. # text = text[1:]
  294. return True
  295. def child_exec_command(self, text):
  296. self.exec_command(text)
  297. def exec_command(self, text, no_echo=False):
  298. """
  299. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  300. Also handles execution in separated threads
  301. :param text: FlatCAM TclCommand with parameters
  302. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  303. will create crashes of the _Expandable_Edit widget
  304. :return: output if there was any
  305. """
  306. self.app.defaults.report_usage('exec_command')
  307. return self.exec_command_test(text, False, no_echo=no_echo)
  308. def exec_command_test(self, text, reraise=True, no_echo=False):
  309. """
  310. Same as exec_command(...) with additional control over exceptions.
  311. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  312. :param text: Input command
  313. :param reraise: Re-raise TclError exceptions in Python (mostly for unittests).
  314. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  315. will create crashes of the _Expandable_Edit widget
  316. :return: Output from the command
  317. """
  318. tcl_command_string = str(text)
  319. try:
  320. if no_echo is False:
  321. self.open_processing() # Disables input box.
  322. result = self.tcl.eval(str(tcl_command_string))
  323. if result != 'None' and no_echo is False:
  324. self.append_output(result + '\n')
  325. except tk.TclError as e:
  326. # This will display more precise answer if something in TCL shell fails
  327. result = self.tcl.eval("set errorInfo")
  328. self.app.log.error("Exec command Exception: %s" % (result + '\n'))
  329. if no_echo is False:
  330. self.append_error('ERROR: ' + result + '\n')
  331. # Show error in console and just return or in test raise exception
  332. if reraise:
  333. raise e
  334. finally:
  335. if no_echo is False:
  336. self.close_processing()
  337. pass
  338. return result
  339. def raise_tcl_unknown_error(self, unknownException):
  340. """
  341. Raise exception if is different type than TclErrorException
  342. this is here mainly to show unknown errors inside TCL shell console.
  343. :param unknownException:
  344. :return:
  345. """
  346. if not isinstance(unknownException, self.TclErrorException):
  347. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  348. else:
  349. raise unknownException
  350. def display_tcl_error(self, error, error_info=None):
  351. """
  352. Escape bracket [ with '\' otherwise there is error
  353. "ERROR: missing close-bracket" instead of real error
  354. :param error: it may be text or exception
  355. :param error_info: Some informations about the error
  356. :return: None
  357. """
  358. if isinstance(error, Exception):
  359. exc_type, exc_value, exc_traceback = error_info
  360. if not isinstance(error, self.TclErrorException):
  361. show_trace = 1
  362. else:
  363. show_trace = int(self.app.defaults['global_verbose_error_level'])
  364. if show_trace > 0:
  365. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  366. trc_formated = []
  367. for a in reversed(trc):
  368. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  369. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  370. else:
  371. text = "%s" % error
  372. else:
  373. text = error
  374. text = text.replace('[', '\\[').replace('"', '\\"')
  375. self.tcl.eval('return -code error "%s"' % text)
  376. def raise_tcl_error(self, text):
  377. """
  378. This method pass exception from python into TCL as error, so we get stacktrace and reason
  379. :param text: text of error
  380. :return: raise exception
  381. """
  382. self.display_tcl_error(text)
  383. raise self.TclErrorException(text)
  384. class TclErrorException(Exception):
  385. """
  386. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  387. """
  388. pass
  389. # """
  390. # Code below is unsused. Saved for later.
  391. # """
  392. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  393. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  394. # self.log.debug(parts)
  395. # try:
  396. # if parts[0] not in commands:
  397. # self.shell.append_error("Unknown command\n")
  398. # return
  399. #
  400. # #import inspect
  401. # #inspect.getargspec(someMethod)
  402. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  403. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  404. # self.shell.append_error(
  405. # "Command %s takes %d arguments. %d given.\n" %
  406. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  407. # )
  408. # return
  409. #
  410. # cmdfcn = commands[parts[0]]["fcn"]
  411. # cmdconv = commands[parts[0]]["converters"]
  412. # if len(parts) - 1 > 0:
  413. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  414. # else:
  415. # retval = cmdfcn()
  416. # retfcn = commands[parts[0]]["retfcn"]
  417. # if retval and retfcn(retval):
  418. # self.shell.append_output(retfcn(retval) + "\n")
  419. #
  420. # except Exception as e:
  421. # #self.shell.append_error(''.join(traceback.format_exc()))
  422. # #self.shell.append_error("?\n")
  423. # self.shell.append_error(str(e) + "\n")