ToolShell.py 19 KB

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