ToolAlignObjects.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 1/13/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import FCComboBox, RadioSet
  10. import math
  11. from shapely.geometry import Point
  12. from shapely.affinity import translate
  13. import gettext
  14. import FlatCAMTranslation as fcTranslate
  15. import builtins
  16. import logging
  17. fcTranslate.apply_language('strings')
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class AlignObjects(FlatCAMTool):
  22. toolName = _("Align Objects")
  23. def __init__(self, app):
  24. FlatCAMTool.__init__(self, app)
  25. self.app = app
  26. self.decimals = app.decimals
  27. self.canvas = self.app.plotcanvas
  28. # ## Title
  29. title_label = QtWidgets.QLabel("%s" % self.toolName)
  30. title_label.setStyleSheet("""
  31. QLabel
  32. {
  33. font-size: 16px;
  34. font-weight: bold;
  35. }
  36. """)
  37. self.layout.addWidget(title_label)
  38. self.layout.addWidget(QtWidgets.QLabel(''))
  39. # Form Layout
  40. grid0 = QtWidgets.QGridLayout()
  41. grid0.setColumnStretch(0, 0)
  42. grid0.setColumnStretch(1, 1)
  43. self.layout.addLayout(grid0)
  44. self.aligned_label = QtWidgets.QLabel('<b>%s:</b>' % _("MOVING object"))
  45. grid0.addWidget(self.aligned_label, 0, 0, 1, 2)
  46. self.aligned_label.setToolTip(
  47. _("Specify the type of object to be aligned.\n"
  48. "It can be of type: Gerber or Excellon.\n"
  49. "The selection here decide the type of objects that will be\n"
  50. "in the Object combobox.")
  51. )
  52. # Type of object to be aligned
  53. self.type_obj_radio = RadioSet([
  54. {"label": _("Gerber"), "value": "grb"},
  55. {"label": _("Excellon"), "value": "exc"},
  56. ], orientation='vertical', stretch=False)
  57. grid0.addWidget(self.type_obj_radio, 3, 0, 1, 2)
  58. # Object to be aligned
  59. self.object_combo = FCComboBox()
  60. self.object_combo.setModel(self.app.collection)
  61. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  62. self.object_combo.is_last = True
  63. self.object_combo.setToolTip(
  64. _("Object to be aligned.")
  65. )
  66. grid0.addWidget(self.object_combo, 4, 0, 1, 2)
  67. separator_line = QtWidgets.QFrame()
  68. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  69. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  70. grid0.addWidget(separator_line, 5, 0, 1, 2)
  71. grid0.addWidget(QtWidgets.QLabel(''), 6, 0, 1, 2)
  72. self.aligned_label = QtWidgets.QLabel('<b>%s:</b>' % _("TARGET object"))
  73. self.aligned_label.setToolTip(
  74. _("Specify the type of object to be aligned to.\n"
  75. "It can be of type: Gerber or Excellon.\n"
  76. "The selection here decide the type of objects that will be\n"
  77. "in the Object combobox.")
  78. )
  79. grid0.addWidget(self.aligned_label, 7, 0, 1, 2)
  80. # Type of object to be aligned to = aligner
  81. self.type_aligner_obj_radio = RadioSet([
  82. {"label": _("Gerber"), "value": "grb"},
  83. {"label": _("Excellon"), "value": "exc"},
  84. ], orientation='vertical', stretch=False)
  85. grid0.addWidget(self.type_aligner_obj_radio, 8, 0, 1, 2)
  86. # Object to be aligned to = aligner
  87. self.aligner_object_combo = FCComboBox()
  88. self.aligner_object_combo.setModel(self.app.collection)
  89. self.aligner_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  90. self.aligner_object_combo.is_last = True
  91. self.aligner_object_combo.setToolTip(
  92. _("Object to be aligned to. Aligner.")
  93. )
  94. grid0.addWidget(self.aligner_object_combo, 9, 0, 1, 2)
  95. separator_line = QtWidgets.QFrame()
  96. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  97. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  98. grid0.addWidget(separator_line, 10, 0, 1, 2)
  99. grid0.addWidget(QtWidgets.QLabel(''), 11, 0, 1, 2)
  100. # Alignment Type
  101. self.a_type_lbl = QtWidgets.QLabel('<b>%s:</b>' % _("Alignment Type"))
  102. self.a_type_lbl.setToolTip(
  103. _("The type of alignment can be:\n"
  104. "- Single Point -> it require a single point of sync, the action will be a translation\n"
  105. "- Dual Point -> it require two points of sync, the action will be translation followed by rotation")
  106. )
  107. self.a_type_radio = RadioSet(
  108. [
  109. {'label': _('Single Point'), 'value': 'sp'},
  110. {'label': _('Dual Point'), 'value': 'dp'}
  111. ],
  112. orientation='vertical',
  113. stretch=False
  114. )
  115. grid0.addWidget(self.a_type_lbl, 12, 0, 1, 2)
  116. grid0.addWidget(self.a_type_radio, 13, 0, 1, 2)
  117. separator_line = QtWidgets.QFrame()
  118. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  119. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  120. grid0.addWidget(separator_line, 14, 0, 1, 2)
  121. # Buttons
  122. self.align_object_button = QtWidgets.QPushButton(_("Align Object"))
  123. self.align_object_button.setToolTip(
  124. _("Align the specified object to the aligner object.\n"
  125. "If only one point is used then it assumes translation.\n"
  126. "If tho points are used it assume translation and rotation.")
  127. )
  128. self.align_object_button.setStyleSheet("""
  129. QPushButton
  130. {
  131. font-weight: bold;
  132. }
  133. """)
  134. self.layout.addWidget(self.align_object_button)
  135. self.layout.addStretch()
  136. # ## Reset Tool
  137. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  138. self.reset_button.setToolTip(
  139. _("Will reset the tool parameters.")
  140. )
  141. self.reset_button.setStyleSheet("""
  142. QPushButton
  143. {
  144. font-weight: bold;
  145. }
  146. """)
  147. self.layout.addWidget(self.reset_button)
  148. # Signals
  149. self.align_object_button.clicked.connect(self.on_align)
  150. self.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  151. self.type_aligner_obj_radio.activated_custom.connect(self.on_type_aligner_changed)
  152. self.reset_button.clicked.connect(self.set_tool_ui)
  153. self.mr = None
  154. # if the mouse events are connected to a local method set this True
  155. self.local_connected = False
  156. # store the status of the grid
  157. self.grid_status_memory = None
  158. self.aligned_obj = None
  159. self.aligner_obj = None
  160. # this is one of the objects: self.aligned_obj or self.aligner_obj
  161. self.target_obj = None
  162. # here store the alignment points
  163. self.clicked_points = []
  164. self.align_type = None
  165. # old colors of objects involved in the alignment
  166. self.aligner_old_fill_color = None
  167. self.aligner_old_line_color = None
  168. self.aligned_old_fill_color = None
  169. self.aligned_old_line_color = None
  170. def run(self, toggle=True):
  171. self.app.report_usage("ToolAlignObjects()")
  172. if toggle:
  173. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  174. if self.app.ui.splitter.sizes()[0] == 0:
  175. self.app.ui.splitter.setSizes([1, 1])
  176. else:
  177. try:
  178. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  179. # if tab is populated with the tool but it does not have the focus, focus on it
  180. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  181. # focus on Tool Tab
  182. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  183. else:
  184. self.app.ui.splitter.setSizes([0, 1])
  185. except AttributeError:
  186. pass
  187. else:
  188. if self.app.ui.splitter.sizes()[0] == 0:
  189. self.app.ui.splitter.setSizes([1, 1])
  190. FlatCAMTool.run(self)
  191. self.set_tool_ui()
  192. self.app.ui.notebook.setTabText(2, _("Align Tool"))
  193. def install(self, icon=None, separator=None, **kwargs):
  194. FlatCAMTool.install(self, icon, separator, shortcut='Alt+A', **kwargs)
  195. def set_tool_ui(self):
  196. self.reset_fields()
  197. self.clicked_points = []
  198. self.target_obj = None
  199. self.aligned_obj = None
  200. self.aligner_obj = None
  201. self.aligner_old_fill_color = None
  202. self.aligner_old_line_color = None
  203. self.aligned_old_fill_color = None
  204. self.aligned_old_line_color = None
  205. self.a_type_radio.set_value(self.app.defaults["tools_align_objects_align_type"])
  206. self.type_obj_radio.set_value('grb')
  207. self.type_aligner_obj_radio.set_value('grb')
  208. if self.local_connected is True:
  209. self.disconnect_cal_events()
  210. def on_type_obj_changed(self, val):
  211. obj_type = {'grb': 0, 'exc': 1}[val]
  212. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  213. self.object_combo.setCurrentIndex(0)
  214. self.object_combo.obj_type = {'grb': "Gerber", 'exc': "Excellon"}[val]
  215. def on_type_aligner_changed(self, val):
  216. obj_type = {'grb': 0, 'exc': 1}[val]
  217. self.aligner_object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  218. self.aligner_object_combo.setCurrentIndex(0)
  219. self.aligner_object_combo.obj_type = {'grb': "Gerber", 'exc': "Excellon"}[val]
  220. def on_align(self):
  221. self.app.delete_selection_shape()
  222. obj_sel_index = self.object_combo.currentIndex()
  223. obj_model_index = self.app.collection.index(obj_sel_index, 0, self.object_combo.rootModelIndex())
  224. try:
  225. self.aligned_obj = obj_model_index.internalPointer().obj
  226. except AttributeError:
  227. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no aligned FlatCAM object selected..."))
  228. return
  229. aligner_obj_sel_index = self.aligner_object_combo.currentIndex()
  230. aligner_obj_model_index = self.app.collection.index(
  231. aligner_obj_sel_index, 0, self.aligner_object_combo.rootModelIndex())
  232. try:
  233. self.aligner_obj = aligner_obj_model_index.internalPointer().obj
  234. except AttributeError:
  235. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no aligner FlatCAM object selected..."))
  236. return
  237. self.align_type = self.a_type_radio.get_value()
  238. # disengage the grid snapping since it will be hard to find the drills or pads on grid
  239. if self.app.ui.grid_snap_btn.isChecked():
  240. self.grid_status_memory = True
  241. self.app.ui.grid_snap_btn.trigger()
  242. else:
  243. self.grid_status_memory = False
  244. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  245. if self.app.is_legacy is False:
  246. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  247. else:
  248. self.canvas.graph_event_disconnect(self.app.mr)
  249. self.local_connected = True
  250. self.aligner_old_fill_color = self.aligner_obj.fill_color
  251. self.aligner_old_line_color = self.aligner_obj.outline_color
  252. self.aligned_old_fill_color = self.aligned_obj.fill_color
  253. self.aligned_old_line_color = self.aligned_obj.outline_color
  254. self.app.inform.emit('%s: %s' % (_("First Point"), _("Click on the START point.")))
  255. self.target_obj = self.aligned_obj
  256. self.set_color()
  257. def on_mouse_click_release(self, event):
  258. if self.app.is_legacy is False:
  259. event_pos = event.pos
  260. right_button = 2
  261. self.app.event_is_dragging = self.app.event_is_dragging
  262. else:
  263. event_pos = (event.xdata, event.ydata)
  264. right_button = 3
  265. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  266. pos_canvas = self.canvas.translate_coords(event_pos)
  267. if event.button == 1:
  268. click_pt = Point([pos_canvas[0], pos_canvas[1]])
  269. if self.app.selection_type is not None:
  270. # delete previous selection shape
  271. self.app.delete_selection_shape()
  272. self.app.selection_type = None
  273. else:
  274. if self.target_obj.kind.lower() == 'excellon':
  275. for tool, tool_dict in self.target_obj.tools.items():
  276. for geo in tool_dict['solid_geometry']:
  277. if click_pt.within(geo):
  278. center_pt = geo.centroid
  279. self.clicked_points.append(
  280. [
  281. float('%.*f' % (self.decimals, center_pt.x)),
  282. float('%.*f' % (self.decimals, center_pt.y))
  283. ]
  284. )
  285. self.check_points()
  286. elif self.target_obj.kind.lower() == 'gerber':
  287. for apid, apid_val in self.target_obj.apertures.items():
  288. for geo_el in apid_val['geometry']:
  289. if 'solid' in geo_el:
  290. if click_pt.within(geo_el['solid']):
  291. if isinstance(geo_el['follow'], Point):
  292. center_pt = geo_el['solid'].centroid
  293. self.clicked_points.append(
  294. [
  295. float('%.*f' % (self.decimals, center_pt.x)),
  296. float('%.*f' % (self.decimals, center_pt.y))
  297. ]
  298. )
  299. self.check_points()
  300. elif event.button == right_button and self.app.event_is_dragging is False:
  301. self.reset_color()
  302. self.clicked_points = []
  303. self.disconnect_cal_events()
  304. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled by user request."))
  305. def check_points(self):
  306. if len(self.clicked_points) == 1:
  307. self.app.inform.emit('%s: %s. %s' % (
  308. _("First Point"), _("Click on the DESTINATION point."), _("Or right click to cancel.")))
  309. self.target_obj = self.aligner_obj
  310. self.reset_color()
  311. self.set_color()
  312. if len(self.clicked_points) == 2:
  313. if self.align_type == 'sp':
  314. self.align_translate()
  315. self.app.inform.emit('[success] %s' % _("Done."))
  316. self.app.plot_all()
  317. self.disconnect_cal_events()
  318. return
  319. else:
  320. self.app.inform.emit('%s: %s. %s' % (
  321. _("Second Point"), _("Click on the START point."), _("Or right click to cancel.")))
  322. self.target_obj = self.aligned_obj
  323. self.reset_color()
  324. self.set_color()
  325. if len(self.clicked_points) == 3:
  326. self.app.inform.emit('%s: %s. %s' % (
  327. _("Second Point"), _("Click on the DESTINATION point."), _("Or right click to cancel.")))
  328. self.target_obj = self.aligner_obj
  329. self.reset_color()
  330. self.set_color()
  331. if len(self.clicked_points) == 4:
  332. self.align_translate()
  333. self.align_rotate()
  334. self.app.inform.emit('[success] %s' % _("Done."))
  335. self.disconnect_cal_events()
  336. self.app.plot_all()
  337. def align_translate(self):
  338. dx = self.clicked_points[1][0] - self.clicked_points[0][0]
  339. dy = self.clicked_points[1][1] - self.clicked_points[0][1]
  340. self.aligned_obj.offset((dx, dy))
  341. # Update the object bounding box options
  342. a, b, c, d = self.aligned_obj.bounds()
  343. self.aligned_obj.options['xmin'] = a
  344. self.aligned_obj.options['ymin'] = b
  345. self.aligned_obj.options['xmax'] = c
  346. self.aligned_obj.options['ymax'] = d
  347. def align_rotate(self):
  348. dx = self.clicked_points[1][0] - self.clicked_points[0][0]
  349. dy = self.clicked_points[1][1] - self.clicked_points[0][1]
  350. test_rotation_pt = translate(Point(self.clicked_points[2]), xoff=dx, yoff=dy)
  351. new_start = (test_rotation_pt.x, test_rotation_pt.y)
  352. new_dest = self.clicked_points[3]
  353. origin_pt = self.clicked_points[1]
  354. dxd = new_dest[0] - origin_pt[0]
  355. dyd = new_dest[1] - origin_pt[1]
  356. dxs = new_start[0] - origin_pt[0]
  357. dys = new_start[1] - origin_pt[1]
  358. rotation_not_needed = (abs(new_start[0] - new_dest[0]) <= (10 ** -self.decimals)) or \
  359. (abs(new_start[1] - new_dest[1]) <= (10 ** -self.decimals))
  360. if rotation_not_needed is False:
  361. # calculate rotation angle
  362. angle_dest = math.degrees(math.atan(dyd / dxd))
  363. angle_start = math.degrees(math.atan(dys / dxs))
  364. angle = angle_dest - angle_start
  365. self.aligned_obj.rotate(angle=angle, point=origin_pt)
  366. def disconnect_cal_events(self):
  367. # restore the Grid snapping if it was active before
  368. if self.grid_status_memory is True:
  369. self.app.ui.grid_snap_btn.trigger()
  370. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  371. if self.app.is_legacy is False:
  372. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  373. else:
  374. self.canvas.graph_event_disconnect(self.mr)
  375. self.local_connected = False
  376. self.aligner_old_fill_color = None
  377. self.aligner_old_line_color = None
  378. self.aligned_old_fill_color = None
  379. self.aligned_old_line_color = None
  380. def set_color(self):
  381. new_color = "#15678abf"
  382. new_line_color = new_color
  383. self.target_obj.shapes.redraw(
  384. update_colors=(new_color, new_line_color)
  385. )
  386. def reset_color(self):
  387. self.aligned_obj.shapes.redraw(
  388. update_colors=(self.aligned_old_fill_color, self.aligned_old_line_color)
  389. )
  390. self.aligner_obj.shapes.redraw(
  391. update_colors=(self.aligner_old_fill_color, self.aligner_old_line_color)
  392. )
  393. def reset_fields(self):
  394. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  395. self.aligner_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))