ToolMove.py 12 KB

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