TclCommand.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import sys
  2. import re
  3. import FlatCAMApp
  4. import abc
  5. import collections
  6. from PyQt5 import QtCore, QtGui
  7. from PyQt5.QtCore import Qt
  8. from contextlib import contextmanager
  9. class TclCommand(object):
  10. # FlatCAMApp
  11. app = None
  12. # Logger
  13. log = None
  14. # List of all command aliases, to be able use old names
  15. # for backward compatibility (add_poly, add_polygon)
  16. aliases = []
  17. # Dictionary of types from Tcl command, needs to be ordered
  18. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  19. arg_names = collections.OrderedDict([
  20. ('name', str)
  21. ])
  22. # dictionary of types from Tcl command, needs to be ordered.
  23. # This is for options like -optionname value.
  24. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  25. option_types = collections.OrderedDict()
  26. # List of mandatory options for current Tcl command: required = {'name','outname'}
  27. required = ['name']
  28. # Structured help for current command, args needs to be ordered
  29. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  30. help = {
  31. 'main': "undefined help.",
  32. 'args': collections.OrderedDict([
  33. ('argumentname', 'undefined help.'),
  34. ('optionname', 'undefined help.')
  35. ]),
  36. 'examples': []
  37. }
  38. # Original incoming arguments into command
  39. original_args = None
  40. def __init__(self, app):
  41. self.app = app
  42. if self.app is None:
  43. raise TypeError('Expected app to be FlatCAMApp instance.')
  44. if not isinstance(self.app, FlatCAMApp.App):
  45. raise TypeError('Expected FlatCAMApp, got %s.' % type(app))
  46. self.log = self.app.log
  47. def raise_tcl_error(self, text):
  48. """
  49. This method pass exception from python into TCL as error
  50. so we get stacktrace and reason.
  51. This is only redirect to self.app.raise_tcl_error
  52. :param text: text of error
  53. :return: none
  54. """
  55. self.app.raise_tcl_error(text)
  56. def get_current_command(self):
  57. """
  58. Get current command, we are not able to get it from TCL we have to reconstruct it.
  59. :return: current command
  60. """
  61. command_string = list()
  62. command_string.append(self.aliases[0])
  63. if self.original_args is not None:
  64. for arg in self.original_args:
  65. command_string.append(arg)
  66. return " ".join(command_string)
  67. def get_decorated_help(self):
  68. """
  69. Decorate help for TCL console output.
  70. :return: decorated help from structure
  71. """
  72. def get_decorated_command(alias_name):
  73. command_string = []
  74. for arg_key, arg_type in list(self.help['args'].items()):
  75. command_string.append(get_decorated_argument(arg_key, arg_type, True))
  76. return "> " + alias_name + " " + " ".join(command_string)
  77. def get_decorated_argument(help_key, help_text, in_command=False):
  78. """
  79. :param help_key: Name of the argument.
  80. :param help_text:
  81. :param in_command:
  82. :return:
  83. """
  84. option_symbol = ''
  85. if help_key in self.arg_names:
  86. arg_type = self.arg_names[help_key]
  87. type_name = str(arg_type.__name__)
  88. # in_command_name = help_key + "<" + type_name + ">"
  89. in_command_name = help_key
  90. elif help_key in self.option_types:
  91. option_symbol = '-'
  92. arg_type = self.option_types[help_key]
  93. type_name = str(arg_type.__name__)
  94. in_command_name = option_symbol + help_key + " <" + type_name + ">"
  95. else:
  96. option_symbol = ''
  97. type_name = '?'
  98. in_command_name = option_symbol + help_key + " <" + type_name + ">"
  99. if in_command:
  100. if help_key in self.required:
  101. return in_command_name
  102. else:
  103. return '[' + in_command_name + "]"
  104. else:
  105. if help_key in self.required:
  106. return "\t" + option_symbol + help_key + " <" + type_name + ">: " + help_text
  107. else:
  108. return "\t[" + option_symbol + help_key + " <" + type_name + ">: " + help_text + "]"
  109. def get_decorated_example(example_item):
  110. return "> " + example_item
  111. help_string = [self.help['main']]
  112. for alias in self.aliases:
  113. help_string.append(get_decorated_command(alias))
  114. for key, value in list(self.help['args'].items()):
  115. help_string.append(get_decorated_argument(key, value))
  116. # timeout is unique for signaled commands (this is not best oop practice, but much easier for now)
  117. if isinstance(self, TclCommandSignaled):
  118. help_string.append("\t[-timeout <int>: Max wait for job timeout before error.]")
  119. for example in self.help['examples']:
  120. help_string.append(get_decorated_example(example))
  121. return "\n".join(help_string)
  122. @staticmethod
  123. def parse_arguments(args):
  124. """
  125. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  126. and standalone parameters into list.
  127. This is copy from FlatCAMApp.setup_shell().h() just for accessibility,
  128. original should be removed after all commands will be converted
  129. :param args: arguments from tcl to parse
  130. :return: arguments, options
  131. """
  132. options = {}
  133. arguments = []
  134. n = len(args)
  135. name = None
  136. for i in range(n):
  137. match = re.search(r'^-([a-zA-Z].*)', args[i])
  138. if match:
  139. assert name is None
  140. name = match.group(1)
  141. continue
  142. if name is None:
  143. arguments.append(args[i])
  144. else:
  145. options[name] = args[i]
  146. name = None
  147. return arguments, options
  148. def check_args(self, args):
  149. """
  150. Check arguments and options for right types
  151. :param args: arguments from tcl to check
  152. :return: named_args, unnamed_args
  153. """
  154. arguments, options = self.parse_arguments(args)
  155. named_args = {}
  156. unnamed_args = []
  157. # check arguments
  158. idx = 0
  159. arg_names_items = list(self.arg_names.items())
  160. for argument in arguments:
  161. if len(self.arg_names) > idx:
  162. key, arg_type = arg_names_items[idx]
  163. try:
  164. named_args[key] = arg_type(argument)
  165. except Exception as e:
  166. self.raise_tcl_error("Cannot cast named argument '%s' to type %s with exception '%s'."
  167. % (key, arg_type, str(e)))
  168. else:
  169. unnamed_args.append(argument)
  170. idx += 1
  171. # check options
  172. for key in options:
  173. if key not in self.option_types and key != 'timeout':
  174. self.raise_tcl_error('Unknown parameter: %s' % key)
  175. try:
  176. if key != 'timeout':
  177. named_args[key] = self.option_types[key](options[key])
  178. else:
  179. named_args[key] = int(options[key])
  180. except Exception as e:
  181. self.raise_tcl_error("Cannot cast argument '-%s' to type '%s' with exception '%s'."
  182. % (key, self.option_types[key], str(e)))
  183. # check required arguments
  184. for key in self.required:
  185. if key not in named_args:
  186. self.raise_tcl_error("Missing required argument '%s'." % key)
  187. return named_args, unnamed_args
  188. def raise_tcl_unknown_error(self, unknown_exception):
  189. """
  190. raise Exception if is different type than TclErrorException
  191. this is here mainly to show unknown errors inside TCL shell console
  192. :param unknown_exception:
  193. :return:
  194. """
  195. raise unknown_exception
  196. def raise_tcl_error(self, text):
  197. """
  198. this method pass exception from python into TCL as error, so we get stacktrace and reason
  199. :param text: text of error
  200. :return: raise exception
  201. """
  202. # becouse of signaling we cannot call error to TCL from here but when task
  203. # is finished also nonsignaled are handled here to better exception
  204. # handling and displayed after command is finished
  205. raise self.app.TclErrorException(text)
  206. def execute_wrapper(self, *args):
  207. """
  208. Command which is called by tcl console when current commands aliases are hit.
  209. Main catch(except) is implemented here.
  210. This method should be reimplemented only when initial checking sequence differs
  211. :param args: arguments passed from tcl command console
  212. :return: None, output text or exception
  213. """
  214. # self.worker_task.emit({'fcn': self.exec_command_test, 'params': [text, False]})
  215. try:
  216. self.log.debug("TCL command '%s' executed." % str(self.__class__))
  217. self.original_args = args
  218. args, unnamed_args = self.check_args(args)
  219. return self.execute(args, unnamed_args)
  220. except Exception as unknown:
  221. error_info = sys.exc_info()
  222. self.log.error("TCL command '%s' failed. Error text: %s" % (str(self), str(unknown)))
  223. self.app.display_tcl_error(unknown, error_info)
  224. self.raise_tcl_unknown_error(unknown)
  225. @abc.abstractmethod
  226. def execute(self, args, unnamed_args):
  227. """
  228. Direct execute of command, this method should be implemented in each descendant.
  229. No main catch should be implemented here.
  230. :param args: array of known named arguments and options
  231. :param unnamed_args: array of other values which were passed into command
  232. without -somename and we do not have them in known arg_names
  233. :return: None, output text or exception
  234. """
  235. raise NotImplementedError("Please Implement this method")
  236. class TclCommandSignaled(TclCommand):
  237. """
  238. !!! I left it here only for demonstration !!!
  239. Go to TclCommandCncjob and into class definition put
  240. class TclCommandCncjob(TclCommandSignaled):
  241. also change
  242. obj.generatecncjob(use_thread = False, **args)
  243. to
  244. obj.generatecncjob(use_thread = True, **args)
  245. This class is child of TclCommand and is used for commands which create new objects
  246. it handles all necessary stuff about blocking and passing exceptions
  247. """
  248. @abc.abstractmethod
  249. def execute(self, args, unnamed_args):
  250. raise NotImplementedError("Please Implement this method")
  251. output = None
  252. def execute_call(self, args, unnamed_args):
  253. try:
  254. self.output = None
  255. self.error = None
  256. self.error_info = None
  257. self.output = self.execute(args, unnamed_args)
  258. except Exception as unknown:
  259. self.error_info = sys.exc_info()
  260. self.error = unknown
  261. finally:
  262. self.app.shell_command_finished.emit(self)
  263. def execute_wrapper(self, *args):
  264. """
  265. Command which is called by tcl console when current commands aliases are hit.
  266. Main catch(except) is implemented here.
  267. This method should be reimplemented only when initial checking sequence differs
  268. :param args: arguments passed from tcl command console
  269. :return: None, output text or exception
  270. """
  271. @contextmanager
  272. def wait_signal(signal, timeout=300000):
  273. """Block loop until signal emitted, or timeout (ms) elapses."""
  274. loop = QtCore.QEventLoop()
  275. # Normal termination
  276. signal.connect(loop.quit)
  277. # Termination by exception in thread
  278. self.app.thread_exception.connect(loop.quit)
  279. status = {'timed_out': False}
  280. def report_quit():
  281. status['timed_out'] = True
  282. loop.quit()
  283. yield
  284. # Temporarily change how exceptions are managed.
  285. oeh = sys.excepthook
  286. ex = []
  287. def except_hook(type_, value, traceback_):
  288. ex.append(value)
  289. oeh(type_, value, traceback_)
  290. sys.excepthook = except_hook
  291. # Terminate on timeout
  292. if timeout is not None:
  293. QtCore.QTimer.singleShot(timeout, report_quit)
  294. # Block
  295. loop.exec_()
  296. # Restore exception management
  297. sys.excepthook = oeh
  298. if ex:
  299. raise ex[0]
  300. if status['timed_out']:
  301. self.app.raise_tcl_unknown_error("Operation timed outed! Consider increasing option "
  302. "'-timeout <miliseconds>' for command or "
  303. "'set_sys global_background_timeout <miliseconds>'.")
  304. try:
  305. self.log.debug("TCL command '%s' executed." % str(self.__class__))
  306. self.original_args = args
  307. args, unnamed_args = self.check_args(args)
  308. if 'timeout' in args:
  309. passed_timeout = args['timeout']
  310. del args['timeout']
  311. else:
  312. passed_timeout = self.app.defaults['global_background_timeout']
  313. # set detail for processing, it will be there until next open or close
  314. self.app.shell.open_proccessing(self.get_current_command())
  315. def handle_finished(obj):
  316. self.app.shell_command_finished.disconnect(handle_finished)
  317. if self.error is not None:
  318. self.raise_tcl_unknown_error(self.error)
  319. self.app.shell_command_finished.connect(handle_finished)
  320. with wait_signal(self.app.shell_command_finished, passed_timeout):
  321. # every TclCommandNewObject ancestor support timeout as parameter,
  322. # but it does not mean anything for child itself
  323. # when operation will be really long is good to set it higher then defqault 30s
  324. self.app.worker_task.emit({'fcn': self.execute_call, 'params': [args, unnamed_args]})
  325. return self.output
  326. except Exception as unknown:
  327. # if error happens inside thread execution, then pass correct error_info to display
  328. if self.error_info is not None:
  329. error_info = self.error_info
  330. else:
  331. error_info = sys.exc_info()
  332. self.log.error("TCL command '%s' failed." % str(self))
  333. self.app.display_tcl_error(unknown, error_info)
  334. self.raise_tcl_unknown_error(unknown)