ToolFiducials.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 11/21/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCDoubleSpinner, RadioSet, EvalEntry, FCTable, FCComboBox
  10. from shapely.geometry import Point, Polygon, MultiPolygon, LineString
  11. from shapely.geometry import box as box
  12. import math
  13. import logging
  14. from copy import deepcopy
  15. import gettext
  16. import appTranslation as fcTranslate
  17. import builtins
  18. fcTranslate.apply_language('strings')
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. log = logging.getLogger('base')
  22. class ToolFiducials(AppTool):
  23. def __init__(self, app):
  24. AppTool.__init__(self, app)
  25. self.app = app
  26. self.canvas = self.app.plotcanvas
  27. self.decimals = self.app.decimals
  28. self.units = ''
  29. # #############################################################################
  30. # ######################### Tool GUI ##########################################
  31. # #############################################################################
  32. self.ui = FidoUI(layout=self.layout, app=self.app)
  33. self.toolName = self.ui.toolName
  34. # Objects involved in Copper thieving
  35. self.grb_object = None
  36. self.sm_object = None
  37. self.copper_obj_set = set()
  38. self.sm_obj_set = set()
  39. # store the flattened geometry here:
  40. self.flat_geometry = []
  41. # Events ID
  42. self.mr = None
  43. self.mm = None
  44. # Mouse cursor positions
  45. self.cursor_pos = (0, 0)
  46. self.first_click = False
  47. self.mode_method = False
  48. # Tool properties
  49. self.fid_dia = None
  50. self.sm_opening_dia = None
  51. self.margin_val = None
  52. self.sec_position = None
  53. self.grb_steps_per_circle = self.app.defaults["gerber_circle_steps"]
  54. self.click_points = []
  55. # SIGNALS
  56. self.ui.add_cfid_button.clicked.connect(self.add_fiducials)
  57. self.ui.add_sm_opening_button.clicked.connect(self.add_soldermask_opening)
  58. self.ui.fid_type_radio.activated_custom.connect(self.on_fiducial_type)
  59. self.ui.pos_radio.activated_custom.connect(self.on_second_point)
  60. self.ui.mode_radio.activated_custom.connect(self.on_method_change)
  61. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  62. def run(self, toggle=True):
  63. self.app.defaults.report_usage("ToolFiducials()")
  64. if toggle:
  65. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  66. if self.app.ui.splitter.sizes()[0] == 0:
  67. self.app.ui.splitter.setSizes([1, 1])
  68. else:
  69. try:
  70. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  71. # if tab is populated with the tool but it does not have the focus, focus on it
  72. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  73. # focus on Tool Tab
  74. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  75. else:
  76. self.app.ui.splitter.setSizes([0, 1])
  77. except AttributeError:
  78. pass
  79. else:
  80. if self.app.ui.splitter.sizes()[0] == 0:
  81. self.app.ui.splitter.setSizes([1, 1])
  82. AppTool.run(self)
  83. self.set_tool_ui()
  84. self.app.ui.notebook.setTabText(2, _("Fiducials Tool"))
  85. def install(self, icon=None, separator=None, **kwargs):
  86. AppTool.install(self, icon, separator, shortcut='Alt+F', **kwargs)
  87. def set_tool_ui(self):
  88. self.units = self.app.defaults['units']
  89. self.ui.fid_size_entry.set_value(self.app.defaults["tools_fiducials_dia"])
  90. self.ui.margin_entry.set_value(float(self.app.defaults["tools_fiducials_margin"]))
  91. self.ui.mode_radio.set_value(self.app.defaults["tools_fiducials_mode"])
  92. self.ui.pos_radio.set_value(self.app.defaults["tools_fiducials_second_pos"])
  93. self.ui.fid_type_radio.set_value(self.app.defaults["tools_fiducials_type"])
  94. self.ui.line_thickness_entry.set_value(float(self.app.defaults["tools_fiducials_line_thickness"]))
  95. self.click_points = []
  96. self.ui.bottom_left_coords_entry.set_value('')
  97. self.ui.top_right_coords_entry.set_value('')
  98. self.ui.sec_points_coords_entry.set_value('')
  99. self.copper_obj_set = set()
  100. self.sm_obj_set = set()
  101. def on_second_point(self, val):
  102. if val == 'no':
  103. self.ui.id_item_3.setFlags(QtCore.Qt.NoItemFlags)
  104. self.ui.sec_point_coords_lbl.setFlags(QtCore.Qt.NoItemFlags)
  105. self.ui.sec_points_coords_entry.setDisabled(True)
  106. else:
  107. self.ui.id_item_3.setFlags(QtCore.Qt.ItemIsEnabled)
  108. self.ui.sec_point_coords_lbl.setFlags(QtCore.Qt.ItemIsEnabled)
  109. self.ui.sec_points_coords_entry.setDisabled(False)
  110. def on_method_change(self, val):
  111. """
  112. Make sure that on method change we disconnect the event handlers and reset the points storage
  113. :param val: value of the Radio button which trigger this method
  114. :return: None
  115. """
  116. if val == 'auto':
  117. self.click_points = []
  118. try:
  119. self.disconnect_event_handlers()
  120. except TypeError:
  121. pass
  122. def on_fiducial_type(self, val):
  123. if val == 'cross':
  124. self.ui.line_thickness_label.setDisabled(False)
  125. self.ui.line_thickness_entry.setDisabled(False)
  126. else:
  127. self.ui.line_thickness_label.setDisabled(True)
  128. self.ui.line_thickness_entry.setDisabled(True)
  129. def add_fiducials(self):
  130. self.app.call_source = "fiducials_tool"
  131. self.mode_method = self.ui.mode_radio.get_value()
  132. self.margin_val = self.ui.margin_entry.get_value()
  133. self.sec_position = self.ui.pos_radio.get_value()
  134. fid_type = self.ui.fid_type_radio.get_value()
  135. self.click_points = []
  136. # get the Gerber object on which the Fiducial will be inserted
  137. selection_index = self.ui.grb_object_combo.currentIndex()
  138. model_index = self.app.collection.index(selection_index, 0, self.ui.grb_object_combo.rootModelIndex())
  139. try:
  140. self.grb_object = model_index.internalPointer().obj
  141. except Exception as e:
  142. log.debug("ToolFiducials.execute() --> %s" % str(e))
  143. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  144. return
  145. self.copper_obj_set.add(self.grb_object.options['name'])
  146. if self.mode_method == 'auto':
  147. xmin, ymin, xmax, ymax = self.grb_object.bounds()
  148. bbox = box(xmin, ymin, xmax, ymax)
  149. buf_bbox = bbox.buffer(self.margin_val, self.grb_steps_per_circle, join_style=2)
  150. x0, y0, x1, y1 = buf_bbox.bounds
  151. self.click_points.append(
  152. (
  153. float('%.*f' % (self.decimals, x0)),
  154. float('%.*f' % (self.decimals, y0))
  155. )
  156. )
  157. self.ui.bottom_left_coords_entry.set_value('(%.*f, %.*f)' % (self.decimals, x0, self.decimals, y0))
  158. self.click_points.append(
  159. (
  160. float('%.*f' % (self.decimals, x1)),
  161. float('%.*f' % (self.decimals, y1))
  162. )
  163. )
  164. self.ui.top_right_coords_entry.set_value('(%.*f, %.*f)' % (self.decimals, x1, self.decimals, y1))
  165. if self.sec_position == 'up':
  166. self.click_points.append(
  167. (
  168. float('%.*f' % (self.decimals, x0)),
  169. float('%.*f' % (self.decimals, y1))
  170. )
  171. )
  172. self.ui.sec_points_coords_entry.set_value('(%.*f, %.*f)' % (self.decimals, x0, self.decimals, y1))
  173. elif self.sec_position == 'down':
  174. self.click_points.append(
  175. (
  176. float('%.*f' % (self.decimals, x1)),
  177. float('%.*f' % (self.decimals, y0))
  178. )
  179. )
  180. self.ui.sec_points_coords_entry.set_value('(%.*f, %.*f)' % (self.decimals, x1, self.decimals, y0))
  181. self.add_fiducials_geo(self.click_points, g_obj=self.grb_object, fid_type=fid_type)
  182. self.grb_object.source_file = self.app.f_handlers.export_gerber(obj_name=self.grb_object.options['name'],
  183. filename=None,
  184. local_use=self.grb_object, use_thread=False)
  185. self.on_exit()
  186. else:
  187. self.app.inform.emit(_("Click to add first Fiducial. Bottom Left..."))
  188. self.ui.bottom_left_coords_entry.set_value('')
  189. self.ui.top_right_coords_entry.set_value('')
  190. self.ui.sec_points_coords_entry.set_value('')
  191. self.connect_event_handlers()
  192. # To be called after clicking on the plot.
  193. def add_fiducials_geo(self, points_list, g_obj, fid_size=None, fid_type=None, line_size=None):
  194. """
  195. Add geometry to the solid_geometry of the copper Gerber object
  196. :param points_list: list of coordinates for the fiducials
  197. :param g_obj: the Gerber object where to add the geometry
  198. :param fid_size: the overall size of the fiducial or fiducial opening depending on the g_obj type
  199. :param fid_type: the type of fiducial: circular or cross
  200. :param line_size: the line thickenss when the fiducial type is cross
  201. :return:
  202. """
  203. fid_size = self.ui.fid_size_entry.get_value() if fid_size is None else fid_size
  204. fid_type = 'circular' if fid_type is None else fid_type
  205. line_thickness = self.ui.line_thickness_entry.get_value() if line_size is None else line_size
  206. radius = fid_size / 2.0
  207. if fid_type == 'circular':
  208. geo_list = [Point(pt).buffer(radius, self.grb_steps_per_circle) for pt in points_list]
  209. aperture_found = None
  210. for ap_id, ap_val in g_obj.apertures.items():
  211. if ap_val['type'] == 'C' and ap_val['size'] == fid_size:
  212. aperture_found = ap_id
  213. break
  214. if aperture_found:
  215. for geo in geo_list:
  216. dict_el = {'follow': geo.centroid, 'solid': geo}
  217. g_obj.apertures[aperture_found]['geometry'].append(deepcopy(dict_el))
  218. else:
  219. ap_keys = list(g_obj.apertures.keys())
  220. if ap_keys:
  221. new_apid = str(int(max(ap_keys)) + 1)
  222. else:
  223. new_apid = '10'
  224. g_obj.apertures[new_apid] = {}
  225. g_obj.apertures[new_apid]['type'] = 'C'
  226. g_obj.apertures[new_apid]['size'] = fid_size
  227. g_obj.apertures[new_apid]['geometry'] = []
  228. for geo in geo_list:
  229. dict_el = {'follow': geo.centroid, 'solid': geo}
  230. g_obj.apertures[new_apid]['geometry'].append(deepcopy(dict_el))
  231. s_list = []
  232. if g_obj.solid_geometry:
  233. try:
  234. for poly in g_obj.solid_geometry:
  235. s_list.append(poly)
  236. except TypeError:
  237. s_list.append(g_obj.solid_geometry)
  238. s_list += geo_list
  239. g_obj.solid_geometry = MultiPolygon(s_list)
  240. elif fid_type == 'cross':
  241. geo_list = []
  242. for pt in points_list:
  243. x = pt[0]
  244. y = pt[1]
  245. line_geo_hor = LineString([
  246. (x - radius + (line_thickness / 2.0), y), (x + radius - (line_thickness / 2.0), y)
  247. ])
  248. line_geo_vert = LineString([
  249. (x, y - radius + (line_thickness / 2.0)), (x, y + radius - (line_thickness / 2.0))
  250. ])
  251. geo_list.append([line_geo_hor, line_geo_vert])
  252. aperture_found = None
  253. for ap_id, ap_val in g_obj.apertures.items():
  254. if ap_val['type'] == 'C' and ap_val['size'] == line_thickness:
  255. aperture_found = ap_id
  256. break
  257. geo_buff_list = []
  258. if aperture_found:
  259. for geo in geo_list:
  260. geo_buff_h = geo[0].buffer(line_thickness / 2.0, self.grb_steps_per_circle)
  261. geo_buff_v = geo[1].buffer(line_thickness / 2.0, self.grb_steps_per_circle)
  262. geo_buff_list.append(geo_buff_h)
  263. geo_buff_list.append(geo_buff_v)
  264. dict_el = {'follow': geo_buff_h.centroid, 'solid': geo_buff_h}
  265. g_obj.apertures[aperture_found]['geometry'].append(deepcopy(dict_el))
  266. dict_el['follow'] = geo_buff_v.centroid
  267. dict_el['solid'] = geo_buff_v
  268. g_obj.apertures[aperture_found]['geometry'].append(deepcopy(dict_el))
  269. else:
  270. ap_keys = list(g_obj.apertures.keys())
  271. if ap_keys:
  272. new_apid = str(int(max(ap_keys)) + 1)
  273. else:
  274. new_apid = '10'
  275. g_obj.apertures[new_apid] = {
  276. 'type': 'C',
  277. 'size': line_thickness,
  278. 'geometry': []
  279. }
  280. for geo in geo_list:
  281. geo_buff_h = geo[0].buffer(line_thickness / 2.0, self.grb_steps_per_circle)
  282. geo_buff_v = geo[1].buffer(line_thickness / 2.0, self.grb_steps_per_circle)
  283. geo_buff_list.append(geo_buff_h)
  284. geo_buff_list.append(geo_buff_v)
  285. dict_el = {'follow': geo_buff_h.centroid, 'solid': geo_buff_h}
  286. g_obj.apertures[new_apid]['geometry'].append(deepcopy(dict_el))
  287. dict_el['follow'] = geo_buff_v.centroid
  288. dict_el['solid'] = geo_buff_v
  289. g_obj.apertures[new_apid]['geometry'].append(deepcopy(dict_el))
  290. s_list = []
  291. if g_obj.solid_geometry:
  292. try:
  293. for poly in g_obj.solid_geometry:
  294. s_list.append(poly)
  295. except TypeError:
  296. s_list.append(g_obj.solid_geometry)
  297. geo_buff_list = MultiPolygon(geo_buff_list)
  298. geo_buff_list = geo_buff_list.buffer(0)
  299. for poly in geo_buff_list:
  300. s_list.append(poly)
  301. g_obj.solid_geometry = MultiPolygon(s_list)
  302. else:
  303. # chess pattern fiducial type
  304. geo_list = []
  305. def make_square_poly(center_pt, side_size):
  306. half_s = side_size / 2
  307. x_center = center_pt[0]
  308. y_center = center_pt[1]
  309. pt1 = (x_center - half_s, y_center - half_s)
  310. pt2 = (x_center + half_s, y_center - half_s)
  311. pt3 = (x_center + half_s, y_center + half_s)
  312. pt4 = (x_center - half_s, y_center + half_s)
  313. return Polygon([pt1, pt2, pt3, pt4, pt1])
  314. for pt in points_list:
  315. x = pt[0]
  316. y = pt[1]
  317. first_square = make_square_poly(center_pt=(x-fid_size/4, y+fid_size/4), side_size=fid_size/2)
  318. second_square = make_square_poly(center_pt=(x+fid_size/4, y-fid_size/4), side_size=fid_size/2)
  319. geo_list += [first_square, second_square]
  320. aperture_found = None
  321. new_ap_size = math.sqrt(fid_size**2 + fid_size**2)
  322. for ap_id, ap_val in g_obj.apertures.items():
  323. if ap_val['type'] == 'R' and \
  324. round(ap_val['size'], ndigits=self.decimals) == round(new_ap_size, ndigits=self.decimals):
  325. aperture_found = ap_id
  326. break
  327. geo_buff_list = []
  328. if aperture_found:
  329. for geo in geo_list:
  330. geo_buff_list.append(geo)
  331. dict_el = {'follow': geo.centroid, 'solid': geo}
  332. g_obj.apertures[aperture_found]['geometry'].append(deepcopy(dict_el))
  333. else:
  334. ap_keys = list(g_obj.apertures.keys())
  335. if ap_keys:
  336. new_apid = str(int(max(ap_keys)) + 1)
  337. else:
  338. new_apid = '10'
  339. g_obj.apertures[new_apid] = {
  340. 'type': 'R',
  341. 'size': new_ap_size,
  342. 'width': fid_size,
  343. 'height': fid_size,
  344. 'geometry': []
  345. }
  346. for geo in geo_list:
  347. geo_buff_list.append(geo)
  348. dict_el = {'follow': geo.centroid, 'solid': geo}
  349. g_obj.apertures[new_apid]['geometry'].append(deepcopy(dict_el))
  350. s_list = []
  351. if g_obj.solid_geometry:
  352. try:
  353. for poly in g_obj.solid_geometry:
  354. s_list.append(poly)
  355. except TypeError:
  356. s_list.append(g_obj.solid_geometry)
  357. for poly in geo_buff_list:
  358. s_list.append(poly)
  359. g_obj.solid_geometry = MultiPolygon(s_list)
  360. def add_soldermask_opening(self):
  361. sm_opening_dia = self.ui.fid_size_entry.get_value() * 2.0
  362. # get the Gerber object on which the Fiducial will be inserted
  363. selection_index = self.ui.sm_object_combo.currentIndex()
  364. model_index = self.app.collection.index(selection_index, 0, self.ui.sm_object_combo.rootModelIndex())
  365. try:
  366. self.sm_object = model_index.internalPointer().obj
  367. except Exception as e:
  368. log.debug("ToolFiducials.add_soldermask_opening() --> %s" % str(e))
  369. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  370. return
  371. self.sm_obj_set.add(self.sm_object.options['name'])
  372. self.add_fiducials_geo(self.click_points, g_obj=self.sm_object, fid_size=sm_opening_dia, fid_type='circular')
  373. self.sm_object.source_file = self.app.f_handlers.export_gerber(obj_name=self.sm_object.options['name'],
  374. filename=None,
  375. local_use=self.sm_object,
  376. use_thread=False)
  377. self.on_exit()
  378. def on_mouse_release(self, event):
  379. if event.button == 1:
  380. if self.app.is_legacy is False:
  381. event_pos = event.pos
  382. else:
  383. event_pos = (event.xdata, event.ydata)
  384. pos_canvas = self.canvas.translate_coords(event_pos)
  385. if self.app.grid_status():
  386. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  387. else:
  388. pos = (pos_canvas[0], pos_canvas[1])
  389. click_pt = Point([pos[0], pos[1]])
  390. self.click_points.append(
  391. (
  392. float('%.*f' % (self.decimals, click_pt.x)),
  393. float('%.*f' % (self.decimals, click_pt.y))
  394. )
  395. )
  396. self.check_points()
  397. def check_points(self):
  398. fid_type = self.fid_type_radio.get_value()
  399. if len(self.click_points) == 1:
  400. self.ui.bottom_left_coords_entry.set_value(self.click_points[0])
  401. self.app.inform.emit(_("Click to add the last fiducial. Top Right..."))
  402. if self.sec_position != 'no':
  403. if len(self.click_points) == 2:
  404. self.ui.top_right_coords_entry.set_value(self.click_points[1])
  405. self.app.inform.emit(_("Click to add the second fiducial. Top Left or Bottom Right..."))
  406. elif len(self.click_points) == 3:
  407. self.ui.sec_points_coords_entry.set_value(self.click_points[2])
  408. self.app.inform.emit('[success] %s' % _("Done. All fiducials have been added."))
  409. self.add_fiducials_geo(self.click_points, g_obj=self.grb_object, fid_type=fid_type)
  410. self.grb_object.source_file = self.app.f_handlers.export_gerber(
  411. obj_name=self.grb_object.options['name'], filename=None, local_use=self.grb_object,
  412. use_thread=False)
  413. self.on_exit()
  414. else:
  415. if len(self.click_points) == 2:
  416. self.ui.top_right_coords_entry.set_value(self.click_points[1])
  417. self.app.inform.emit('[success] %s' % _("Done. All fiducials have been added."))
  418. self.add_fiducials_geo(self.click_points, g_obj=self.grb_object, fid_type=fid_type)
  419. self.grb_object.source_file = self.app.f_handlers.export_gerber(
  420. obj_name=self.grb_object.options['name'], filename=None,
  421. local_use=self.grb_object, use_thread=False)
  422. self.on_exit()
  423. def on_mouse_move(self, event):
  424. pass
  425. def replot(self, obj, run_thread=True):
  426. def worker_task():
  427. with self.app.proc_container.new('%s...' % _("Plotting")):
  428. obj.plot()
  429. if run_thread:
  430. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  431. else:
  432. worker_task()
  433. def on_exit(self):
  434. # plot the object
  435. for ob_name in self.copper_obj_set:
  436. try:
  437. copper_obj = self.app.collection.get_by_name(name=ob_name)
  438. if len(self.copper_obj_set) > 1:
  439. self.replot(obj=copper_obj, run_thread=False)
  440. else:
  441. self.replot(obj=copper_obj)
  442. except (AttributeError, TypeError):
  443. continue
  444. # update the bounding box values
  445. try:
  446. a, b, c, d = copper_obj.bounds()
  447. copper_obj.options['xmin'] = a
  448. copper_obj.options['ymin'] = b
  449. copper_obj.options['xmax'] = c
  450. copper_obj.options['ymax'] = d
  451. except Exception as e:
  452. log.debug("ToolFiducials.on_exit() copper_obj bounds error --> %s" % str(e))
  453. for ob_name in self.sm_obj_set:
  454. try:
  455. sm_obj = self.app.collection.get_by_name(name=ob_name)
  456. if len(self.sm_obj_set) > 1:
  457. self.replot(obj=sm_obj, run_thread=False)
  458. else:
  459. self.replot(obj=sm_obj)
  460. except (AttributeError, TypeError):
  461. continue
  462. # update the bounding box values
  463. try:
  464. a, b, c, d = sm_obj.bounds()
  465. sm_obj.options['xmin'] = a
  466. sm_obj.options['ymin'] = b
  467. sm_obj.options['xmax'] = c
  468. sm_obj.options['ymax'] = d
  469. except Exception as e:
  470. log.debug("ToolFiducials.on_exit() sm_obj bounds error --> %s" % str(e))
  471. # reset the variables
  472. self.grb_object = None
  473. self.sm_object = None
  474. # Events ID
  475. self.mr = None
  476. # self.mm = None
  477. # Mouse cursor positions
  478. self.cursor_pos = (0, 0)
  479. self.first_click = False
  480. self.disconnect_event_handlers()
  481. self.app.call_source = "app"
  482. self.app.inform.emit('[success] %s' % _("Fiducials Tool exit."))
  483. def connect_event_handlers(self):
  484. if self.app.is_legacy is False:
  485. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  486. # self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  487. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  488. else:
  489. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  490. # self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  491. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  492. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  493. # self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  494. def disconnect_event_handlers(self):
  495. if self.app.is_legacy is False:
  496. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  497. # self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  498. else:
  499. self.app.plotcanvas.graph_event_disconnect(self.mr)
  500. # self.app.plotcanvas.graph_event_disconnect(self.mm)
  501. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  502. self.app.on_mouse_click_over_plot)
  503. # self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  504. # self.app.on_mouse_move_over_plot)
  505. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  506. self.app.on_mouse_click_release_over_plot)
  507. def flatten(self, geometry):
  508. """
  509. Creates a list of non-iterable linear geometry objects.
  510. :param geometry: Shapely type or list or list of list of such.
  511. Results are placed in self.flat_geometry
  512. """
  513. # ## If iterable, expand recursively.
  514. try:
  515. for geo in geometry:
  516. if geo is not None:
  517. self.flatten(geometry=geo)
  518. # ## Not iterable, do the actual indexing and add.
  519. except TypeError:
  520. self.flat_geometry.append(geometry)
  521. return self.flat_geometry
  522. class FidoUI:
  523. toolName = _("Fiducials Tool")
  524. def __init__(self, layout, app):
  525. self.app = app
  526. self.decimals = self.app.decimals
  527. self.layout = layout
  528. # ## Title
  529. title_label = QtWidgets.QLabel("%s" % self.toolName)
  530. title_label.setStyleSheet("""
  531. QLabel
  532. {
  533. font-size: 16px;
  534. font-weight: bold;
  535. }
  536. """)
  537. self.layout.addWidget(title_label)
  538. self.layout.addWidget(QtWidgets.QLabel(""))
  539. self.points_label = QtWidgets.QLabel('<b>%s:</b>' % _('Fiducials Coordinates'))
  540. self.points_label.setToolTip(
  541. _("A table with the fiducial points coordinates,\n"
  542. "in the format (x, y).")
  543. )
  544. self.layout.addWidget(self.points_label)
  545. self.points_table = FCTable()
  546. self.points_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  547. self.points_table.setColumnCount(3)
  548. self.points_table.setHorizontalHeaderLabels(
  549. [
  550. '#',
  551. _("Name"),
  552. _("Coordinates"),
  553. ]
  554. )
  555. self.points_table.setRowCount(3)
  556. row = 0
  557. flags = QtCore.Qt.ItemIsEnabled
  558. # BOTTOM LEFT
  559. id_item_1 = QtWidgets.QTableWidgetItem('%d' % 1)
  560. id_item_1.setFlags(flags)
  561. self.points_table.setItem(row, 0, id_item_1) # Tool name/id
  562. self.bottom_left_coords_lbl = QtWidgets.QTableWidgetItem('%s' % _('Bottom Left'))
  563. self.bottom_left_coords_lbl.setFlags(flags)
  564. self.points_table.setItem(row, 1, self.bottom_left_coords_lbl)
  565. self.bottom_left_coords_entry = EvalEntry()
  566. self.points_table.setCellWidget(row, 2, self.bottom_left_coords_entry)
  567. row += 1
  568. # TOP RIGHT
  569. id_item_2 = QtWidgets.QTableWidgetItem('%d' % 2)
  570. id_item_2.setFlags(flags)
  571. self.points_table.setItem(row, 0, id_item_2) # Tool name/id
  572. self.top_right_coords_lbl = QtWidgets.QTableWidgetItem('%s' % _('Top Right'))
  573. self.top_right_coords_lbl.setFlags(flags)
  574. self.points_table.setItem(row, 1, self.top_right_coords_lbl)
  575. self.top_right_coords_entry = EvalEntry()
  576. self.points_table.setCellWidget(row, 2, self.top_right_coords_entry)
  577. row += 1
  578. # Second Point
  579. self.id_item_3 = QtWidgets.QTableWidgetItem('%d' % 3)
  580. self.id_item_3.setFlags(flags)
  581. self.points_table.setItem(row, 0, self.id_item_3) # Tool name/id
  582. self.sec_point_coords_lbl = QtWidgets.QTableWidgetItem('%s' % _('Second Point'))
  583. self.sec_point_coords_lbl.setFlags(flags)
  584. self.points_table.setItem(row, 1, self.sec_point_coords_lbl)
  585. self.sec_points_coords_entry = EvalEntry()
  586. self.points_table.setCellWidget(row, 2, self.sec_points_coords_entry)
  587. vertical_header = self.points_table.verticalHeader()
  588. vertical_header.hide()
  589. self.points_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  590. horizontal_header = self.points_table.horizontalHeader()
  591. horizontal_header.setMinimumSectionSize(10)
  592. horizontal_header.setDefaultSectionSize(70)
  593. self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  594. # for x in range(4):
  595. # self.points_table.resizeColumnToContents(x)
  596. self.points_table.resizeColumnsToContents()
  597. self.points_table.resizeRowsToContents()
  598. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  599. horizontal_header.resizeSection(0, 20)
  600. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Fixed)
  601. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
  602. self.points_table.setMinimumHeight(self.points_table.getHeight() + 2)
  603. self.points_table.setMaximumHeight(self.points_table.getHeight() + 2)
  604. # remove the frame on the QLineEdit childrens of the table
  605. for row in range(self.points_table.rowCount()):
  606. self.points_table.cellWidget(row, 2).setFrame(False)
  607. self.layout.addWidget(self.points_table)
  608. separator_line = QtWidgets.QFrame()
  609. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  610. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  611. self.layout.addWidget(separator_line)
  612. # ## Grid Layout
  613. grid_lay = QtWidgets.QGridLayout()
  614. self.layout.addLayout(grid_lay)
  615. grid_lay.setColumnStretch(0, 0)
  616. grid_lay.setColumnStretch(1, 1)
  617. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _('Parameters'))
  618. self.param_label.setToolTip(
  619. _("Parameters used for this tool.")
  620. )
  621. grid_lay.addWidget(self.param_label, 0, 0, 1, 2)
  622. # DIAMETER #
  623. self.size_label = QtWidgets.QLabel('%s:' % _("Size"))
  624. self.size_label.setToolTip(
  625. _("This set the fiducial diameter if fiducial type is circular,\n"
  626. "otherwise is the size of the fiducial.\n"
  627. "The soldermask opening is double than that.")
  628. )
  629. self.fid_size_entry = FCDoubleSpinner(callback=self.confirmation_message)
  630. self.fid_size_entry.set_range(1.0000, 3.0000)
  631. self.fid_size_entry.set_precision(self.decimals)
  632. self.fid_size_entry.setWrapping(True)
  633. self.fid_size_entry.setSingleStep(0.1)
  634. grid_lay.addWidget(self.size_label, 1, 0)
  635. grid_lay.addWidget(self.fid_size_entry, 1, 1)
  636. # MARGIN #
  637. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  638. self.margin_label.setToolTip(
  639. _("Bounding box margin.")
  640. )
  641. self.margin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  642. self.margin_entry.set_range(-9999.9999, 9999.9999)
  643. self.margin_entry.set_precision(self.decimals)
  644. self.margin_entry.setSingleStep(0.1)
  645. grid_lay.addWidget(self.margin_label, 2, 0)
  646. grid_lay.addWidget(self.margin_entry, 2, 1)
  647. # Mode #
  648. self.mode_radio = RadioSet([
  649. {'label': _('Auto'), 'value': 'auto'},
  650. {"label": _("Manual"), "value": "manual"}
  651. ], stretch=False)
  652. self.mode_label = QtWidgets.QLabel(_("Mode:"))
  653. self.mode_label.setToolTip(
  654. _("- 'Auto' - automatic placement of fiducials in the corners of the bounding box.\n "
  655. "- 'Manual' - manual placement of fiducials.")
  656. )
  657. grid_lay.addWidget(self.mode_label, 3, 0)
  658. grid_lay.addWidget(self.mode_radio, 3, 1)
  659. # Position for second fiducial #
  660. self.pos_radio = RadioSet([
  661. {'label': _('Up'), 'value': 'up'},
  662. {"label": _("Down"), "value": "down"},
  663. {"label": _("None"), "value": "no"}
  664. ], stretch=False)
  665. self.pos_label = QtWidgets.QLabel('%s:' % _("Second fiducial"))
  666. self.pos_label.setToolTip(
  667. _("The position for the second fiducial.\n"
  668. "- 'Up' - the order is: bottom-left, top-left, top-right.\n"
  669. "- 'Down' - the order is: bottom-left, bottom-right, top-right.\n"
  670. "- 'None' - there is no second fiducial. The order is: bottom-left, top-right.")
  671. )
  672. grid_lay.addWidget(self.pos_label, 4, 0)
  673. grid_lay.addWidget(self.pos_radio, 4, 1)
  674. separator_line = QtWidgets.QFrame()
  675. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  676. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  677. grid_lay.addWidget(separator_line, 5, 0, 1, 2)
  678. # Fiducial type #
  679. self.fid_type_radio = RadioSet([
  680. {'label': _('Circular'), 'value': 'circular'},
  681. {"label": _("Cross"), "value": "cross"},
  682. {"label": _("Chess"), "value": "chess"}
  683. ], stretch=False)
  684. self.fid_type_label = QtWidgets.QLabel('%s:' % _("Fiducial Type"))
  685. self.fid_type_label.setToolTip(
  686. _("The type of fiducial.\n"
  687. "- 'Circular' - this is the regular fiducial.\n"
  688. "- 'Cross' - cross lines fiducial.\n"
  689. "- 'Chess' - chess pattern fiducial.")
  690. )
  691. grid_lay.addWidget(self.fid_type_label, 6, 0)
  692. grid_lay.addWidget(self.fid_type_radio, 6, 1)
  693. # Line Thickness #
  694. self.line_thickness_label = QtWidgets.QLabel('%s:' % _("Line thickness"))
  695. self.line_thickness_label.setToolTip(
  696. _("Thickness of the line that makes the fiducial.")
  697. )
  698. self.line_thickness_entry = FCDoubleSpinner(callback=self.confirmation_message)
  699. self.line_thickness_entry.set_range(0.00001, 9999.9999)
  700. self.line_thickness_entry.set_precision(self.decimals)
  701. self.line_thickness_entry.setSingleStep(0.1)
  702. grid_lay.addWidget(self.line_thickness_label, 7, 0)
  703. grid_lay.addWidget(self.line_thickness_entry, 7, 1)
  704. separator_line_1 = QtWidgets.QFrame()
  705. separator_line_1.setFrameShape(QtWidgets.QFrame.HLine)
  706. separator_line_1.setFrameShadow(QtWidgets.QFrame.Sunken)
  707. grid_lay.addWidget(separator_line_1, 8, 0, 1, 2)
  708. # Copper Gerber object
  709. self.grb_object_combo = FCComboBox()
  710. self.grb_object_combo.setModel(self.app.collection)
  711. self.grb_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  712. self.grb_object_combo.is_last = True
  713. self.grb_object_combo.obj_type = "Gerber"
  714. self.grbobj_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  715. self.grbobj_label.setToolTip(
  716. _("Gerber Object to which will be added a copper thieving.")
  717. )
  718. grid_lay.addWidget(self.grbobj_label, 9, 0, 1, 2)
  719. grid_lay.addWidget(self.grb_object_combo, 10, 0, 1, 2)
  720. # ## Insert Copper Fiducial
  721. self.add_cfid_button = QtWidgets.QPushButton(_("Add Fiducial"))
  722. self.add_cfid_button.setIcon(QtGui.QIcon(self.app.resource_location + '/fiducials_32.png'))
  723. self.add_cfid_button.setToolTip(
  724. _("Will add a polygon on the copper layer to serve as fiducial.")
  725. )
  726. self.add_cfid_button.setStyleSheet("""
  727. QPushButton
  728. {
  729. font-weight: bold;
  730. }
  731. """)
  732. grid_lay.addWidget(self.add_cfid_button, 11, 0, 1, 2)
  733. separator_line_2 = QtWidgets.QFrame()
  734. separator_line_2.setFrameShape(QtWidgets.QFrame.HLine)
  735. separator_line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
  736. grid_lay.addWidget(separator_line_2, 12, 0, 1, 2)
  737. # Soldermask Gerber object #
  738. self.sm_object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Soldermask Gerber"))
  739. self.sm_object_label.setToolTip(
  740. _("The Soldermask Gerber object.")
  741. )
  742. self.sm_object_combo = FCComboBox()
  743. self.sm_object_combo.setModel(self.app.collection)
  744. self.sm_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  745. self.sm_object_combo.is_last = True
  746. self.sm_object_combo.obj_type = "Gerber"
  747. grid_lay.addWidget(self.sm_object_label, 13, 0, 1, 2)
  748. grid_lay.addWidget(self.sm_object_combo, 14, 0, 1, 2)
  749. # ## Insert Soldermask opening for Fiducial
  750. self.add_sm_opening_button = QtWidgets.QPushButton(_("Add Soldermask Opening"))
  751. self.add_sm_opening_button.setToolTip(
  752. _("Will add a polygon on the soldermask layer\n"
  753. "to serve as fiducial opening.\n"
  754. "The diameter is always double of the diameter\n"
  755. "for the copper fiducial.")
  756. )
  757. self.add_sm_opening_button.setStyleSheet("""
  758. QPushButton
  759. {
  760. font-weight: bold;
  761. }
  762. """)
  763. grid_lay.addWidget(self.add_sm_opening_button, 15, 0, 1, 2)
  764. self.layout.addStretch()
  765. # ## Reset Tool
  766. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  767. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  768. self.reset_button.setToolTip(
  769. _("Will reset the tool parameters.")
  770. )
  771. self.reset_button.setStyleSheet("""
  772. QPushButton
  773. {
  774. font-weight: bold;
  775. }
  776. """)
  777. self.layout.addWidget(self.reset_button)
  778. # #################################### FINSIHED GUI ###########################
  779. # #############################################################################
  780. def confirmation_message(self, accepted, minval, maxval):
  781. if accepted is False:
  782. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  783. self.decimals,
  784. minval,
  785. self.decimals,
  786. maxval), False)
  787. else:
  788. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  789. def confirmation_message_int(self, accepted, minval, maxval):
  790. if accepted is False:
  791. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  792. (_("Edited value is out of range"), minval, maxval), False)
  793. else:
  794. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)