ToolCutOut.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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. import builtins
  8. fcTranslate.apply_language('strings')
  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.\n"
  99. "Used only if the source object type is Gerber.")
  100. )
  101. form_layout.addRow(self.convex_box_label, self.convex_box)
  102. # Title2
  103. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  104. title_param_label.setToolTip(
  105. _("This section handle creation of automatic bridge gaps.")
  106. )
  107. self.layout.addWidget(title_param_label)
  108. # Form Layout
  109. form_layout_2 = QtWidgets.QFormLayout()
  110. self.layout.addLayout(form_layout_2)
  111. # Gaps
  112. gaps_label = QtWidgets.QLabel(_('Gaps:'))
  113. gaps_label.setToolTip(
  114. _("Number of gaps used for the Automatic cutout.\n"
  115. "There can be maximum 8 bridges/gaps.\n"
  116. "The choices are:\n"
  117. "- lr - left + right\n"
  118. "- tb - top + bottom\n"
  119. "- 4 - left + right +top + bottom\n"
  120. "- 2lr - 2*left + 2*right\n"
  121. "- 2tb - 2*top + 2*bottom\n"
  122. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  123. )
  124. gaps_label.setFixedWidth(60)
  125. self.gaps = FCComboBox()
  126. gaps_items = ['LR', 'TB', '4', '2LR', '2TB', '8']
  127. for it in gaps_items:
  128. self.gaps.addItem(it)
  129. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  130. form_layout_2.addRow(gaps_label, self.gaps)
  131. # Buttons
  132. hlay = QtWidgets.QHBoxLayout()
  133. self.layout.addLayout(hlay)
  134. title_ff_label = QtWidgets.QLabel("<b>%s</b>" % _('FreeForm:'))
  135. title_ff_label.setToolTip(
  136. _("The cutout shape can be of ny shape.\n"
  137. "Useful when the PCB has a non-rectangular shape.")
  138. )
  139. hlay.addWidget(title_ff_label)
  140. hlay.addStretch()
  141. self.ff_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  142. self.ff_cutout_object_btn.setToolTip(
  143. _("Cutout the selected object.\n"
  144. "The cutout shape can be of any shape.\n"
  145. "Useful when the PCB has a non-rectangular shape.")
  146. )
  147. hlay.addWidget(self.ff_cutout_object_btn)
  148. hlay2 = QtWidgets.QHBoxLayout()
  149. self.layout.addLayout(hlay2)
  150. title_rct_label = QtWidgets.QLabel("<b>%s</b>" % _('Rectangular:'))
  151. title_rct_label.setToolTip(
  152. _("The resulting cutout shape is\n"
  153. "always a rectangle shape and it will be\n"
  154. "the bounding box of the Object.")
  155. )
  156. hlay2.addWidget(title_rct_label)
  157. hlay2.addStretch()
  158. self.rect_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  159. self.rect_cutout_object_btn.setToolTip(
  160. _("Cutout the selected object.\n"
  161. "The resulting cutout shape is\n"
  162. "always a rectangle shape and it will be\n"
  163. "the bounding box of the Object.")
  164. )
  165. hlay2.addWidget(self.rect_cutout_object_btn)
  166. # Title5
  167. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  168. title_manual_label.setToolTip(
  169. _("This section handle creation of manual bridge gaps.\n"
  170. "This is done by mouse clicking on the perimeter of the\n"
  171. "Geometry object that is used as a cutout object. ")
  172. )
  173. self.layout.addWidget(title_manual_label)
  174. # Form Layout
  175. form_layout_3 = QtWidgets.QFormLayout()
  176. self.layout.addLayout(form_layout_3)
  177. # Manual Geo Object
  178. self.man_object_combo = QtWidgets.QComboBox()
  179. self.man_object_combo.setModel(self.app.collection)
  180. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  181. self.man_object_combo.setCurrentIndex(1)
  182. self.man_object_label = QtWidgets.QLabel(_("Geo Obj:"))
  183. self.man_object_label.setToolTip(
  184. _("Geometry object used to create the manual cutout.")
  185. )
  186. self.man_object_label.setFixedWidth(60)
  187. # e_lab_0 = QtWidgets.QLabel('')
  188. form_layout_3.addRow(self.man_object_label, self.man_object_combo)
  189. # form_layout_3.addRow(e_lab_0)
  190. hlay3 = QtWidgets.QHBoxLayout()
  191. self.layout.addLayout(hlay3)
  192. self.man_geo_label = QtWidgets.QLabel(_("Manual Geo:"))
  193. self.man_geo_label.setToolTip(
  194. _("If the object to be cutout is a Gerber\n"
  195. "first create a Geometry that surrounds it,\n"
  196. "to be used as the cutout, if one doesn't exist yet.\n"
  197. "Select the source Gerber file in the top object combobox.")
  198. )
  199. hlay3.addWidget(self.man_geo_label)
  200. hlay3.addStretch()
  201. self.man_geo_creation_btn = QtWidgets.QPushButton(_("Generate Geo"))
  202. self.man_geo_creation_btn.setToolTip(
  203. _("If the object to be cutout is a Gerber\n"
  204. "first create a Geometry that surrounds it,\n"
  205. "to be used as the cutout, if one doesn't exist yet.\n"
  206. "Select the source Gerber file in the top object combobox.")
  207. )
  208. hlay3.addWidget(self.man_geo_creation_btn)
  209. hlay4 = QtWidgets.QHBoxLayout()
  210. self.layout.addLayout(hlay4)
  211. self.man_bridge_gaps_label = QtWidgets.QLabel(_("Manual Add Bridge Gaps:"))
  212. self.man_bridge_gaps_label.setToolTip(
  213. _("Use the left mouse button (LMB) click\n"
  214. "to create a bridge gap to separate the PCB from\n"
  215. "the surrounding material.")
  216. )
  217. hlay4.addWidget(self.man_bridge_gaps_label)
  218. hlay4.addStretch()
  219. self.man_gaps_creation_btn = QtWidgets.QPushButton(_("Generate Gap"))
  220. self.man_gaps_creation_btn.setToolTip(
  221. _("Use the left mouse button (LMB) click\n"
  222. "to create a bridge gap to separate the PCB from\n"
  223. "the surrounding material.\n"
  224. "The LMB click has to be done on the perimeter of\n"
  225. "the Geometry object used as a cutout geometry.")
  226. )
  227. hlay4.addWidget(self.man_gaps_creation_btn)
  228. self.layout.addStretch()
  229. self.cutting_gapsize = 0.0
  230. self.cutting_dia = 0.0
  231. # true if we want to repeat the gap without clicking again on the button
  232. self.repeat_gap = False
  233. self.flat_geometry = []
  234. # Signals
  235. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  236. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  237. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  238. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  239. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  240. def on_type_obj_index_changed(self, index):
  241. obj_type = self.type_obj_combo.currentIndex()
  242. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  243. self.obj_combo.setCurrentIndex(0)
  244. def run(self, toggle=True):
  245. self.app.report_usage("ToolCutOut()")
  246. if toggle:
  247. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  248. if self.app.ui.splitter.sizes()[0] == 0:
  249. self.app.ui.splitter.setSizes([1, 1])
  250. else:
  251. try:
  252. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  253. self.app.ui.splitter.setSizes([0, 1])
  254. except AttributeError:
  255. pass
  256. else:
  257. if self.app.ui.splitter.sizes()[0] == 0:
  258. self.app.ui.splitter.setSizes([1, 1])
  259. FlatCAMTool.run(self)
  260. self.set_tool_ui()
  261. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  262. def install(self, icon=None, separator=None, **kwargs):
  263. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  264. def set_tool_ui(self):
  265. self.reset_fields()
  266. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  267. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  268. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  269. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  270. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  271. self.gapFinished.connect(self.on_gap_finished)
  272. def on_freeform_cutout(self):
  273. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  274. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  275. # obj_.subtract_polygon(pts)
  276. name = self.obj_combo.currentText()
  277. # Get source object.
  278. try:
  279. cutout_obj = self.app.collection.get_by_name(str(name))
  280. except:
  281. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  282. return "Could not retrieve object: %s" % name
  283. if cutout_obj is None:
  284. self.app.inform.emit(_("[ERROR_NOTCL] There is no object selected for Cutout.\nSelect one and try again."))
  285. return
  286. try:
  287. dia = float(self.dia.get_value())
  288. except ValueError:
  289. # try to convert comma to decimal point. if it's still not working error message and return
  290. try:
  291. dia = float(self.dia.get_value().replace(',', '.'))
  292. except ValueError:
  293. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  294. "Add it and retry."))
  295. return
  296. if 0 in {dia}:
  297. self.app.inform.emit(_("[WARNING_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  298. return "Tool Diameter is zero value. Change it to a positive real number."
  299. try:
  300. margin = float(self.margin.get_value())
  301. except ValueError:
  302. # try to convert comma to decimal point. if it's still not working error message and return
  303. try:
  304. margin = float(self.margin.get_value().replace(',', '.'))
  305. except ValueError:
  306. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  307. "Add it and retry."))
  308. return
  309. try:
  310. gapsize = float(self.gapsize.get_value())
  311. except ValueError:
  312. # try to convert comma to decimal point. if it's still not working error message and return
  313. try:
  314. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  315. except ValueError:
  316. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  317. "Add it and retry."))
  318. return
  319. try:
  320. gaps = self.gaps.get_value()
  321. except TypeError:
  322. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  323. return
  324. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  325. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  326. "Fill in a correct value and retry. "))
  327. return
  328. if cutout_obj.multigeo is True:
  329. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  330. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  331. "and after that perform Cutout."))
  332. return
  333. convex_box = self.convex_box.get_value()
  334. gapsize = gapsize / 2 + (dia / 2)
  335. def geo_init(geo_obj, app_obj):
  336. solid_geo = []
  337. if isinstance(cutout_obj, FlatCAMGerber):
  338. if convex_box:
  339. object_geo = cutout_obj.solid_geometry.convex_hull
  340. else:
  341. object_geo = cutout_obj.solid_geometry
  342. else:
  343. object_geo = cutout_obj.solid_geometry
  344. # try:
  345. # __ = iter(object_geo)
  346. # except TypeError:
  347. # object_geo = [object_geo]
  348. object_geo = unary_union(object_geo)
  349. # for geo in object_geo:
  350. if isinstance(cutout_obj, FlatCAMGerber):
  351. geo = object_geo.buffer(margin + abs(dia / 2))
  352. geo = geo.exterior
  353. else:
  354. geo = object_geo
  355. # Get min and max data for each object as we just cut rectangles across X or Y
  356. xmin, ymin, xmax, ymax = recursive_bounds(geo)
  357. px = 0.5 * (xmin + xmax) + margin
  358. py = 0.5 * (ymin + ymax) + margin
  359. lenx = (xmax - xmin) + (margin * 2)
  360. leny = (ymax - ymin) + (margin * 2)
  361. if gaps == '8' or gaps == '2LR':
  362. geo = self.subtract_poly_from_geo(geo,
  363. xmin - gapsize, # botleft_x
  364. py - gapsize + leny / 4, # botleft_y
  365. xmax + gapsize, # topright_x
  366. py + gapsize + leny / 4) # topright_y
  367. geo = self.subtract_poly_from_geo(geo,
  368. xmin - gapsize,
  369. py - gapsize - leny / 4,
  370. xmax + gapsize,
  371. py + gapsize - leny / 4)
  372. if gaps == '8' or gaps == '2TB':
  373. geo = self.subtract_poly_from_geo(geo,
  374. px - gapsize + lenx / 4,
  375. ymin - gapsize,
  376. px + gapsize + lenx / 4,
  377. ymax + gapsize)
  378. geo = self.subtract_poly_from_geo(geo,
  379. px - gapsize - lenx / 4,
  380. ymin - gapsize,
  381. px + gapsize - lenx / 4,
  382. ymax + gapsize)
  383. if gaps == '4' or gaps == 'LR':
  384. geo = self.subtract_poly_from_geo(geo,
  385. xmin - gapsize,
  386. py - gapsize,
  387. xmax + gapsize,
  388. py + gapsize)
  389. if gaps == '4' or gaps == 'TB':
  390. geo = self.subtract_poly_from_geo(geo,
  391. px - gapsize,
  392. ymin - gapsize,
  393. px + gapsize,
  394. ymax + gapsize)
  395. try:
  396. for g in geo:
  397. solid_geo.append(g)
  398. except TypeError:
  399. solid_geo.append(geo)
  400. geo_obj.solid_geometry = deepcopy(solid_geo)
  401. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  402. geo_obj.options['xmin'] = xmin
  403. geo_obj.options['ymin'] = ymin
  404. geo_obj.options['xmax'] = xmax
  405. geo_obj.options['ymax'] = ymax
  406. geo_obj.options['cnctooldia'] = str(dia)
  407. outname = cutout_obj.options["name"] + "_cutout"
  408. self.app.new_object('geometry', outname, geo_init)
  409. cutout_obj.plot()
  410. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  411. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  412. self.app.should_we_save = True
  413. def on_rectangular_cutout(self):
  414. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  415. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  416. # obj_.subtract_polygon(pts)
  417. name = self.obj_combo.currentText()
  418. # Get source object.
  419. try:
  420. cutout_obj = self.app.collection.get_by_name(str(name))
  421. except:
  422. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  423. return "Could not retrieve object: %s" % name
  424. if cutout_obj is None:
  425. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % cutout_obj)
  426. try:
  427. dia = float(self.dia.get_value())
  428. except ValueError:
  429. # try to convert comma to decimal point. if it's still not working error message and return
  430. try:
  431. dia = float(self.dia.get_value().replace(',', '.'))
  432. except ValueError:
  433. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  434. "Add it and retry."))
  435. return
  436. if 0 in {dia}:
  437. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  438. return "Tool Diameter is zero value. Change it to a positive real number."
  439. try:
  440. margin = float(self.margin.get_value())
  441. except ValueError:
  442. # try to convert comma to decimal point. if it's still not working error message and return
  443. try:
  444. margin = float(self.margin.get_value().replace(',', '.'))
  445. except ValueError:
  446. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  447. "Add it and retry."))
  448. return
  449. try:
  450. gapsize = float(self.gapsize.get_value())
  451. except ValueError:
  452. # try to convert comma to decimal point. if it's still not working error message and return
  453. try:
  454. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  455. except ValueError:
  456. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  457. "Add it and retry."))
  458. return
  459. try:
  460. gaps = self.gaps.get_value()
  461. except TypeError:
  462. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  463. return
  464. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  465. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  466. "Fill in a correct value and retry. "))
  467. return
  468. if cutout_obj.multigeo is True:
  469. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  470. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  471. "and after that perform Cutout."))
  472. return
  473. # Get min and max data for each object as we just cut rectangles across X or Y
  474. gapsize = gapsize / 2 + (dia / 2)
  475. def geo_init(geo_obj, app_obj):
  476. solid_geo = []
  477. object_geo = cutout_obj.solid_geometry
  478. try:
  479. __ = iter(object_geo)
  480. except TypeError:
  481. object_geo = [object_geo]
  482. object_geo = unary_union(object_geo)
  483. xmin, ymin, xmax, ymax = object_geo.bounds
  484. geo = box(xmin, ymin, xmax, ymax)
  485. # if Gerber create a buffer at a distance
  486. # if Geometry then cut through the geometry
  487. if isinstance(cutout_obj, FlatCAMGerber):
  488. geo = geo.buffer(margin + abs(dia / 2))
  489. px = 0.5 * (xmin + xmax) + margin
  490. py = 0.5 * (ymin + ymax) + margin
  491. lenx = (xmax - xmin) + (margin * 2)
  492. leny = (ymax - ymin) + (margin * 2)
  493. if gaps == '8' or gaps == '2LR':
  494. geo = self.subtract_poly_from_geo(geo,
  495. xmin - gapsize, # botleft_x
  496. py - gapsize + leny / 4, # botleft_y
  497. xmax + gapsize, # topright_x
  498. py + gapsize + leny / 4) # topright_y
  499. geo = self.subtract_poly_from_geo(geo,
  500. xmin - gapsize,
  501. py - gapsize - leny / 4,
  502. xmax + gapsize,
  503. py + gapsize - leny / 4)
  504. if gaps == '8' or gaps == '2TB':
  505. geo = self.subtract_poly_from_geo(geo,
  506. px - gapsize + lenx / 4,
  507. ymin - gapsize,
  508. px + gapsize + lenx / 4,
  509. ymax + gapsize)
  510. geo = self.subtract_poly_from_geo(geo,
  511. px - gapsize - lenx / 4,
  512. ymin - gapsize,
  513. px + gapsize - lenx / 4,
  514. ymax + gapsize)
  515. if gaps == '4' or gaps == 'LR':
  516. geo = self.subtract_poly_from_geo(geo,
  517. xmin - gapsize,
  518. py - gapsize,
  519. xmax + gapsize,
  520. py + gapsize)
  521. if gaps == '4' or gaps == 'TB':
  522. geo = self.subtract_poly_from_geo(geo,
  523. px - gapsize,
  524. ymin - gapsize,
  525. px + gapsize,
  526. ymax + gapsize)
  527. try:
  528. for g in geo:
  529. solid_geo.append(g)
  530. except TypeError:
  531. solid_geo.append(geo)
  532. geo_obj.solid_geometry = deepcopy(solid_geo)
  533. geo_obj.options['cnctooldia'] = str(dia)
  534. outname = cutout_obj.options["name"] + "_cutout"
  535. self.app.new_object('geometry', outname, geo_init)
  536. # cutout_obj.plot()
  537. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  538. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  539. self.app.should_we_save = True
  540. def on_manual_gap_click(self):
  541. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  542. self.app.geo_editor.tool_shape.enabled = True
  543. try:
  544. self.cutting_dia = float(self.dia.get_value())
  545. except ValueError:
  546. # try to convert comma to decimal point. if it's still not working error message and return
  547. try:
  548. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  549. except ValueError:
  550. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  551. "Add it and retry."))
  552. return
  553. if 0 in {self.cutting_dia}:
  554. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  555. return "Tool Diameter is zero value. Change it to a positive real number."
  556. try:
  557. self.cutting_gapsize = float(self.gapsize.get_value())
  558. except ValueError:
  559. # try to convert comma to decimal point. if it's still not working error message and return
  560. try:
  561. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  562. except ValueError:
  563. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  564. "Add it and retry."))
  565. return
  566. self.app.plotcanvas.vis_disconnect('key_press', self.app.ui.keyPressEvent)
  567. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  568. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  569. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  570. self.app.plotcanvas.vis_connect('key_press', self.on_key_press)
  571. self.app.plotcanvas.vis_connect('mouse_move', self.on_mouse_move)
  572. self.app.plotcanvas.vis_connect('mouse_release', self.doit)
  573. # To be called after clicking on the plot.
  574. def doit(self, event):
  575. # do paint single only for left mouse clicks
  576. if event.button == 1:
  577. self.app.inform.emit(_("Making manual bridge gap..."))
  578. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  579. self.on_manual_cutout(click_pos=pos)
  580. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  581. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  582. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  583. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  584. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  585. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  586. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  587. self.app.geo_editor.tool_shape.clear(update=True)
  588. self.app.geo_editor.tool_shape.enabled = False
  589. self.gapFinished.emit()
  590. def on_manual_cutout(self, click_pos):
  591. name = self.man_object_combo.currentText()
  592. # Get source object.
  593. try:
  594. cutout_obj = self.app.collection.get_by_name(str(name))
  595. except:
  596. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Geometry object: %s") % name)
  597. return "Could not retrieve object: %s" % name
  598. if cutout_obj is None:
  599. self.app.inform.emit(_("[ERROR_NOTCL] Geometry object for manual cutout not found: %s") % cutout_obj)
  600. return
  601. # use the snapped position as reference
  602. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  603. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  604. cutout_obj.subtract_polygon(cut_poly)
  605. cutout_obj.plot()
  606. self.app.inform.emit(_("[success] Added manual Bridge Gap."))
  607. self.app.should_we_save = True
  608. def on_gap_finished(self):
  609. # if CTRL key modifier is pressed then repeat the bridge gap cut
  610. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  611. if key_modifier == Qt.ControlModifier:
  612. self.on_manual_gap_click()
  613. def on_manual_geo(self):
  614. name = self.obj_combo.currentText()
  615. # Get source object.
  616. try:
  617. cutout_obj = self.app.collection.get_by_name(str(name))
  618. except:
  619. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Gerber object: %s") % name)
  620. return "Could not retrieve object: %s" % name
  621. if cutout_obj is None:
  622. self.app.inform.emit(_("[ERROR_NOTCL] There is no Gerber object selected for Cutout.\n"
  623. "Select one and try again."))
  624. return
  625. if not isinstance(cutout_obj, FlatCAMGerber):
  626. self.app.inform.emit(_("[ERROR_NOTCL] The selected object has to be of Gerber type.\n"
  627. "Select a Gerber file and try again."))
  628. return
  629. try:
  630. dia = float(self.dia.get_value())
  631. except ValueError:
  632. # try to convert comma to decimal point. if it's still not working error message and return
  633. try:
  634. dia = float(self.dia.get_value().replace(',', '.'))
  635. except ValueError:
  636. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  637. "Add it and retry."))
  638. return
  639. if 0 in {dia}:
  640. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  641. return "Tool Diameter is zero value. Change it to a positive real number."
  642. try:
  643. margin = float(self.margin.get_value())
  644. except ValueError:
  645. # try to convert comma to decimal point. if it's still not working error message and return
  646. try:
  647. margin = float(self.margin.get_value().replace(',', '.'))
  648. except ValueError:
  649. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  650. "Add it and retry."))
  651. return
  652. convex_box = self.convex_box.get_value()
  653. def geo_init(geo_obj, app_obj):
  654. geo_union = unary_union(cutout_obj.solid_geometry)
  655. if convex_box:
  656. geo = geo_union.convex_hull
  657. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  658. else:
  659. geo = geo_union
  660. geo = geo.buffer(margin + abs(dia / 2))
  661. if isinstance(geo, Polygon):
  662. geo_obj.solid_geometry = geo.exterior
  663. elif isinstance(geo, MultiPolygon):
  664. solid_geo = []
  665. for poly in geo:
  666. solid_geo.append(poly.exterior)
  667. geo_obj.solid_geometry = deepcopy(solid_geo)
  668. geo_obj.options['cnctooldia'] = str(dia)
  669. outname = cutout_obj.options["name"] + "_cutout"
  670. self.app.new_object('geometry', outname, geo_init)
  671. def cutting_geo(self, pos):
  672. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  673. # cutting area definition
  674. orig_x = pos[0]
  675. orig_y = pos[1]
  676. xmin = orig_x - offset
  677. ymin = orig_y - offset
  678. xmax = orig_x + offset
  679. ymax = orig_y + offset
  680. cut_poly = box(xmin, ymin, xmax, ymax)
  681. return cut_poly
  682. def on_mouse_move(self, event):
  683. self.app.on_mouse_move_over_plot(event=event)
  684. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  685. event.xdata, event.ydata = pos[0], pos[1]
  686. try:
  687. x = float(event.xdata)
  688. y = float(event.ydata)
  689. except TypeError:
  690. return
  691. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  692. geo = self.cutting_geo(pos=(snap_x, snap_y))
  693. # Remove any previous utility shape
  694. self.app.geo_editor.tool_shape.clear(update=True)
  695. self.draw_utility_geometry(geo=geo)
  696. def draw_utility_geometry(self, geo):
  697. self.app.geo_editor.tool_shape.add(
  698. shape=geo,
  699. color=(self.app.defaults["global_draw_color"] + '80'),
  700. update=False,
  701. layer=0,
  702. tolerance=None)
  703. self.app.geo_editor.tool_shape.redraw()
  704. def on_key_press(self, event):
  705. # events out of the self.app.collection view (it's about Project Tab) are of type int
  706. if type(event) is int:
  707. key = event
  708. # events from the GUI are of type QKeyEvent
  709. elif type(event) == QtGui.QKeyEvent:
  710. key = event.key()
  711. # events from Vispy are of type KeyEvent
  712. else:
  713. key = event.key
  714. # Escape = Deselect All
  715. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  716. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  717. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  718. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  719. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  720. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  721. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  722. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  723. # Remove any previous utility shape
  724. self.app.geo_editor.tool_shape.clear(update=True)
  725. self.app.geo_editor.tool_shape.enabled = False
  726. def subtract_poly_from_geo(self, solid_geo, x0, y0, x1, y1):
  727. """
  728. Subtract polygon made from points from the given object.
  729. This only operates on the paths in the original geometry,
  730. i.e. it converts polygons into paths.
  731. :param x0: x coord for lower left vertice of the polygon.
  732. :param y0: y coord for lower left vertice of the polygon.
  733. :param x1: x coord for upper right vertice of the polygon.
  734. :param y1: y coord for upper right vertice of the polygon.
  735. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  736. :return: none
  737. """
  738. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  739. # pathonly should be allways True, otherwise polygons are not subtracted
  740. flat_geometry = flatten(geometry=solid_geo)
  741. log.debug("%d paths" % len(flat_geometry))
  742. polygon = Polygon(points)
  743. toolgeo = cascaded_union(polygon)
  744. diffs = []
  745. for target in flat_geometry:
  746. if type(target) == LineString or type(target) == LinearRing:
  747. diffs.append(target.difference(toolgeo))
  748. else:
  749. log.warning("Not implemented.")
  750. return unary_union(diffs)
  751. def reset_fields(self):
  752. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  753. def flatten(geometry):
  754. """
  755. Creates a list of non-iterable linear geometry objects.
  756. Polygons are expanded into its exterior and interiors.
  757. Results are placed in self.flat_geometry
  758. :param geometry: Shapely type or list or list of list of such.
  759. """
  760. flat_geo = []
  761. try:
  762. for geo in geometry:
  763. if type(geo) == Polygon:
  764. flat_geo.append(geo.exterior)
  765. for subgeo in geo.interiors:
  766. flat_geo.append(subgeo)
  767. else:
  768. flat_geo.append(geo)
  769. except TypeError:
  770. if type(geometry) == Polygon:
  771. flat_geo.append(geometry.exterior)
  772. for subgeo in geometry.interiors:
  773. flat_geo.append(subgeo)
  774. else:
  775. flat_geo.append(geometry)
  776. return flat_geo
  777. def recursive_bounds(geometry):
  778. """
  779. Returns coordinates of rectangular bounds
  780. of geometry: (xmin, ymin, xmax, ymax).
  781. """
  782. # now it can get bounds for nested lists of objects
  783. def bounds_rec(obj):
  784. try:
  785. minx = Inf
  786. miny = Inf
  787. maxx = -Inf
  788. maxy = -Inf
  789. for k in obj:
  790. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  791. minx = min(minx, minx_)
  792. miny = min(miny, miny_)
  793. maxx = max(maxx, maxx_)
  794. maxy = max(maxy, maxy_)
  795. return minx, miny, maxx, maxy
  796. except TypeError:
  797. # it's a Shapely object, return it's bounds
  798. return obj.bounds
  799. return bounds_rec(geometry)