ToolCutOut.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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. self.flat_geometry = []
  233. ## Signals
  234. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  235. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  236. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  237. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  238. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  239. def on_type_obj_index_changed(self, index):
  240. obj_type = self.type_obj_combo.currentIndex()
  241. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  242. self.obj_combo.setCurrentIndex(0)
  243. def run(self, toggle=True):
  244. self.app.report_usage("ToolCutOut()")
  245. if toggle:
  246. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  247. if self.app.ui.splitter.sizes()[0] == 0:
  248. self.app.ui.splitter.setSizes([1, 1])
  249. else:
  250. try:
  251. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  252. self.app.ui.splitter.setSizes([0, 1])
  253. except AttributeError:
  254. pass
  255. else:
  256. if self.app.ui.splitter.sizes()[0] == 0:
  257. self.app.ui.splitter.setSizes([1, 1])
  258. FlatCAMTool.run(self)
  259. self.set_tool_ui()
  260. self.app.ui.notebook.setTabText(2, "Cutout Tool")
  261. def install(self, icon=None, separator=None, **kwargs):
  262. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  263. def set_tool_ui(self):
  264. self.reset_fields()
  265. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  266. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  267. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  268. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  269. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  270. self.gapFinished.connect(self.on_gap_finished)
  271. def on_freeform_cutout(self):
  272. def subtract_rectangle(obj_, x0, y0, x1, y1):
  273. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  274. obj_.subtract_polygon(pts)
  275. name = self.obj_combo.currentText()
  276. # Get source object.
  277. try:
  278. cutout_obj = self.app.collection.get_by_name(str(name))
  279. except:
  280. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  281. return "Could not retrieve object: %s" % name
  282. if cutout_obj is None:
  283. self.app.inform.emit(_("[ERROR_NOTCL] There is no object selected for Cutout.\nSelect one and try again."))
  284. return
  285. try:
  286. dia = float(self.dia.get_value())
  287. except ValueError:
  288. # try to convert comma to decimal point. if it's still not working error message and return
  289. try:
  290. dia = float(self.dia.get_value().replace(',', '.'))
  291. except ValueError:
  292. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  293. "Add it and retry."))
  294. return
  295. if 0 in {dia}:
  296. self.app.inform.emit(_("[WARNING_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  297. return "Tool Diameter is zero value. Change it to a positive real number."
  298. try:
  299. margin = float(self.margin.get_value())
  300. except ValueError:
  301. # try to convert comma to decimal point. if it's still not working error message and return
  302. try:
  303. margin = float(self.margin.get_value().replace(',', '.'))
  304. except ValueError:
  305. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  306. "Add it and retry."))
  307. return
  308. try:
  309. gapsize = float(self.gapsize.get_value())
  310. except ValueError:
  311. # try to convert comma to decimal point. if it's still not working error message and return
  312. try:
  313. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  314. except ValueError:
  315. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  316. "Add it and retry."))
  317. return
  318. try:
  319. gaps = self.gaps.get_value()
  320. except TypeError:
  321. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  322. return
  323. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  324. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  325. "Fill in a correct value and retry. "))
  326. return
  327. if cutout_obj.multigeo is True:
  328. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  329. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  330. "and after that perform Cutout."))
  331. return
  332. convex_box = self.convex_box.get_value()
  333. # Get min and max data for each object as we just cut rectangles across X or Y
  334. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  335. px = 0.5 * (xmin + xmax) + margin
  336. py = 0.5 * (ymin + ymax) + margin
  337. lenghtx = (xmax - xmin) + (margin * 2)
  338. lenghty = (ymax - ymin) + (margin * 2)
  339. gapsize = gapsize / 2 + (dia / 2)
  340. if isinstance(cutout_obj,FlatCAMGeometry):
  341. # rename the obj name so it can be identified as cutout
  342. cutout_obj.options["name"] += "_cutout"
  343. else:
  344. def geo_init(geo_obj, app_obj):
  345. if convex_box:
  346. geo = cutout_obj.solid_geometry.convex_hull
  347. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  348. else:
  349. geo = cutout_obj.solid_geometry
  350. geo = geo.buffer(margin + abs(dia / 2))
  351. if isinstance(geo, Polygon):
  352. geo_obj.solid_geometry = deepcopy(geo.exterior)
  353. elif isinstance(geo, MultiPolygon):
  354. solid_geo = []
  355. for poly in geo:
  356. solid_geo.append(poly.exterior)
  357. geo_obj.solid_geometry = deepcopy(solid_geo)
  358. outname = cutout_obj.options["name"] + "_cutout"
  359. self.app.new_object('geometry', outname, geo_init)
  360. cutout_obj = self.app.collection.get_by_name(outname)
  361. if gaps == '8' or gaps == '2LR':
  362. subtract_rectangle(cutout_obj,
  363. xmin - gapsize, # botleft_x
  364. py - gapsize + lenghty / 4, # botleft_y
  365. xmax + gapsize, # topright_x
  366. py + gapsize + lenghty / 4) # topright_y
  367. subtract_rectangle(cutout_obj,
  368. xmin - gapsize,
  369. py - gapsize - lenghty / 4,
  370. xmax + gapsize,
  371. py + gapsize - lenghty / 4)
  372. if gaps == '8' or gaps == '2TB':
  373. subtract_rectangle(cutout_obj,
  374. px - gapsize + lenghtx / 4,
  375. ymin - gapsize,
  376. px + gapsize + lenghtx / 4,
  377. ymax + gapsize)
  378. subtract_rectangle(cutout_obj,
  379. px - gapsize - lenghtx / 4,
  380. ymin - gapsize,
  381. px + gapsize - lenghtx / 4,
  382. ymax + gapsize)
  383. if gaps == '4' or gaps == 'LR':
  384. subtract_rectangle(cutout_obj,
  385. xmin - gapsize,
  386. py - gapsize,
  387. xmax + gapsize,
  388. py + gapsize)
  389. if gaps == '4' or gaps == 'TB':
  390. subtract_rectangle(cutout_obj,
  391. px - gapsize,
  392. ymin - gapsize,
  393. px + gapsize,
  394. ymax + gapsize)
  395. cutout_obj.plot()
  396. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  397. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  398. self.app.should_we_save = True
  399. def on_rectangular_cutout(self):
  400. def subtract_rectangle(obj_, x0, y0, x1, y1):
  401. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  402. obj_.subtract_polygon(pts)
  403. name = self.obj_combo.currentText()
  404. # Get source object.
  405. try:
  406. cutout_obj = self.app.collection.get_by_name(str(name))
  407. except:
  408. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  409. return "Could not retrieve object: %s" % name
  410. if cutout_obj is None:
  411. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % cutout_obj)
  412. try:
  413. dia = float(self.dia.get_value())
  414. except ValueError:
  415. # try to convert comma to decimal point. if it's still not working error message and return
  416. try:
  417. dia = float(self.dia.get_value().replace(',', '.'))
  418. except ValueError:
  419. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  420. "Add it and retry."))
  421. return
  422. if 0 in {dia}:
  423. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  424. return "Tool Diameter is zero value. Change it to a positive real number."
  425. try:
  426. margin = float(self.margin.get_value())
  427. except ValueError:
  428. # try to convert comma to decimal point. if it's still not working error message and return
  429. try:
  430. margin = float(self.margin.get_value().replace(',', '.'))
  431. except ValueError:
  432. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  433. "Add it and retry."))
  434. return
  435. try:
  436. gapsize = float(self.gapsize.get_value())
  437. except ValueError:
  438. # try to convert comma to decimal point. if it's still not working error message and return
  439. try:
  440. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  441. except ValueError:
  442. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  443. "Add it and retry."))
  444. return
  445. try:
  446. gaps = self.gaps.get_value()
  447. except TypeError:
  448. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  449. return
  450. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  451. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  452. "Fill in a correct value and retry. "))
  453. return
  454. if cutout_obj.multigeo is True:
  455. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  456. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  457. "and after that perform Cutout."))
  458. return
  459. # Get min and max data for each object as we just cut rectangles across X or Y
  460. if isinstance(cutout_obj.solid_geometry, Polygon):
  461. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  462. geo = box(xmin, ymin, xmax, ymax)
  463. elif isinstance(cutout_obj.solid_geometry, MultiPolygon):
  464. geo = []
  465. for poly in cutout_obj.solid_geometry:
  466. xmin, ymin, xmax, ymax = poly.bounds
  467. poly_geo = box(xmin, ymin, xmax, ymax)
  468. geo.append(poly_geo)
  469. px = 0.5 * (xmin + xmax) + margin
  470. py = 0.5 * (ymin + ymax) + margin
  471. lenghtx = (xmax - xmin) + (margin * 2)
  472. lenghty = (ymax - ymin) + (margin * 2)
  473. gapsize = gapsize / 2 + (dia / 2)
  474. def geo_init(geo_obj, app_obj):
  475. if isinstance(geo, list):
  476. solid_geo = []
  477. for subgeo in geo:
  478. solid_geo.append(subgeo.buffer(margin + abs(dia / 2)))
  479. geo_obj.solid_geometry = deepcopy(solid_geo)
  480. else:
  481. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  482. outname = cutout_obj.options["name"] + "_cutout"
  483. self.app.new_object('geometry', outname, geo_init)
  484. cutout_obj = self.app.collection.get_by_name(outname)
  485. if gaps == '8' or gaps == '2LR':
  486. subtract_rectangle(cutout_obj,
  487. xmin - gapsize, # botleft_x
  488. py - gapsize + lenghty / 4, # botleft_y
  489. xmax + gapsize, # topright_x
  490. py + gapsize + lenghty / 4) # topright_y
  491. subtract_rectangle(cutout_obj,
  492. xmin - gapsize,
  493. py - gapsize - lenghty / 4,
  494. xmax + gapsize,
  495. py + gapsize - lenghty / 4)
  496. if gaps == '8' or gaps == '2TB':
  497. subtract_rectangle(cutout_obj,
  498. px - gapsize + lenghtx / 4,
  499. ymin - gapsize,
  500. px + gapsize + lenghtx / 4,
  501. ymax + gapsize)
  502. subtract_rectangle(cutout_obj,
  503. px - gapsize - lenghtx / 4,
  504. ymin - gapsize,
  505. px + gapsize - lenghtx / 4,
  506. ymax + gapsize)
  507. if gaps == '4' or gaps == 'LR':
  508. subtract_rectangle(cutout_obj,
  509. xmin - gapsize,
  510. py - gapsize,
  511. xmax + gapsize,
  512. py + gapsize)
  513. if gaps == '4' or gaps == 'TB':
  514. subtract_rectangle(cutout_obj,
  515. px - gapsize,
  516. ymin - gapsize,
  517. px + gapsize,
  518. ymax + gapsize)
  519. cutout_obj.plot()
  520. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  521. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  522. self.app.should_we_save = True
  523. def on_manual_gap_click(self):
  524. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  525. self.app.geo_editor.tool_shape.enabled = True
  526. try:
  527. self.cutting_dia = float(self.dia.get_value())
  528. except ValueError:
  529. # try to convert comma to decimal point. if it's still not working error message and return
  530. try:
  531. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  532. except ValueError:
  533. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  534. "Add it and retry."))
  535. return
  536. if 0 in {self.cutting_dia}:
  537. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  538. return "Tool Diameter is zero value. Change it to a positive real number."
  539. try:
  540. self.cutting_gapsize = float(self.gapsize.get_value())
  541. except ValueError:
  542. # try to convert comma to decimal point. if it's still not working error message and return
  543. try:
  544. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  545. except ValueError:
  546. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  547. "Add it and retry."))
  548. return
  549. self.app.plotcanvas.vis_disconnect('key_press', self.app.ui.keyPressEvent)
  550. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  551. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  552. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  553. self.app.plotcanvas.vis_connect('key_press', self.on_key_press)
  554. self.app.plotcanvas.vis_connect('mouse_move', self.on_mouse_move)
  555. self.app.plotcanvas.vis_connect('mouse_release', self.doit)
  556. # To be called after clicking on the plot.
  557. def doit(self, event):
  558. # do paint single only for left mouse clicks
  559. if event.button == 1:
  560. self.app.inform.emit(_("Making manual bridge gap..."))
  561. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  562. self.on_manual_cutout(click_pos=pos)
  563. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  564. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  565. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  566. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  567. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  568. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  569. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  570. self.app.geo_editor.tool_shape.clear(update=True)
  571. self.app.geo_editor.tool_shape.enabled = False
  572. self.gapFinished.emit()
  573. def on_manual_cutout(self, click_pos):
  574. name = self.man_object_combo.currentText()
  575. # Get source object.
  576. try:
  577. cutout_obj = self.app.collection.get_by_name(str(name))
  578. except:
  579. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Geometry object: %s") % name)
  580. return "Could not retrieve object: %s" % name
  581. if cutout_obj is None:
  582. self.app.inform.emit(_("[ERROR_NOTCL] Geometry object for manual cutout not found: %s") % cutout_obj)
  583. return
  584. # use the snapped position as reference
  585. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  586. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  587. cutout_obj.subtract_polygon(cut_poly)
  588. cutout_obj.plot()
  589. self.app.inform.emit(_("[success] Added manual Bridge Gap."))
  590. self.app.should_we_save = True
  591. def on_gap_finished(self):
  592. # if CTRL key modifier is pressed then repeat the bridge gap cut
  593. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  594. if key_modifier == Qt.ControlModifier:
  595. self.on_manual_gap_click()
  596. def on_manual_geo(self):
  597. name = self.obj_combo.currentText()
  598. # Get source object.
  599. try:
  600. cutout_obj = self.app.collection.get_by_name(str(name))
  601. except:
  602. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Gerber object: %s") % name)
  603. return "Could not retrieve object: %s" % name
  604. if cutout_obj is None:
  605. self.app.inform.emit(_("[ERROR_NOTCL] There is no Gerber object selected for Cutout.\n"
  606. "Select one and try again."))
  607. return
  608. if not isinstance(cutout_obj, FlatCAMGerber):
  609. self.app.inform.emit(_("[ERROR_NOTCL] The selected object has to be of Gerber type.\n"
  610. "Select a Gerber file and try again."))
  611. return
  612. try:
  613. dia = float(self.dia.get_value())
  614. except ValueError:
  615. # try to convert comma to decimal point. if it's still not working error message and return
  616. try:
  617. dia = float(self.dia.get_value().replace(',', '.'))
  618. except ValueError:
  619. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  620. "Add it and retry."))
  621. return
  622. if 0 in {dia}:
  623. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  624. return "Tool Diameter is zero value. Change it to a positive real number."
  625. try:
  626. margin = float(self.margin.get_value())
  627. except ValueError:
  628. # try to convert comma to decimal point. if it's still not working error message and return
  629. try:
  630. margin = float(self.margin.get_value().replace(',', '.'))
  631. except ValueError:
  632. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  633. "Add it and retry."))
  634. return
  635. convex_box = self.convex_box.get_value()
  636. def geo_init(geo_obj, app_obj):
  637. if convex_box:
  638. geo = cutout_obj.solid_geometry.convex_hull
  639. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  640. else:
  641. geo = cutout_obj.solid_geometry
  642. geo = geo.buffer(margin + abs(dia / 2))
  643. if isinstance(geo, Polygon):
  644. geo_obj.solid_geometry = geo.exterior
  645. elif isinstance(geo, MultiPolygon):
  646. solid_geo = []
  647. for poly in geo:
  648. solid_geo.append(poly.exterior)
  649. geo_obj.solid_geometry = deepcopy(solid_geo)
  650. outname = cutout_obj.options["name"] + "_cutout"
  651. self.app.new_object('geometry', outname, geo_init)
  652. def cutting_geo(self, pos):
  653. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  654. # cutting area definition
  655. orig_x = pos[0]
  656. orig_y = pos[1]
  657. xmin = orig_x - offset
  658. ymin = orig_y - offset
  659. xmax = orig_x + offset
  660. ymax = orig_y + offset
  661. cut_poly = box(xmin, ymin, xmax, ymax)
  662. return cut_poly
  663. def on_mouse_move(self, event):
  664. self.app.on_mouse_move_over_plot(event=event)
  665. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  666. event.xdata, event.ydata = pos[0], pos[1]
  667. try:
  668. x = float(event.xdata)
  669. y = float(event.ydata)
  670. except TypeError:
  671. return
  672. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  673. geo = self.cutting_geo(pos=(snap_x, snap_y))
  674. # Remove any previous utility shape
  675. self.app.geo_editor.tool_shape.clear(update=True)
  676. self.draw_utility_geometry(geo=geo)
  677. def draw_utility_geometry(self, geo):
  678. self.app.geo_editor.tool_shape.add(
  679. shape=geo,
  680. color=(self.app.defaults["global_draw_color"] + '80'),
  681. update=False,
  682. layer=0,
  683. tolerance=None)
  684. self.app.geo_editor.tool_shape.redraw()
  685. def on_key_press(self, event):
  686. # events out of the self.app.collection view (it's about Project Tab) are of type int
  687. if type(event) is int:
  688. key = event
  689. # events from the GUI are of type QKeyEvent
  690. elif type(event) == QtGui.QKeyEvent:
  691. key = event.key()
  692. # events from Vispy are of type KeyEvent
  693. else:
  694. key = event.key
  695. # Escape = Deselect All
  696. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  697. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  698. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  699. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  700. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  701. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  702. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  703. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  704. # Remove any previous utility shape
  705. self.app.geo_editor.tool_shape.clear(update=True)
  706. self.app.geo_editor.tool_shape.enabled = False
  707. def flatten(self, geometry=None, reset=True, pathonly=False):
  708. """
  709. Creates a list of non-iterable linear geometry objects.
  710. Polygons are expanded into its exterior and interiors if specified.
  711. Results are placed in self.flat_geometry
  712. :param geometry: Shapely type or list or list of list of such.
  713. :param reset: Clears the contents of self.flat_geometry.
  714. :param pathonly: Expands polygons into linear elements.
  715. """
  716. if geometry is None:
  717. geometry = self.solid_geometry
  718. if reset:
  719. self.flat_geometry = []
  720. ## If iterable, expand recursively.
  721. try:
  722. for geo in geometry:
  723. if geo is not None:
  724. self.flatten(geometry=geo,
  725. reset=False,
  726. pathonly=pathonly)
  727. ## Not iterable, do the actual indexing and add.
  728. except TypeError:
  729. if pathonly and type(geometry) == Polygon:
  730. self.flat_geometry.append(geometry.exterior)
  731. self.flatten(geometry=geometry.interiors,
  732. reset=False,
  733. pathonly=True)
  734. else:
  735. self.flat_geometry.append(geometry)
  736. return self.flat_geometry
  737. def subtract_poly_from_geo(self, solid_geo, points):
  738. """
  739. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  740. i.e. it converts polygons into paths.
  741. :param points: The vertices of the polygon.
  742. :param geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  743. :return: none
  744. """
  745. # pathonly should be allways True, otherwise polygons are not subtracted
  746. flat_geometry = self.flatten(geometry=solid_geo, pathonly=True)
  747. log.debug("%d paths" % len(flat_geometry))
  748. polygon = Polygon(points)
  749. toolgeo = cascaded_union(polygon)
  750. diffs = []
  751. for target in flat_geometry:
  752. if type(target) == LineString or type(target) == LinearRing:
  753. diffs.append(target.difference(toolgeo))
  754. else:
  755. log.warning("Not implemented.")
  756. return cascaded_union(diffs)
  757. def reset_fields(self):
  758. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))