ToolMove.py 13 KB

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