ToolCutOut.py 32 KB

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