ToolShell.py 19 KB

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