ToolMove.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.VisPyVisuals import *
  10. from FlatCAMObj import FlatCAMGerber
  11. from copy import copy
  12. import logging
  13. import gettext
  14. import FlatCAMTranslation as fcTranslate
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. log = logging.getLogger('base')
  20. class ToolMove(FlatCAMTool):
  21. toolName = _("Move")
  22. replot_signal = QtCore.pyqtSignal(list)
  23. def __init__(self, app):
  24. FlatCAMTool.__init__(self, app)
  25. self.app = app
  26. self.decimals = self.app.decimals
  27. self.layout.setContentsMargins(0, 0, 3, 0)
  28. self.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Maximum)
  29. self.clicked_move = 0
  30. self.point1 = None
  31. self.point2 = None
  32. # the default state is disabled for the Move command
  33. self.setVisible(False)
  34. self.sel_rect = None
  35. self.old_coords = []
  36. # VisPy visuals
  37. if self.app.is_legacy is False:
  38. self.sel_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1)
  39. else:
  40. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  41. self.sel_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name="move")
  42. self.mm = None
  43. self.mp = None
  44. self.kr = None
  45. self.replot_signal[list].connect(self.replot)
  46. def install(self, icon=None, separator=None, **kwargs):
  47. FlatCAMTool.install(self, icon, separator, shortcut='M', **kwargs)
  48. def run(self, toggle):
  49. self.app.report_usage("ToolMove()")
  50. if self.app.tool_tab_locked is True:
  51. return
  52. self.toggle()
  53. def toggle(self, toggle=False):
  54. if self.isVisible():
  55. self.setVisible(False)
  56. if self.app.is_legacy is False:
  57. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_move)
  58. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.on_left_click)
  59. self.app.plotcanvas.graph_event_disconnect('key_release', self.on_key_press)
  60. self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  61. else:
  62. self.app.plotcanvas.graph_event_disconnect(self.mm)
  63. self.app.plotcanvas.graph_event_disconnect(self.mp)
  64. self.app.plotcanvas.graph_event_disconnect(self.kr)
  65. self.app.kr = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  66. self.clicked_move = 0
  67. # signal that there is no command active
  68. self.app.command_active = None
  69. # delete the selection box
  70. self.delete_shape()
  71. return
  72. else:
  73. self.setVisible(True)
  74. # signal that there is a command active and it is 'Move'
  75. self.app.command_active = "Move"
  76. sel_obj_list = self.app.collection.get_selected()
  77. if sel_obj_list:
  78. self.app.inform.emit(_("MOVE: Click on the Start point ..."))
  79. # if we have an object selected then we can safely activate the mouse events
  80. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_move)
  81. self.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.on_left_click)
  82. self.kr = self.app.plotcanvas.graph_event_connect('key_release', self.on_key_press)
  83. # draw the selection box
  84. self.draw_sel_bbox()
  85. else:
  86. self.toggle()
  87. self.app.inform.emit('[WARNING_NOTCL] %s' % _("MOVE action cancelled. No object(s) to move."))
  88. def on_left_click(self, event):
  89. # mouse click will be accepted only if the left button is clicked
  90. # this is necessary because right mouse click and middle mouse click
  91. # are used for panning on the canvas
  92. if self.app.is_legacy is False:
  93. event_pos = event.pos
  94. else:
  95. event_pos = (event.xdata, event.ydata)
  96. if event.button == 1:
  97. if self.clicked_move == 0:
  98. pos_canvas = self.app.plotcanvas.translate_coords(event_pos)
  99. # if GRID is active we need to get the snapped positions
  100. if self.app.grid_status() == True:
  101. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  102. else:
  103. pos = pos_canvas
  104. if self.point1 is None:
  105. self.point1 = pos
  106. else:
  107. self.point2 = copy(self.point1)
  108. self.point1 = pos
  109. self.app.inform.emit(_("MOVE: Click on the Destination point ..."))
  110. if self.clicked_move == 1:
  111. try:
  112. pos_canvas = self.app.plotcanvas.translate_coords(event_pos)
  113. # delete the selection bounding box
  114. self.delete_shape()
  115. # if GRID is active we need to get the snapped positions
  116. if self.app.grid_status() == True:
  117. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  118. else:
  119. pos = pos_canvas
  120. dx = pos[0] - self.point1[0]
  121. dy = pos[1] - self.point1[1]
  122. # move only the objects selected and plotted and visible
  123. obj_list = [obj for obj in self.app.collection.get_selected()
  124. if obj.options['plot'] and obj.visible is True]
  125. def job_move(app_obj):
  126. with self.app.proc_container.new(_("Moving...")) as proc:
  127. if not obj_list:
  128. app_obj.app.inform.emit('[WARNING_NOTCL] %s' % _("No object(s) selected."))
  129. return "fail"
  130. try:
  131. # remove any mark aperture shape that may be displayed
  132. for sel_obj in obj_list:
  133. # if the Gerber mark shapes are enabled they need to be disabled before move
  134. if isinstance(sel_obj, FlatCAMGerber):
  135. sel_obj.ui.aperture_table_visibility_cb.setChecked(False)
  136. try:
  137. sel_obj.replotApertures.emit()
  138. except Exception:
  139. pass
  140. # offset solid_geometry
  141. sel_obj.offset((dx, dy))
  142. # Update the object bounding box options
  143. a, b, c, d = sel_obj.bounds()
  144. sel_obj.options['xmin'] = a
  145. sel_obj.options['ymin'] = b
  146. sel_obj.options['xmax'] = c
  147. sel_obj.options['ymax'] = d
  148. # update the source_file with the new positions
  149. for sel_obj in obj_list:
  150. out_name = sel_obj.options["name"]
  151. if sel_obj.kind == 'gerber':
  152. sel_obj.source_file = self.app.export_gerber(
  153. obj_name=out_name, filename=None, local_use=sel_obj, use_thread=False)
  154. elif sel_obj.kind == 'excellon':
  155. sel_obj.source_file = self.app.export_excellon(
  156. obj_name=out_name, filename=None, local_use=sel_obj, use_thread=False)
  157. except Exception as e:
  158. log.debug('[ERROR_NOTCL] %s --> %s' % ('ToolMove.on_left_click()', str(e)))
  159. return "fail"
  160. # time to plot the moved objects
  161. app_obj.replot_signal.emit(obj_list)
  162. # delete the selection bounding box
  163. self.delete_shape()
  164. self.app.inform.emit('[success] %s %s' %
  165. (str(sel_obj.kind).capitalize(), 'object was moved ...'))
  166. self.app.worker_task.emit({'fcn': job_move, 'params': [self]})
  167. self.clicked_move = 0
  168. self.toggle()
  169. return
  170. except TypeError as e:
  171. log.debug("ToolMove.on_left_click() --> %s" % str(e))
  172. self.app.inform.emit('[ERROR_NOTCL] ToolMove.on_left_click() --> %s' %
  173. _('Error when mouse left click.'))
  174. return
  175. self.clicked_move = 1
  176. def replot(self, obj_list):
  177. def worker_task():
  178. with self.app.proc_container.new('%s...' % _("Plotting")):
  179. for sel_obj in obj_list:
  180. sel_obj.plot()
  181. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  182. def on_move(self, event):
  183. if self.app.is_legacy is False:
  184. event_pos = event.pos
  185. else:
  186. event_pos = (event.xdata, event.ydata)
  187. try:
  188. x = float(event_pos[0])
  189. y = float(event_pos[1])
  190. except TypeError:
  191. return
  192. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  193. # if GRID is active we need to get the snapped positions
  194. if self.app.grid_status() == True:
  195. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  196. else:
  197. pos = pos_canvas
  198. if self.point1 is None:
  199. dx = pos[0]
  200. dy = pos[1]
  201. else:
  202. dx = pos[0] - self.point1[0]
  203. dy = pos[1] - self.point1[1]
  204. if self.clicked_move == 1:
  205. self.update_sel_bbox((dx, dy))
  206. def on_key_press(self, event):
  207. if event.key == 'escape':
  208. # abort the move action
  209. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Move action cancelled."))
  210. self.toggle()
  211. return
  212. def draw_sel_bbox(self):
  213. xminlist = []
  214. yminlist = []
  215. xmaxlist = []
  216. ymaxlist = []
  217. obj_list = self.app.collection.get_selected()
  218. # first get a bounding box to fit all
  219. for obj in obj_list:
  220. # don't move disabled objects, move only plotted objects
  221. if obj.options['plot']:
  222. xmin, ymin, xmax, ymax = obj.bounds()
  223. xminlist.append(xmin)
  224. yminlist.append(ymin)
  225. xmaxlist.append(xmax)
  226. ymaxlist.append(ymax)
  227. # get the minimum x,y and maximum x,y for all objects selected
  228. xminimal = min(xminlist)
  229. yminimal = min(yminlist)
  230. xmaximal = max(xmaxlist)
  231. ymaximal = max(ymaxlist)
  232. p1 = (xminimal, yminimal)
  233. p2 = (xmaximal, yminimal)
  234. p3 = (xmaximal, ymaximal)
  235. p4 = (xminimal, ymaximal)
  236. self.old_coords = [p1, p2, p3, p4]
  237. self.draw_shape(Polygon(self.old_coords))
  238. if self.app.is_legacy is True:
  239. self.sel_shapes.redraw()
  240. def update_sel_bbox(self, pos):
  241. self.delete_shape()
  242. pt1 = (self.old_coords[0][0] + pos[0], self.old_coords[0][1] + pos[1])
  243. pt2 = (self.old_coords[1][0] + pos[0], self.old_coords[1][1] + pos[1])
  244. pt3 = (self.old_coords[2][0] + pos[0], self.old_coords[2][1] + pos[1])
  245. pt4 = (self.old_coords[3][0] + pos[0], self.old_coords[3][1] + pos[1])
  246. self.draw_shape(Polygon([pt1, pt2, pt3, pt4]))
  247. if self.app.is_legacy is True:
  248. self.sel_shapes.redraw()
  249. def delete_shape(self):
  250. self.sel_shapes.clear()
  251. self.sel_shapes.redraw()
  252. def draw_shape(self, shape):
  253. if self.app.defaults['units'].upper() == 'MM':
  254. proc_shape = shape.buffer(-0.1)
  255. proc_shape = proc_shape.buffer(0.2)
  256. else:
  257. proc_shape = shape.buffer(-0.00393)
  258. proc_shape = proc_shape.buffer(0.00787)
  259. # face = Color('blue')
  260. # face.alpha = 0.2
  261. face = '#0000FF' + str(hex(int(0.2 * 255)))[2:]
  262. outline = '#0000FFAF'
  263. self.sel_shapes.add(proc_shape, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  264. # end of file