TclCommand.py 14 KB

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