TclCommand.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. # array of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon)
  14. aliases = []
  15. # dictionary of types from Tcl command, needs to be ordered
  16. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  17. arg_names = collections.OrderedDict([
  18. ('name', str)
  19. ])
  20. # dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value
  21. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  22. option_types = collections.OrderedDict()
  23. # array of mandatory options for current Tcl command: required = {'name','outname'}
  24. required = ['name']
  25. # structured help for current command, args needs to be ordered
  26. # OrderedDict should be like collections.OrderedDict([(key,value),(key2,value2)])
  27. help = {
  28. 'main': "undefined help.",
  29. 'args': collections.OrderedDict([
  30. ('argumentname', 'undefined help.'),
  31. ('optionname', 'undefined help.')
  32. ]),
  33. 'examples': []
  34. }
  35. # original incoming arguments into command
  36. original_args = None
  37. def __init__(self, app):
  38. self.app = app
  39. if self.app is None:
  40. raise TypeError('Expected app to be FlatCAMApp instance.')
  41. if not isinstance(self.app, FlatCAMApp.App):
  42. raise TypeError('Expected FlatCAMApp, got %s.' % type(app))
  43. self.log = self.app.log
  44. def raise_tcl_error(self, text):
  45. """
  46. this method pass exception from python into TCL as error, so we get stacktrace and reason
  47. this is only redirect to self.app.raise_tcl_error
  48. :param text: text of error
  49. :return: none
  50. """
  51. self.app.raise_tcl_error(text)
  52. def get_current_command(self):
  53. """
  54. get current command, we are not able to get it from TCL we have to reconstruct it
  55. :return: current command
  56. """
  57. command_string = []
  58. command_string.append(self.aliases[0])
  59. if self.original_args is not None:
  60. for arg in self.original_args:
  61. command_string.append(arg)
  62. return " ".join(command_string)
  63. def get_decorated_help(self):
  64. """
  65. Decorate help for TCL console output.
  66. :return: decorated help from structure
  67. """
  68. def get_decorated_command(alias_name):
  69. command_string = []
  70. for arg_key, arg_type in self.help['args'].items():
  71. command_string.append(get_decorated_argument(arg_key, arg_type, True))
  72. return "> " + alias_name + " " + " ".join(command_string)
  73. def get_decorated_argument(help_key, help_text, in_command=False):
  74. option_symbol = ''
  75. if help_key in self.arg_names:
  76. arg_type = self.arg_names[help_key]
  77. type_name = str(arg_type.__name__)
  78. in_command_name = "<" + type_name + ">"
  79. elif help_key in self.option_types:
  80. option_symbol = '-'
  81. arg_type = self.option_types[help_key]
  82. type_name = str(arg_type.__name__)
  83. in_command_name = option_symbol + help_key + " <" + type_name + ">"
  84. else:
  85. option_symbol = ''
  86. type_name = '?'
  87. in_command_name = option_symbol + help_key + " <" + type_name + ">"
  88. if in_command:
  89. if help_key in self.required:
  90. return in_command_name
  91. else:
  92. return '[' + in_command_name + "]"
  93. else:
  94. if help_key in self.required:
  95. return "\t" + option_symbol + help_key + " <" + type_name + ">: " + help_text
  96. else:
  97. return "\t[" + option_symbol + help_key + " <" + type_name + ">: " + help_text + "]"
  98. def get_decorated_example(example_item):
  99. return "> "+example_item
  100. help_string = [self.help['main']]
  101. for alias in self.aliases:
  102. help_string.append(get_decorated_command(alias))
  103. for key, value in self.help['args'].items():
  104. help_string.append(get_decorated_argument(key, value))
  105. # timeout is unique for signaled commands (this is not best oop practice, but much easier for now)
  106. if isinstance(self, TclCommandSignaled):
  107. help_string.append("\t[-timeout <int>: Max wait for job timeout before error.]")
  108. for example in self.help['examples']:
  109. help_string.append(get_decorated_example(example))
  110. return "\n".join(help_string)
  111. @staticmethod
  112. def parse_arguments(args):
  113. """
  114. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  115. and standalone parameters into list.
  116. This is copy from FlatCAMApp.setup_shell().h() just for accessibility,
  117. original should be removed after all commands will be converted
  118. :param args: arguments from tcl to parse
  119. :return: arguments, options
  120. """
  121. options = {}
  122. arguments = []
  123. n = len(args)
  124. name = None
  125. for i in range(n):
  126. match = re.search(r'^-([a-zA-Z].*)', args[i])
  127. if match:
  128. assert name is None
  129. name = match.group(1)
  130. continue
  131. if name is None:
  132. arguments.append(args[i])
  133. else:
  134. options[name] = args[i]
  135. name = None
  136. return arguments, options
  137. def check_args(self, args):
  138. """
  139. Check arguments and options for right types
  140. :param args: arguments from tcl to check
  141. :return: named_args, unnamed_args
  142. """
  143. arguments, options = self.parse_arguments(args)
  144. named_args = {}
  145. unnamed_args = []
  146. # check arguments
  147. idx = 0
  148. arg_names_items = self.arg_names.items()
  149. for argument in arguments:
  150. if len(self.arg_names) > idx:
  151. key, arg_type = arg_names_items[idx]
  152. try:
  153. named_args[key] = arg_type(argument)
  154. except Exception, e:
  155. self.raise_tcl_error("Cannot cast named argument '%s' to type %s with exception '%s'."
  156. % (key, arg_type, str(e)))
  157. else:
  158. unnamed_args.append(argument)
  159. idx += 1
  160. # check options
  161. for key in options:
  162. if key not in self.option_types and key != 'timeout':
  163. self.raise_tcl_error('Unknown parameter: %s' % key)
  164. try:
  165. if key != 'timeout':
  166. named_args[key] = self.option_types[key](options[key])
  167. else:
  168. named_args[key] = int(options[key])
  169. except Exception, e:
  170. self.raise_tcl_error("Cannot cast argument '-%s' to type '%s' with exception '%s'."
  171. % (key, self.option_types[key], str(e)))
  172. # check required arguments
  173. for key in self.required:
  174. if key not in named_args:
  175. self.raise_tcl_error("Missing required argument '%s'." % key)
  176. return named_args, unnamed_args
  177. def raise_tcl_unknown_error(self, unknownException):
  178. """
  179. raise Exception if is different type than TclErrorException
  180. this is here mainly to show unknown errors inside TCL shell console
  181. :param unknownException:
  182. :return:
  183. """
  184. #if not isinstance(unknownException, self.TclErrorException):
  185. # self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  186. #else:
  187. raise unknownException
  188. def raise_tcl_error(self, text):
  189. """
  190. this method pass exception from python into TCL as error, so we get stacktrace and reason
  191. :param text: text of error
  192. :return: raise exception
  193. """
  194. # becouse of signaling we cannot call error to TCL from here but when task is finished
  195. # also nonsiglaned arwe handled here to better exception handling and diplay after command is finished
  196. raise self.app.TclErrorException(text)
  197. def execute_wrapper(self, *args):
  198. """
  199. Command which is called by tcl console when current commands aliases are hit.
  200. Main catch(except) is implemented here.
  201. This method should be reimplemented only when initial checking sequence differs
  202. :param args: arguments passed from tcl command console
  203. :return: None, output text or exception
  204. """
  205. #self.worker_task.emit({'fcn': self.exec_command_test, 'params': [text, False]})
  206. try:
  207. self.log.debug("TCL command '%s' executed." % str(self.__class__))
  208. self.original_args=args
  209. args, unnamed_args = self.check_args(args)
  210. return self.execute(args, unnamed_args)
  211. except Exception as unknown:
  212. error_info=sys.exc_info()
  213. self.log.error("TCL command '%s' failed." % str(self))
  214. self.app.display_tcl_error(unknown, error_info)
  215. self.raise_tcl_unknown_error(unknown)
  216. @abc.abstractmethod
  217. def execute(self, args, unnamed_args):
  218. """
  219. Direct execute of command, this method should be implemented in each descendant.
  220. No main catch should be implemented here.
  221. :param args: array of known named arguments and options
  222. :param unnamed_args: array of other values which were passed into command
  223. without -somename and we do not have them in known arg_names
  224. :return: None, output text or exception
  225. """
  226. raise NotImplementedError("Please Implement this method")
  227. class TclCommandSignaled(TclCommand):
  228. """
  229. !!! I left it here only for demonstration !!!
  230. Go to TclCommandCncjob and into class definition put
  231. class TclCommandCncjob(TclCommand.TclCommandSignaled):
  232. also change
  233. obj.generatecncjob(use_thread = False, **args)
  234. to
  235. obj.generatecncjob(use_thread = True, **args)
  236. This class is child of TclCommand and is used for commands which create new objects
  237. it handles all neccessary stuff about blocking and passing exeptions
  238. """
  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 '-timeout <miliseconds>' for command or 'set_sys background_timeout <miliseconds>'.")
  290. try:
  291. self.log.debug("TCL command '%s' executed." % str(self.__class__))
  292. self.original_args=args
  293. args, unnamed_args = self.check_args(args)
  294. if 'timeout' in args:
  295. passed_timeout=args['timeout']
  296. del args['timeout']
  297. else:
  298. passed_timeout= self.app.defaults['background_timeout']
  299. # set detail for processing, it will be there until next open or close
  300. self.app.shell.open_proccessing(self.get_current_command())
  301. def handle_finished(obj):
  302. self.app.shell_command_finished.disconnect(handle_finished)
  303. if self.error is not None:
  304. self.raise_tcl_unknown_error(self.error)
  305. self.app.shell_command_finished.connect(handle_finished)
  306. with wait_signal(self.app.shell_command_finished, passed_timeout):
  307. # every TclCommandNewObject ancestor support timeout as parameter,
  308. # but it does not mean anything for child itself
  309. # when operation will be really long is good to set it higher then defqault 30s
  310. self.app.worker_task.emit({'fcn': self.execute_call, 'params': [args, unnamed_args]})
  311. return self.output
  312. except Exception as unknown:
  313. error_info=sys.exc_info()
  314. self.log.error("TCL command '%s' failed." % str(self))
  315. self.app.display_tcl_error(unknown, error_info)
  316. self.raise_tcl_unknown_error(unknown)