ToolAlignObjects.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. from copy import deepcopy
  11. import numpy as np
  12. from shapely.geometry import Point
  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. # Form Layout
  39. grid0 = QtWidgets.QGridLayout()
  40. grid0.setColumnStretch(0, 0)
  41. grid0.setColumnStretch(1, 1)
  42. self.layout.addLayout(grid0)
  43. self.aligned_label = QtWidgets.QLabel('<b>%s</b>' % _("Selection of the aligned object"))
  44. grid0.addWidget(self.aligned_label, 0, 0, 1, 2)
  45. # Type of object to be aligned
  46. self.type_obj_combo = FCComboBox()
  47. self.type_obj_combo.addItem("Gerber")
  48. self.type_obj_combo.addItem("Excellon")
  49. self.type_obj_combo.addItem("Geometry")
  50. self.type_obj_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  51. self.type_obj_combo.setItemIcon(1, QtGui.QIcon(self.app.resource_location + "/drill16.png"))
  52. self.type_obj_combo.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  53. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Object Type"))
  54. self.type_obj_combo_label.setToolTip(
  55. _("Specify the type of object to be aligned.\n"
  56. "It can be of type: Gerber, Excellon or Geometry.\n"
  57. "The selection here decide the type of objects that will be\n"
  58. "in the Object combobox.")
  59. )
  60. grid0.addWidget(self.type_obj_combo_label, 2, 0)
  61. grid0.addWidget(self.type_obj_combo, 2, 1)
  62. # Object to be aligned
  63. self.object_combo = FCComboBox()
  64. self.object_combo.setModel(self.app.collection)
  65. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  66. self.object_combo.setCurrentIndex(1)
  67. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  68. self.object_label.setToolTip(
  69. _("Object to be aligned.")
  70. )
  71. grid0.addWidget(self.object_label, 3, 0)
  72. grid0.addWidget(self.object_combo, 3, 1)
  73. separator_line = QtWidgets.QFrame()
  74. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  75. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  76. grid0.addWidget(separator_line, 4, 0, 1, 2)
  77. self.aligned_label = QtWidgets.QLabel('<b>%s</b>' % _("Selection of the aligner object"))
  78. self.aligned_label.setToolTip(
  79. _("Object to which the other objects will be aligned to (moved).")
  80. )
  81. grid0.addWidget(self.aligned_label, 6, 0, 1, 2)
  82. # Type of object to be aligned to = aligner
  83. self.type_aligner_obj_combo = FCComboBox()
  84. self.type_aligner_obj_combo.addItem("Gerber")
  85. self.type_aligner_obj_combo.addItem("Excellon")
  86. self.type_aligner_obj_combo.addItem("Geometry")
  87. self.type_aligner_obj_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  88. self.type_aligner_obj_combo.setItemIcon(1, QtGui.QIcon(self.app.resource_location + "/drill16.png"))
  89. self.type_aligner_obj_combo.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  90. self.type_aligner_obj_combo_label = QtWidgets.QLabel('%s:' % _("Object Type"))
  91. self.type_aligner_obj_combo_label.setToolTip(
  92. _("Specify the type of object to be aligned to.\n"
  93. "It can be of type: Gerber, Excellon or Geometry.\n"
  94. "The selection here decide the type of objects that will be\n"
  95. "in the Object combobox.")
  96. )
  97. grid0.addWidget(self.type_aligner_obj_combo_label, 7, 0)
  98. grid0.addWidget(self.type_aligner_obj_combo, 7, 1)
  99. # Object to be aligned to = aligner
  100. self.aligner_object_combo = FCComboBox()
  101. self.aligner_object_combo.setModel(self.app.collection)
  102. self.aligner_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  103. self.aligner_object_combo.setCurrentIndex(1)
  104. self.aligner_object_label = QtWidgets.QLabel('%s:' % _("Object"))
  105. self.aligner_object_label.setToolTip(
  106. _("Object to be aligned to. Aligner.")
  107. )
  108. grid0.addWidget(self.aligner_object_label, 8, 0)
  109. grid0.addWidget(self.aligner_object_combo, 8, 1)
  110. separator_line = QtWidgets.QFrame()
  111. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  112. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  113. grid0.addWidget(separator_line, 9, 0, 1, 2)
  114. # Alignment Type
  115. self.a_type_lbl = QtWidgets.QLabel('<b>%s:</b>' % _("Alignment Type"))
  116. self.a_type_lbl.setToolTip(
  117. _("The type of alignment can be:\n"
  118. "- Single Point -> it require a single point of sync, the action will be a translation\n"
  119. "- Dual Point -> it require two points of sync, the action will be translation followed by rotation")
  120. )
  121. self.a_type_radio = RadioSet(
  122. [
  123. {'label': _('Single Point'), 'value': 'sp'},
  124. {'label': _('Dual Point'), 'value': 'dp'}
  125. ],
  126. orientation='horizontal',
  127. stretch=False
  128. )
  129. grid0.addWidget(self.a_type_lbl, 10, 0, 1, 2)
  130. grid0.addWidget(self.a_type_radio, 11, 0, 1, 2)
  131. separator_line = QtWidgets.QFrame()
  132. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  133. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  134. grid0.addWidget(separator_line, 12, 0, 1, 2)
  135. # Buttons
  136. self.align_object_button = QtWidgets.QPushButton(_("Align Object"))
  137. self.align_object_button.setToolTip(
  138. _("Align the specified object to the aligner object.\n"
  139. "If only one point is used then it assumes translation.\n"
  140. "If tho points are used it assume translation and rotation.")
  141. )
  142. self.align_object_button.setStyleSheet("""
  143. QPushButton
  144. {
  145. font-weight: bold;
  146. }
  147. """)
  148. self.layout.addWidget(self.align_object_button)
  149. self.layout.addStretch()
  150. # ## Reset Tool
  151. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  152. self.reset_button.setToolTip(
  153. _("Will reset the tool parameters.")
  154. )
  155. self.reset_button.setStyleSheet("""
  156. QPushButton
  157. {
  158. font-weight: bold;
  159. }
  160. """)
  161. self.layout.addWidget(self.reset_button)
  162. # Signals
  163. self.align_object_button.clicked.connect(self.on_align)
  164. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  165. self.type_aligner_obj_combo.currentIndexChanged.connect(self.on_type_aligner_index_changed)
  166. self.reset_button.clicked.connect(self.set_tool_ui)
  167. self.mr = None
  168. # if the mouse events are connected to a local method set this True
  169. self.local_connected = False
  170. # store the status of the grid
  171. self.grid_status_memory = None
  172. self.aligned_obj = None
  173. self.aligner_obj = None
  174. # this is one of the objects: self.aligned_obj or self.aligner_obj
  175. self.target_obj = None
  176. # here store the alignment points
  177. self.clicked_points = list()
  178. self.align_type = None
  179. def run(self, toggle=True):
  180. self.app.report_usage("ToolAlignObjects()")
  181. if toggle:
  182. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  183. if self.app.ui.splitter.sizes()[0] == 0:
  184. self.app.ui.splitter.setSizes([1, 1])
  185. else:
  186. try:
  187. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  188. # if tab is populated with the tool but it does not have the focus, focus on it
  189. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  190. # focus on Tool Tab
  191. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  192. else:
  193. self.app.ui.splitter.setSizes([0, 1])
  194. except AttributeError:
  195. pass
  196. else:
  197. if self.app.ui.splitter.sizes()[0] == 0:
  198. self.app.ui.splitter.setSizes([1, 1])
  199. FlatCAMTool.run(self)
  200. self.set_tool_ui()
  201. self.app.ui.notebook.setTabText(2, _("Align Tool"))
  202. def install(self, icon=None, separator=None, **kwargs):
  203. FlatCAMTool.install(self, icon, separator, shortcut='ALT+A', **kwargs)
  204. def set_tool_ui(self):
  205. self.reset_fields()
  206. self.clicked_points = list()
  207. self.target_obj = None
  208. self.aligned_obj = None
  209. self.aligner_obj = None
  210. self.a_type_radio.set_value(self.app.defaults["tools_align_objects_align_type"])
  211. if self.local_connected is True:
  212. self.disconnect_cal_events()
  213. def on_type_obj_index_changed(self):
  214. obj_type = self.type_obj_combo.currentIndex()
  215. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  216. self.object_combo.setCurrentIndex(0)
  217. def on_type_aligner_index_changed(self):
  218. obj_type = self.type_aligner_obj_combo.currentIndex()
  219. self.aligner_object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  220. self.aligner_object_combo.setCurrentIndex(0)
  221. def on_align(self):
  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.object_combo.currentIndex()
  230. aligner_obj_model_index = self.app.collection.index(
  231. aligner_obj_sel_index, 0, self.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.app.inform.emit(_("Get First alignment point on the aligned object."))
  251. self.target_obj = self.aligned_obj
  252. def on_mouse_click_release(self, event):
  253. if self.app.is_legacy is False:
  254. event_pos = event.pos
  255. right_button = 2
  256. self.app.event_is_dragging = self.app.event_is_dragging
  257. else:
  258. event_pos = (event.xdata, event.ydata)
  259. right_button = 3
  260. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  261. pos_canvas = self.canvas.translate_coords(event_pos)
  262. if event.button == 1:
  263. click_pt = Point([pos_canvas[0], pos_canvas[1]])
  264. if self.app.selection_type is not None:
  265. # delete previous selection shape
  266. self.app.delete_selection_shape()
  267. self.app.selection_type = None
  268. else:
  269. if self.target_obj.kind.lower() == 'excellon':
  270. for tool, tool_dict in self.target_obj.tools.items():
  271. for geo in tool_dict['solid_geometry']:
  272. if click_pt.within(geo):
  273. center_pt = geo.centroid
  274. self.clicked_points.append(
  275. [
  276. float('%.*f' % (self.decimals, center_pt.x)),
  277. float('%.*f' % (self.decimals, center_pt.y))
  278. ]
  279. )
  280. self.check_points()
  281. elif self.target_obj.kind.lower() == 'gerber':
  282. for apid, apid_val in self.target_obj.apertures.items():
  283. for geo_el in apid_val['geometry']:
  284. if 'solid' in geo_el:
  285. if click_pt.within(geo_el['solid']):
  286. if isinstance(geo_el['follow'], Point):
  287. center_pt = geo_el['solid'].centroid
  288. self.clicked_points.append(
  289. [
  290. float('%.*f' % (self.decimals, center_pt.x)),
  291. float('%.*f' % (self.decimals, center_pt.y))
  292. ]
  293. )
  294. self.check_points()
  295. elif event.button == right_button and self.app.event_is_dragging is False:
  296. self.clicked_points = list()
  297. self.disconnect_cal_events()
  298. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled by user request."))
  299. def check_points(self):
  300. if self.align_type == 'sp':
  301. if len(self.clicked_points) == 1:
  302. self.app.inform.emit(_("Get First alignment point on the aligner object."))
  303. # TODO: not working
  304. self.target_obj = self.aligner_obj
  305. if len(self.clicked_points) == 2:
  306. self.app.inform.emit('[success] %s' % _("Done."))
  307. self.align_translate()
  308. self.disconnect_cal_events()
  309. else:
  310. if len(self.clicked_points) == 1:
  311. self.app.inform.emit(_("Get Second alignment point on aligned object. Or right click to cancel."))
  312. if len(self.clicked_points) == 2:
  313. self.app.inform.emit(_("Get First alignment point on the aligner object."))
  314. self.target_obj = self.aligner_obj
  315. if len(self.clicked_points) == 3:
  316. self.app.inform.emit(_("Get Second alignment point on the aligner object. Or right click to cancel."))
  317. if len(self.clicked_points) == 4:
  318. self.app.inform.emit('[success] %s' % _("Done."))
  319. self.align_translate()
  320. self.align_rotate()
  321. self.disconnect_cal_events()
  322. def align_translate(self):
  323. pass
  324. def align_rotate(self):
  325. pass
  326. def execute(self):
  327. aligned_name = self.object_combo.currentText()
  328. # Get source object.
  329. try:
  330. aligned_obj = self.app.collection.get_by_name(str(aligned_name))
  331. except Exception as e:
  332. log.debug("AlignObjects.on_align() --> %s" % str(e))
  333. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), aligned_name))
  334. return "Could not retrieve object: %s" % aligned_name
  335. if aligned_obj is None:
  336. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), aligned_obj))
  337. return "Object not found: %s" % aligned_obj
  338. aligner_name = self.box_combo.currentText()
  339. try:
  340. aligner_obj = self.app.collection.get_by_name(aligner_name)
  341. except Exception as e:
  342. log.debug("AlignObjects.on_align() --> %s" % str(e))
  343. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), aligner_name))
  344. return "Could not retrieve object: %s" % aligner_name
  345. if aligner_obj is None:
  346. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), aligner_name))
  347. def align_job():
  348. pass
  349. proc = self.app.proc_container.new(_("Working..."))
  350. def job_thread(app_obj):
  351. try:
  352. align_job()
  353. app_obj.inform.emit('[success] %s' % _("Panel created successfully."))
  354. except Exception as ee:
  355. proc.done()
  356. log.debug(str(ee))
  357. return
  358. proc.done()
  359. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  360. def disconnect_cal_events(self):
  361. # restore the Grid snapping if it was active before
  362. if self.grid_status_memory is True:
  363. self.app.ui.grid_snap_btn.trigger()
  364. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  365. if self.app.is_legacy is False:
  366. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  367. else:
  368. self.canvas.graph_event_disconnect(self.mr)
  369. self.local_connected = False
  370. self.target_obj = None
  371. self.aligned_obj = None
  372. self.aligner_obj = None
  373. def reset_fields(self):
  374. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  375. self.aligner_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))