ToolCutOut.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. from FlatCAMTool import FlatCAMTool
  2. from ObjectCollection import *
  3. from FlatCAMApp import *
  4. from shapely.geometry import box
  5. import gettext
  6. import FlatCAMTranslation as fcTranslate
  7. fcTranslate.apply_language('strings')
  8. import builtins
  9. if '_' not in builtins.__dict__:
  10. _ = gettext.gettext
  11. class CutOut(FlatCAMTool):
  12. toolName = _("Cutout PCB")
  13. gapFinished = pyqtSignal()
  14. def __init__(self, app):
  15. FlatCAMTool.__init__(self, app)
  16. self.app = app
  17. self.canvas = app.plotcanvas
  18. ## Title
  19. title_label = QtWidgets.QLabel("%s" % self.toolName)
  20. title_label.setStyleSheet("""
  21. QLabel
  22. {
  23. font-size: 16px;
  24. font-weight: bold;
  25. }
  26. """)
  27. self.layout.addWidget(title_label)
  28. ## Form Layout
  29. form_layout = QtWidgets.QFormLayout()
  30. self.layout.addLayout(form_layout)
  31. ## Type of object to be cutout
  32. self.type_obj_combo = QtWidgets.QComboBox()
  33. self.type_obj_combo.addItem("Gerber")
  34. self.type_obj_combo.addItem("Excellon")
  35. self.type_obj_combo.addItem("Geometry")
  36. # we get rid of item1 ("Excellon") as it is not suitable for creating film
  37. self.type_obj_combo.view().setRowHidden(1, True)
  38. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  39. # self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  40. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  41. self.type_obj_combo_label = QtWidgets.QLabel(_("Obj Type:"))
  42. self.type_obj_combo_label.setToolTip(
  43. _("Specify the type of object to be cutout.\n"
  44. "It can be of type: Gerber or Geometry.\n"
  45. "What is selected here will dictate the kind\n"
  46. "of objects that will populate the 'Object' combobox.")
  47. )
  48. self.type_obj_combo_label.setFixedWidth(60)
  49. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  50. ## Object to be cutout
  51. self.obj_combo = QtWidgets.QComboBox()
  52. self.obj_combo.setModel(self.app.collection)
  53. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  54. self.obj_combo.setCurrentIndex(1)
  55. self.object_label = QtWidgets.QLabel(_("Object:"))
  56. self.object_label.setToolTip(
  57. _("Object to be cutout. ")
  58. )
  59. form_layout.addRow(self.object_label, self.obj_combo)
  60. # Tool Diameter
  61. self.dia = FCEntry()
  62. self.dia_label = QtWidgets.QLabel(_("Tool Dia:"))
  63. self.dia_label.setToolTip(
  64. _( "Diameter of the tool used to cutout\n"
  65. "the PCB shape out of the surrounding material.")
  66. )
  67. form_layout.addRow(self.dia_label, self.dia)
  68. # Margin
  69. self.margin = FCEntry()
  70. self.margin_label = QtWidgets.QLabel(_("Margin:"))
  71. self.margin_label.setToolTip(
  72. _( "Margin over bounds. A positive value here\n"
  73. "will make the cutout of the PCB further from\n"
  74. "the actual PCB border")
  75. )
  76. form_layout.addRow(self.margin_label, self.margin)
  77. # Gapsize
  78. self.gapsize = FCEntry()
  79. self.gapsize_label = QtWidgets.QLabel(_("Gap size:"))
  80. self.gapsize_label.setToolTip(
  81. _( "The size of the bridge gaps in the cutout\n"
  82. "used to keep the board connected to\n"
  83. "the surrounding material (the one \n"
  84. "from which the PCB is cutout).")
  85. )
  86. form_layout.addRow(self.gapsize_label, self.gapsize)
  87. # How gaps wil be rendered:
  88. # lr - left + right
  89. # tb - top + bottom
  90. # 4 - left + right +top + bottom
  91. # 2lr - 2*left + 2*right
  92. # 2tb - 2*top + 2*bottom
  93. # 8 - 2*left + 2*right +2*top + 2*bottom
  94. # Surrounding convex box shape
  95. self.convex_box = FCCheckBox()
  96. self.convex_box_label = QtWidgets.QLabel(_("Convex Sh.:"))
  97. self.convex_box_label.setToolTip(
  98. _("Create a convex shape surrounding the entire PCB.")
  99. )
  100. form_layout.addRow(self.convex_box_label, self.convex_box)
  101. ## Title2
  102. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  103. title_param_label.setToolTip(
  104. _("This section handle creation of automatic bridge gaps.")
  105. )
  106. self.layout.addWidget(title_param_label)
  107. ## Form Layout
  108. form_layout_2 = QtWidgets.QFormLayout()
  109. self.layout.addLayout(form_layout_2)
  110. # Gaps
  111. gaps_label = QtWidgets.QLabel(_('Gaps:'))
  112. gaps_label.setToolTip(
  113. _("Number of gaps used for the Automatic cutout.\n"
  114. "There can be maximum 8 bridges/gaps.\n"
  115. "The choices are:\n"
  116. "- lr - left + right\n"
  117. "- tb - top + bottom\n"
  118. "- 4 - left + right +top + bottom\n"
  119. "- 2lr - 2*left + 2*right\n"
  120. "- 2tb - 2*top + 2*bottom\n"
  121. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  122. )
  123. gaps_label.setFixedWidth(60)
  124. self.gaps = FCComboBox()
  125. gaps_items = ['LR', 'TB', '4', '2LR', '2TB', '8']
  126. for it in gaps_items:
  127. self.gaps.addItem(it)
  128. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  129. form_layout_2.addRow(gaps_label, self.gaps)
  130. ## Buttons
  131. hlay = QtWidgets.QHBoxLayout()
  132. self.layout.addLayout(hlay)
  133. title_ff_label = QtWidgets.QLabel("<b>%s</b>" % _('FreeForm:'))
  134. title_ff_label.setToolTip(
  135. _("The cutout shape can be of ny shape.\n"
  136. "Useful when the PCB has a non-rectangular shape.")
  137. )
  138. hlay.addWidget(title_ff_label)
  139. hlay.addStretch()
  140. self.ff_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  141. self.ff_cutout_object_btn.setToolTip(
  142. _("Cutout the selected object.\n"
  143. "The cutout shape can be of any shape.\n"
  144. "Useful when the PCB has a non-rectangular shape.")
  145. )
  146. hlay.addWidget(self.ff_cutout_object_btn)
  147. hlay2 = QtWidgets.QHBoxLayout()
  148. self.layout.addLayout(hlay2)
  149. title_rct_label = QtWidgets.QLabel("<b>%s</b>" % _('Rectangular:'))
  150. title_rct_label.setToolTip(
  151. _("The resulting cutout shape is\n"
  152. "always a rectangle shape and it will be\n"
  153. "the bounding box of the Object.")
  154. )
  155. hlay2.addWidget(title_rct_label)
  156. hlay2.addStretch()
  157. self.rect_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  158. self.rect_cutout_object_btn.setToolTip(
  159. _("Cutout the selected object.\n"
  160. "The resulting cutout shape is\n"
  161. "always a rectangle shape and it will be\n"
  162. "the bounding box of the Object.")
  163. )
  164. hlay2.addWidget(self.rect_cutout_object_btn)
  165. ## Title5
  166. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  167. title_manual_label.setToolTip(
  168. _("This section handle creation of manual bridge gaps.\n"
  169. "This is done by mouse clicking on the perimeter of the\n"
  170. "Geometry object that is used as a cutout object. ")
  171. )
  172. self.layout.addWidget(title_manual_label)
  173. ## Form Layout
  174. form_layout_3 = QtWidgets.QFormLayout()
  175. self.layout.addLayout(form_layout_3)
  176. ## Manual Geo Object
  177. self.man_object_combo = QtWidgets.QComboBox()
  178. self.man_object_combo.setModel(self.app.collection)
  179. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  180. self.man_object_combo.setCurrentIndex(1)
  181. self.man_object_label = QtWidgets.QLabel(_("Geo Obj:"))
  182. self.man_object_label.setToolTip(
  183. _("Geometry object used to create the manual cutout.")
  184. )
  185. self.man_object_label.setFixedWidth(60)
  186. # e_lab_0 = QtWidgets.QLabel('')
  187. form_layout_3.addRow(self.man_object_label, self.man_object_combo)
  188. # form_layout_3.addRow(e_lab_0)
  189. hlay3 = QtWidgets.QHBoxLayout()
  190. self.layout.addLayout(hlay3)
  191. self.man_geo_label = QtWidgets.QLabel(_("Manual Geo:"))
  192. self.man_geo_label.setToolTip(
  193. _("If the object to be cutout is a Gerber\n"
  194. "first create a Geometry that surrounds it,\n"
  195. "to be used as the cutout, if one doesn't exist yet.\n"
  196. "Select the source Gerber file in the top object combobox.")
  197. )
  198. hlay3.addWidget(self.man_geo_label)
  199. hlay3.addStretch()
  200. self.man_geo_creation_btn = QtWidgets.QPushButton(_("Generate Geo"))
  201. self.man_geo_creation_btn.setToolTip(
  202. _("If the object to be cutout is a Gerber\n"
  203. "first create a Geometry that surrounds it,\n"
  204. "to be used as the cutout, if one doesn't exist yet.\n"
  205. "Select the source Gerber file in the top object combobox.")
  206. )
  207. hlay3.addWidget(self.man_geo_creation_btn)
  208. hlay4 = QtWidgets.QHBoxLayout()
  209. self.layout.addLayout(hlay4)
  210. self.man_bridge_gaps_label = QtWidgets.QLabel(_("Manual Add Bridge Gaps:"))
  211. self.man_bridge_gaps_label.setToolTip(
  212. _("Use the left mouse button (LMB) click\n"
  213. "to create a bridge gap to separate the PCB from\n"
  214. "the surrounding material.")
  215. )
  216. hlay4.addWidget(self.man_bridge_gaps_label)
  217. hlay4.addStretch()
  218. self.man_gaps_creation_btn = QtWidgets.QPushButton(_("Generate Gap"))
  219. self.man_gaps_creation_btn.setToolTip(
  220. _("Use the left mouse button (LMB) click\n"
  221. "to create a bridge gap to separate the PCB from\n"
  222. "the surrounding material.\n"
  223. "The LMB click has to be done on the perimeter of\n"
  224. "the Geometry object used as a cutout geometry.")
  225. )
  226. hlay4.addWidget(self.man_gaps_creation_btn)
  227. self.layout.addStretch()
  228. self.cutting_gapsize = 0.0
  229. self.cutting_dia = 0.0
  230. # true if we want to repeat the gap without clicking again on the button
  231. self.repeat_gap = False
  232. ## Signals
  233. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  234. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  235. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  236. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  237. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  238. def on_type_obj_index_changed(self, index):
  239. obj_type = self.type_obj_combo.currentIndex()
  240. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  241. self.obj_combo.setCurrentIndex(0)
  242. def run(self, toggle=True):
  243. self.app.report_usage("ToolCutOut()")
  244. if toggle:
  245. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  246. if self.app.ui.splitter.sizes()[0] == 0:
  247. self.app.ui.splitter.setSizes([1, 1])
  248. else:
  249. try:
  250. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  251. self.app.ui.splitter.setSizes([0, 1])
  252. except AttributeError:
  253. pass
  254. else:
  255. if self.app.ui.splitter.sizes()[0] == 0:
  256. self.app.ui.splitter.setSizes([1, 1])
  257. FlatCAMTool.run(self)
  258. self.set_tool_ui()
  259. self.app.ui.notebook.setTabText(2, "Cutout Tool")
  260. def install(self, icon=None, separator=None, **kwargs):
  261. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  262. def set_tool_ui(self):
  263. self.reset_fields()
  264. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  265. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  266. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  267. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  268. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  269. self.gapFinished.connect(self.on_gap_finished)
  270. def on_freeform_cutout(self):
  271. def subtract_rectangle(obj_, x0, y0, x1, y1):
  272. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  273. obj_.subtract_polygon(pts)
  274. name = self.obj_combo.currentText()
  275. # Get source object.
  276. try:
  277. cutout_obj = self.app.collection.get_by_name(str(name))
  278. except:
  279. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  280. return "Could not retrieve object: %s" % name
  281. if cutout_obj is None:
  282. self.app.inform.emit(_("[ERROR_NOTCL] There is no object selected for Cutout.\nSelect one and try again."))
  283. return
  284. try:
  285. dia = float(self.dia.get_value())
  286. except ValueError:
  287. # try to convert comma to decimal point. if it's still not working error message and return
  288. try:
  289. dia = float(self.dia.get_value().replace(',', '.'))
  290. except ValueError:
  291. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  292. "Add it and retry."))
  293. return
  294. if 0 in {dia}:
  295. self.app.inform.emit(_("[WARNING_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  296. return "Tool Diameter is zero value. Change it to a positive real number."
  297. try:
  298. margin = float(self.margin.get_value())
  299. except ValueError:
  300. # try to convert comma to decimal point. if it's still not working error message and return
  301. try:
  302. margin = float(self.margin.get_value().replace(',', '.'))
  303. except ValueError:
  304. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  305. "Add it and retry."))
  306. return
  307. try:
  308. gapsize = float(self.gapsize.get_value())
  309. except ValueError:
  310. # try to convert comma to decimal point. if it's still not working error message and return
  311. try:
  312. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  313. except ValueError:
  314. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  315. "Add it and retry."))
  316. return
  317. try:
  318. gaps = self.gaps.get_value()
  319. except TypeError:
  320. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  321. return
  322. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  323. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  324. "Fill in a correct value and retry. "))
  325. return
  326. if cutout_obj.multigeo is True:
  327. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  328. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  329. "and after that perform Cutout."))
  330. return
  331. convex_box = self.convex_box.get_value()
  332. # Get min and max data for each object as we just cut rectangles across X or Y
  333. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  334. px = 0.5 * (xmin + xmax) + margin
  335. py = 0.5 * (ymin + ymax) + margin
  336. lenghtx = (xmax - xmin) + (margin * 2)
  337. lenghty = (ymax - ymin) + (margin * 2)
  338. gapsize = gapsize / 2 + (dia / 2)
  339. if isinstance(cutout_obj,FlatCAMGeometry):
  340. # rename the obj name so it can be identified as cutout
  341. cutout_obj.options["name"] += "_cutout"
  342. else:
  343. def geo_init(geo_obj, app_obj):
  344. if convex_box:
  345. geo = cutout_obj.solid_geometry.convex_hull
  346. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  347. else:
  348. geo = cutout_obj.solid_geometry
  349. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2)).exterior
  350. outname = cutout_obj.options["name"] + "_cutout"
  351. self.app.new_object('geometry', outname, geo_init)
  352. cutout_obj = self.app.collection.get_by_name(outname)
  353. if gaps == '8' or gaps == '2LR':
  354. subtract_rectangle(cutout_obj,
  355. xmin - gapsize, # botleft_x
  356. py - gapsize + lenghty / 4, # botleft_y
  357. xmax + gapsize, # topright_x
  358. py + gapsize + lenghty / 4) # topright_y
  359. subtract_rectangle(cutout_obj,
  360. xmin - gapsize,
  361. py - gapsize - lenghty / 4,
  362. xmax + gapsize,
  363. py + gapsize - lenghty / 4)
  364. if gaps == '8' or gaps == '2TB':
  365. subtract_rectangle(cutout_obj,
  366. px - gapsize + lenghtx / 4,
  367. ymin - gapsize,
  368. px + gapsize + lenghtx / 4,
  369. ymax + gapsize)
  370. subtract_rectangle(cutout_obj,
  371. px - gapsize - lenghtx / 4,
  372. ymin - gapsize,
  373. px + gapsize - lenghtx / 4,
  374. ymax + gapsize)
  375. if gaps == '4' or gaps == 'LR':
  376. subtract_rectangle(cutout_obj,
  377. xmin - gapsize,
  378. py - gapsize,
  379. xmax + gapsize,
  380. py + gapsize)
  381. if gaps == '4' or gaps == 'TB':
  382. subtract_rectangle(cutout_obj,
  383. px - gapsize,
  384. ymin - gapsize,
  385. px + gapsize,
  386. ymax + gapsize)
  387. cutout_obj.plot()
  388. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  389. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  390. self.app.should_we_save = True
  391. def on_rectangular_cutout(self):
  392. def subtract_rectangle(obj_, x0, y0, x1, y1):
  393. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  394. obj_.subtract_polygon(pts)
  395. name = self.obj_combo.currentText()
  396. # Get source object.
  397. try:
  398. cutout_obj = self.app.collection.get_by_name(str(name))
  399. except:
  400. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  401. return "Could not retrieve object: %s" % name
  402. if cutout_obj is None:
  403. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % cutout_obj)
  404. try:
  405. dia = float(self.dia.get_value())
  406. except ValueError:
  407. # try to convert comma to decimal point. if it's still not working error message and return
  408. try:
  409. dia = float(self.dia.get_value().replace(',', '.'))
  410. except ValueError:
  411. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  412. "Add it and retry."))
  413. return
  414. if 0 in {dia}:
  415. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  416. return "Tool Diameter is zero value. Change it to a positive real number."
  417. try:
  418. margin = float(self.margin.get_value())
  419. except ValueError:
  420. # try to convert comma to decimal point. if it's still not working error message and return
  421. try:
  422. margin = float(self.margin.get_value().replace(',', '.'))
  423. except ValueError:
  424. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  425. "Add it and retry."))
  426. return
  427. try:
  428. gapsize = float(self.gapsize.get_value())
  429. except ValueError:
  430. # try to convert comma to decimal point. if it's still not working error message and return
  431. try:
  432. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  433. except ValueError:
  434. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  435. "Add it and retry."))
  436. return
  437. try:
  438. gaps = self.gaps.get_value()
  439. except TypeError:
  440. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  441. return
  442. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  443. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  444. "Fill in a correct value and retry. "))
  445. return
  446. if cutout_obj.multigeo is True:
  447. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  448. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  449. "and after that perform Cutout."))
  450. return
  451. # Get min and max data for each object as we just cut rectangles across X or Y
  452. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  453. geo = box(xmin, ymin, xmax, ymax)
  454. px = 0.5 * (xmin + xmax) + margin
  455. py = 0.5 * (ymin + ymax) + margin
  456. lenghtx = (xmax - xmin) + (margin * 2)
  457. lenghty = (ymax - ymin) + (margin * 2)
  458. gapsize = gapsize / 2 + (dia / 2)
  459. def geo_init(geo_obj, app_obj):
  460. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  461. outname = cutout_obj.options["name"] + "_cutout"
  462. self.app.new_object('geometry', outname, geo_init)
  463. cutout_obj = self.app.collection.get_by_name(outname)
  464. if gaps == '8' or gaps == '2LR':
  465. subtract_rectangle(cutout_obj,
  466. xmin - gapsize, # botleft_x
  467. py - gapsize + lenghty / 4, # botleft_y
  468. xmax + gapsize, # topright_x
  469. py + gapsize + lenghty / 4) # topright_y
  470. subtract_rectangle(cutout_obj,
  471. xmin - gapsize,
  472. py - gapsize - lenghty / 4,
  473. xmax + gapsize,
  474. py + gapsize - lenghty / 4)
  475. if gaps == '8' or gaps == '2TB':
  476. subtract_rectangle(cutout_obj,
  477. px - gapsize + lenghtx / 4,
  478. ymin - gapsize,
  479. px + gapsize + lenghtx / 4,
  480. ymax + gapsize)
  481. subtract_rectangle(cutout_obj,
  482. px - gapsize - lenghtx / 4,
  483. ymin - gapsize,
  484. px + gapsize - lenghtx / 4,
  485. ymax + gapsize)
  486. if gaps == '4' or gaps == 'LR':
  487. subtract_rectangle(cutout_obj,
  488. xmin - gapsize,
  489. py - gapsize,
  490. xmax + gapsize,
  491. py + gapsize)
  492. if gaps == '4' or gaps == 'TB':
  493. subtract_rectangle(cutout_obj,
  494. px - gapsize,
  495. ymin - gapsize,
  496. px + gapsize,
  497. ymax + gapsize)
  498. cutout_obj.plot()
  499. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  500. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  501. self.app.should_we_save = True
  502. def on_manual_gap_click(self):
  503. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  504. self.app.geo_editor.tool_shape.enabled = True
  505. try:
  506. self.cutting_dia = float(self.dia.get_value())
  507. except ValueError:
  508. # try to convert comma to decimal point. if it's still not working error message and return
  509. try:
  510. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  511. except ValueError:
  512. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  513. "Add it and retry."))
  514. return
  515. if 0 in {self.cutting_dia}:
  516. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  517. return "Tool Diameter is zero value. Change it to a positive real number."
  518. try:
  519. self.cutting_gapsize = float(self.gapsize.get_value())
  520. except ValueError:
  521. # try to convert comma to decimal point. if it's still not working error message and return
  522. try:
  523. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  524. except ValueError:
  525. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  526. "Add it and retry."))
  527. return
  528. self.app.plotcanvas.vis_disconnect('key_press', self.app.ui.keyPressEvent)
  529. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  530. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  531. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  532. self.app.plotcanvas.vis_connect('key_press', self.on_key_press)
  533. self.app.plotcanvas.vis_connect('mouse_move', self.on_mouse_move)
  534. self.app.plotcanvas.vis_connect('mouse_release', self.doit)
  535. # To be called after clicking on the plot.
  536. def doit(self, event):
  537. # do paint single only for left mouse clicks
  538. if event.button == 1:
  539. self.app.inform.emit(_("Making manual bridge gap..."))
  540. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  541. self.on_manual_cutout(click_pos=pos)
  542. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  543. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  544. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  545. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  546. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  547. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  548. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  549. self.app.geo_editor.tool_shape.clear(update=True)
  550. self.app.geo_editor.tool_shape.enabled = False
  551. self.gapFinished.emit()
  552. def on_manual_cutout(self, click_pos):
  553. name = self.man_object_combo.currentText()
  554. # Get source object.
  555. try:
  556. cutout_obj = self.app.collection.get_by_name(str(name))
  557. except:
  558. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Geometry object: %s") % name)
  559. return "Could not retrieve object: %s" % name
  560. if cutout_obj is None:
  561. self.app.inform.emit(_("[ERROR_NOTCL] Geometry object for manual cutout not found: %s") % cutout_obj)
  562. return
  563. # use the snapped position as reference
  564. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  565. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  566. cutout_obj.subtract_polygon(cut_poly)
  567. cutout_obj.plot()
  568. self.app.inform.emit(_("[success] Added manual Bridge Gap."))
  569. self.app.should_we_save = True
  570. def on_gap_finished(self):
  571. # if CTRL key modifier is pressed then repeat the bridge gap cut
  572. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  573. if key_modifier == Qt.ControlModifier:
  574. self.on_manual_gap_click()
  575. def on_manual_geo(self):
  576. name = self.obj_combo.currentText()
  577. # Get source object.
  578. try:
  579. cutout_obj = self.app.collection.get_by_name(str(name))
  580. except:
  581. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Gerber object: %s") % name)
  582. return "Could not retrieve object: %s" % name
  583. if cutout_obj is None:
  584. self.app.inform.emit(_("[ERROR_NOTCL] There is no Gerber object selected for Cutout.\n"
  585. "Select one and try again."))
  586. return
  587. if not isinstance(cutout_obj, FlatCAMGerber):
  588. self.app.inform.emit(_("[ERROR_NOTCL] The selected object has to be of Gerber type.\n"
  589. "Select a Gerber file and try again."))
  590. return
  591. try:
  592. dia = float(self.dia.get_value())
  593. except ValueError:
  594. # try to convert comma to decimal point. if it's still not working error message and return
  595. try:
  596. dia = float(self.dia.get_value().replace(',', '.'))
  597. except ValueError:
  598. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  599. "Add it and retry."))
  600. return
  601. if 0 in {dia}:
  602. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  603. return "Tool Diameter is zero value. Change it to a positive real number."
  604. try:
  605. margin = float(self.margin.get_value())
  606. except ValueError:
  607. # try to convert comma to decimal point. if it's still not working error message and return
  608. try:
  609. margin = float(self.margin.get_value().replace(',', '.'))
  610. except ValueError:
  611. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  612. "Add it and retry."))
  613. return
  614. convex_box = self.convex_box.get_value()
  615. def geo_init(geo_obj, app_obj):
  616. if convex_box:
  617. geo = cutout_obj.solid_geometry.convex_hull
  618. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  619. else:
  620. geo = cutout_obj.solid_geometry
  621. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2)).exterior
  622. outname = cutout_obj.options["name"] + "_cutout"
  623. self.app.new_object('geometry', outname, geo_init)
  624. def cutting_geo(self, pos):
  625. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  626. # cutting area definition
  627. orig_x = pos[0]
  628. orig_y = pos[1]
  629. xmin = orig_x - offset
  630. ymin = orig_y - offset
  631. xmax = orig_x + offset
  632. ymax = orig_y + offset
  633. cut_poly = box(xmin, ymin, xmax, ymax)
  634. return cut_poly
  635. def on_mouse_move(self, event):
  636. self.app.on_mouse_move_over_plot(event=event)
  637. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  638. event.xdata, event.ydata = pos[0], pos[1]
  639. try:
  640. x = float(event.xdata)
  641. y = float(event.ydata)
  642. except TypeError:
  643. return
  644. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  645. geo = self.cutting_geo(pos=(snap_x, snap_y))
  646. # Remove any previous utility shape
  647. self.app.geo_editor.tool_shape.clear(update=True)
  648. self.draw_utility_geometry(geo=geo)
  649. def draw_utility_geometry(self, geo):
  650. self.app.geo_editor.tool_shape.add(
  651. shape=geo,
  652. color=(self.app.defaults["global_draw_color"] + '80'),
  653. update=False,
  654. layer=0,
  655. tolerance=None)
  656. self.app.geo_editor.tool_shape.redraw()
  657. def on_key_press(self, event):
  658. # events out of the self.app.collection view (it's about Project Tab) are of type int
  659. if type(event) is int:
  660. key = event
  661. # events from the GUI are of type QKeyEvent
  662. elif type(event) == QtGui.QKeyEvent:
  663. key = event.key()
  664. # events from Vispy are of type KeyEvent
  665. else:
  666. key = event.key
  667. # Escape = Deselect All
  668. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  669. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  670. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  671. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  672. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  673. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  674. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  675. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  676. # Remove any previous utility shape
  677. self.app.geo_editor.tool_shape.clear(update=True)
  678. self.app.geo_editor.tool_shape.enabled = False
  679. def reset_fields(self):
  680. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))