TclCommand.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import sys
  2. import re
  3. import app_Main
  4. import abc
  5. import collections
  6. from PyQt5 import QtCore
  7. from contextlib import contextmanager
  8. class TclCommand(object):
  9. # FlatCAMApp
  10. app = None
  11. # Logger
  12. log = None
  13. # List of all command aliases, to be able use old names
  14. # for backward compatibility (add_poly, add_polygon)
  15. aliases = []
  16. # Dictionary of types from Tcl command, needs to be ordered
  17. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  18. arg_names = collections.OrderedDict([
  19. ('name', str)
  20. ])
  21. # dictionary of types from Tcl command, needs to be ordered.
  22. # This is for options like -optionname value.
  23. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  24. option_types = collections.OrderedDict()
  25. # List of mandatory options for current Tcl command: required = {'name','outname'}
  26. required = ['name']
  27. # Structured help for current command, args needs to be ordered
  28. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  29. help = {
  30. 'main': "undefined help.",
  31. 'args': collections.OrderedDict([
  32. ('argumentname', 'undefined help.'),
  33. ('optionname', 'undefined help.')
  34. ]),
  35. 'examples': []
  36. }
  37. # Original incoming arguments into command
  38. original_args = None
  39. def __init__(self, app):
  40. self.app = app
  41. if self.app is None:
  42. raise TypeError('Expected app to be FlatCAMApp instance.')
  43. if not isinstance(self.app, app_Main.App):
  44. raise TypeError('Expected FlatCAMApp, got %s.' % type(app))
  45. self.log = self.app.log
  46. self.error_info = None
  47. self.error = None
  48. def raise_tcl_error(self, text):
  49. """
  50. This method pass exception from python into TCL as error
  51. so we get stacktrace and reason.
  52. This is only redirect to self.app.raise_tcl_error
  53. :param text: text of error
  54. :return: none
  55. """
  56. self.app.shell.raise_tcl_error(text)
  57. def get_current_command(self):
  58. """
  59. Get current command, we are not able to get it from TCL we have to reconstruct it.
  60. :return: current command
  61. """
  62. command_string = [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. option_name = None
  136. for i in range(n):
  137. match = re.search(r'^-([a-zA-Z].*)', args[i])
  138. if match:
  139. # assert option_name is None
  140. if option_name is not None:
  141. options[option_name] = None
  142. option_name = match.group(1)
  143. continue
  144. if option_name is None:
  145. arguments.append(args[i])
  146. else:
  147. options[option_name] = args[i]
  148. option_name = None
  149. if option_name is not None:
  150. options[option_name] = None
  151. return arguments, options
  152. def check_args(self, args):
  153. """
  154. Check arguments and options for right types
  155. :param args: arguments from tcl to check
  156. :return: named_args, unnamed_args
  157. """
  158. arguments, options = self.parse_arguments(args)
  159. named_args = {}
  160. unnamed_args = []
  161. # check arguments
  162. idx = 0
  163. arg_names_items = list(self.arg_names.items())
  164. for argument in arguments:
  165. if len(self.arg_names) > idx:
  166. key, arg_type = arg_names_items[idx]
  167. try:
  168. named_args[key] = arg_type(argument)
  169. except Exception as e:
  170. self.raise_tcl_error("Cannot cast named argument '%s' to type %s with exception '%s'."
  171. % (key, arg_type, str(e)))
  172. else:
  173. unnamed_args.append(argument)
  174. idx += 1
  175. # check options
  176. for key in options:
  177. if key not in self.option_types and key != 'timeout':
  178. self.raise_tcl_error('Unknown parameter: %s' % key)
  179. try:
  180. if key != 'timeout':
  181. # None options are allowed; if None then the defaults are used
  182. # - must be implemented in the Tcl commands
  183. if options[key] is not None:
  184. named_args[key] = self.option_types[key](options[key])
  185. else:
  186. named_args[key] = options[key]
  187. else:
  188. named_args[key] = int(options[key])
  189. except Exception as e:
  190. self.raise_tcl_error("Cannot cast argument '-%s' to type '%s' with exception '%s'."
  191. % (key, self.option_types[key], str(e)))
  192. # check required arguments
  193. for key in self.required:
  194. if key not in named_args:
  195. self.raise_tcl_error("Missing required argument '%s'." % key)
  196. return named_args, unnamed_args
  197. def raise_tcl_unknown_error(self, unknown_exception):
  198. """
  199. raise Exception if is different type than TclErrorException
  200. this is here mainly to show unknown errors inside TCL shell console
  201. :param unknown_exception:
  202. :return:
  203. """
  204. raise unknown_exception
  205. def raise_tcl_error(self, text):
  206. """
  207. this method pass exception from python into TCL as error, so we get stacktrace and reason
  208. :param text: text of error
  209. :return: raise exception
  210. """
  211. # because of signaling we cannot call error to TCL from here but when task
  212. # is finished also non-signaled are handled here to better exception
  213. # handling and displayed after command is finished
  214. raise self.app.shell.TclErrorException(text)
  215. def execute_wrapper(self, *args):
  216. """
  217. Command which is called by tcl console when current commands aliases are hit.
  218. Main catch(except) is implemented here.
  219. This method should be reimplemented only when initial checking sequence differs
  220. :param args: arguments passed from tcl command console
  221. :return: None, output text or exception
  222. """
  223. # self.worker_task.emit({'fcn': self.exec_command_test, 'params': [text, False]})
  224. try:
  225. self.log.debug("TCL command '%s' executed." % str(type(self).__name__))
  226. self.original_args = args
  227. args, unnamed_args = self.check_args(args)
  228. return self.execute(args, unnamed_args)
  229. except Exception as unknown:
  230. error_info = sys.exc_info()
  231. self.log.error("TCL command '%s' failed. Error text: %s" % (str(self), str(unknown)))
  232. self.app.shell.display_tcl_error(unknown, error_info)
  233. self.raise_tcl_unknown_error(unknown)
  234. @abc.abstractmethod
  235. def execute(self, args, unnamed_args):
  236. """
  237. Direct execute of command, this method should be implemented in each descendant.
  238. No main catch should be implemented here.
  239. :param args: array of known named arguments and options
  240. :param unnamed_args: array of other values which were passed into command
  241. without -somename and we do not have them in known arg_names
  242. :return: None, output text or exception
  243. """
  244. raise NotImplementedError("Please Implement this method")
  245. class TclCommandSignaled(TclCommand):
  246. """
  247. !!! I left it here only for demonstration !!!
  248. Go to TclCommandCncjob and into class definition put
  249. class TclCommandCncjob(TclCommandSignaled):
  250. also change
  251. obj.generatecncjob(use_thread = False, **args)
  252. to
  253. obj.generatecncjob(use_thread = True, **args)
  254. This class is child of TclCommand and is used for commands which create new objects
  255. it handles all necessary stuff about blocking and passing exceptions
  256. """
  257. @abc.abstractmethod
  258. def execute(self, args, unnamed_args):
  259. raise NotImplementedError("Please Implement this method")
  260. output = None
  261. def execute_call(self, args, unnamed_args):
  262. try:
  263. self.output = None
  264. self.error = None
  265. self.error_info = None
  266. self.output = self.execute(args, unnamed_args)
  267. except Exception as unknown:
  268. self.error_info = sys.exc_info()
  269. self.error = unknown
  270. finally:
  271. self.app.shell_command_finished.emit(self)
  272. def execute_wrapper(self, *args):
  273. """
  274. Command which is called by tcl console when current commands aliases are hit.
  275. Main catch(except) is implemented here.
  276. This method should be reimplemented only when initial checking sequence differs
  277. :param args: arguments passed from tcl command console
  278. :return: None, output text or exception
  279. """
  280. @contextmanager
  281. def wait_signal(signal, timeout=300000):
  282. """Block loop until signal emitted, or timeout (ms) elapses."""
  283. loop = QtCore.QEventLoop()
  284. # Normal termination
  285. signal.connect(loop.quit)
  286. # Termination by exception in thread
  287. self.app.thread_exception.connect(loop.quit)
  288. status = {'timed_out': False}
  289. def report_quit():
  290. status['timed_out'] = True
  291. loop.quit()
  292. yield
  293. # Temporarily change how exceptions are managed.
  294. oeh = sys.excepthook
  295. ex = []
  296. def except_hook(type_, value, traceback_):
  297. ex.append(value)
  298. oeh(type_, value, traceback_)
  299. sys.excepthook = except_hook
  300. # Terminate on timeout
  301. if timeout is not None:
  302. time_val = int(timeout)
  303. QtCore.QTimer.singleShot(time_val, report_quit)
  304. # Block
  305. loop.exec_()
  306. # Restore exception management
  307. sys.excepthook = oeh
  308. if ex:
  309. raise ex[0]
  310. if status['timed_out']:
  311. self.app.shell.raise_tcl_unknown_error("Operation timed outed! Consider increasing option "
  312. "'-timeout <miliseconds>' for command or "
  313. "'set_sys global_background_timeout <miliseconds>'.")
  314. try:
  315. self.log.debug("TCL command '%s' executed." % str(type(self).__name__))
  316. self.original_args = args
  317. args, unnamed_args = self.check_args(args)
  318. if 'timeout' in args:
  319. passed_timeout = args['timeout']
  320. del args['timeout']
  321. else:
  322. passed_timeout = self.app.defaults['global_background_timeout']
  323. # set detail for processing, it will be there until next open or close
  324. self.app.shell.open_processing(self.get_current_command())
  325. def handle_finished():
  326. self.app.shell_command_finished.disconnect(handle_finished)
  327. if self.error is not None:
  328. self.raise_tcl_unknown_error(self.error)
  329. self.app.shell_command_finished.connect(handle_finished)
  330. with wait_signal(self.app.shell_command_finished, passed_timeout):
  331. # every TclCommandNewObject ancestor support timeout as parameter,
  332. # but it does not mean anything for child itself
  333. # when operation will be really long is good to set it higher then defqault 30s
  334. self.app.worker_task.emit({'fcn': self.execute_call, 'params': [args, unnamed_args]})
  335. return self.output
  336. except Exception as unknown:
  337. # if error happens inside thread execution, then pass correct error_info to display
  338. if self.error_info is not None:
  339. error_info = self.error_info
  340. else:
  341. error_info = sys.exc_info()
  342. self.log.error("TCL command '%s' failed." % str(self))
  343. self.app.shell.display_tcl_error(unknown, error_info)
  344. self.raise_tcl_unknown_error(unknown)