TclCommand.py 14 KB

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