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