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.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. except Exception as e:
  149. log.debug('[ERROR_NOTCL] %s --> %s' % ('ToolMove.on_left_click()', str(e)))
  150. return "fail"
  151. # time to plot the moved objects
  152. app_obj.replot_signal.emit(obj_list)
  153. # delete the selection bounding box
  154. self.delete_shape()
  155. self.app.inform.emit('[success] %s %s' %
  156. (str(sel_obj.kind).capitalize(), 'object was moved ...'))
  157. self.app.worker_task.emit({'fcn': job_move, 'params': [self]})
  158. self.clicked_move = 0
  159. self.toggle()
  160. return
  161. except TypeError as e:
  162. log.debug("ToolMove.on_left_click() --> %s" % str(e))
  163. self.app.inform.emit('[ERROR_NOTCL] ToolMove.on_left_click() --> %s' %
  164. _('Error when mouse left click.'))
  165. return
  166. self.clicked_move = 1
  167. def replot(self, obj_list):
  168. def worker_task():
  169. with self.app.proc_container.new('%s...' % _("Plotting")):
  170. for sel_obj in obj_list:
  171. sel_obj.plot()
  172. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  173. def on_move(self, event):
  174. if self.app.is_legacy is False:
  175. event_pos = event.pos
  176. else:
  177. event_pos = (event.xdata, event.ydata)
  178. try:
  179. x = float(event_pos[0])
  180. y = float(event_pos[1])
  181. except TypeError:
  182. return
  183. pos_canvas = self.app.plotcanvas.translate_coords((x, y))
  184. # if GRID is active we need to get the snapped positions
  185. if self.app.grid_status() == True:
  186. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  187. else:
  188. pos = pos_canvas
  189. if self.point1 is None:
  190. dx = pos[0]
  191. dy = pos[1]
  192. else:
  193. dx = pos[0] - self.point1[0]
  194. dy = pos[1] - self.point1[1]
  195. if self.clicked_move == 1:
  196. self.update_sel_bbox((dx, dy))
  197. def on_key_press(self, event):
  198. if event.key == 'escape':
  199. # abort the move action
  200. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Move action cancelled."))
  201. self.toggle()
  202. return
  203. def draw_sel_bbox(self):
  204. xminlist = []
  205. yminlist = []
  206. xmaxlist = []
  207. ymaxlist = []
  208. obj_list = self.app.collection.get_selected()
  209. # first get a bounding box to fit all
  210. for obj in obj_list:
  211. # don't move disabled objects, move only plotted objects
  212. if obj.options['plot']:
  213. xmin, ymin, xmax, ymax = obj.bounds()
  214. xminlist.append(xmin)
  215. yminlist.append(ymin)
  216. xmaxlist.append(xmax)
  217. ymaxlist.append(ymax)
  218. # get the minimum x,y and maximum x,y for all objects selected
  219. xminimal = min(xminlist)
  220. yminimal = min(yminlist)
  221. xmaximal = max(xmaxlist)
  222. ymaximal = max(ymaxlist)
  223. p1 = (xminimal, yminimal)
  224. p2 = (xmaximal, yminimal)
  225. p3 = (xmaximal, ymaximal)
  226. p4 = (xminimal, ymaximal)
  227. self.old_coords = [p1, p2, p3, p4]
  228. self.draw_shape(Polygon(self.old_coords))
  229. if self.app.is_legacy is True:
  230. self.sel_shapes.redraw()
  231. def update_sel_bbox(self, pos):
  232. self.delete_shape()
  233. pt1 = (self.old_coords[0][0] + pos[0], self.old_coords[0][1] + pos[1])
  234. pt2 = (self.old_coords[1][0] + pos[0], self.old_coords[1][1] + pos[1])
  235. pt3 = (self.old_coords[2][0] + pos[0], self.old_coords[2][1] + pos[1])
  236. pt4 = (self.old_coords[3][0] + pos[0], self.old_coords[3][1] + pos[1])
  237. self.draw_shape(Polygon([pt1, pt2, pt3, pt4]))
  238. if self.app.is_legacy is True:
  239. self.sel_shapes.redraw()
  240. def delete_shape(self):
  241. self.sel_shapes.clear()
  242. self.sel_shapes.redraw()
  243. def draw_shape(self, shape):
  244. if self.app.defaults['units'].upper() == 'MM':
  245. proc_shape = shape.buffer(-0.1)
  246. proc_shape = proc_shape.buffer(0.2)
  247. else:
  248. proc_shape = shape.buffer(-0.00393)
  249. proc_shape = proc_shape.buffer(0.00787)
  250. # face = Color('blue')
  251. # face.alpha = 0.2
  252. face = '#0000FF' + str(hex(int(0.2 * 255)))[2:]
  253. outline = '#0000FFAF'
  254. self.sel_shapes.add(proc_shape, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  255. # end of file