ToolShell.py 19 KB

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