TclCommand.py 15 KB

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