ToolCutOut.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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. 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('%s:' % _("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.setMinimumWidth(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('%s:' % _("Object"))
  56. self.object_label.setToolTip(
  57. _("Object to be cutout. ")
  58. )
  59. form_layout.addRow(self.object_label, self.obj_combo)
  60. # Object kind
  61. self.kindlabel = QtWidgets.QLabel('%s:' % _('Obj kind'))
  62. self.kindlabel.setToolTip(
  63. _("Choice of what kind the object we want to cutout is.<BR>"
  64. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  65. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  66. "out of many individual PCB outlines.")
  67. )
  68. self.obj_kind_combo = RadioSet([
  69. {"label": _("Single"), "value": "single"},
  70. {"label": _("Panel"), "value": "panel"},
  71. ])
  72. form_layout.addRow(self.kindlabel, self.obj_kind_combo)
  73. # Tool Diameter
  74. self.dia = FCEntry()
  75. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool dia"))
  76. self.dia_label.setToolTip(
  77. _("Diameter of the tool used to cutout\n"
  78. "the PCB shape out of the surrounding material.")
  79. )
  80. form_layout.addRow(self.dia_label, self.dia)
  81. # Margin
  82. self.margin = FCEntry()
  83. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin:"))
  84. self.margin_label.setToolTip(
  85. _("Margin over bounds. A positive value here\n"
  86. "will make the cutout of the PCB further from\n"
  87. "the actual PCB border")
  88. )
  89. form_layout.addRow(self.margin_label, self.margin)
  90. # Gapsize
  91. self.gapsize = FCEntry()
  92. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size:"))
  93. self.gapsize_label.setToolTip(
  94. _("The size of the bridge gaps in the cutout\n"
  95. "used to keep the board connected to\n"
  96. "the surrounding material (the one \n"
  97. "from which the PCB is cutout).")
  98. )
  99. form_layout.addRow(self.gapsize_label, self.gapsize)
  100. # How gaps wil be rendered:
  101. # lr - left + right
  102. # tb - top + bottom
  103. # 4 - left + right +top + bottom
  104. # 2lr - 2*left + 2*right
  105. # 2tb - 2*top + 2*bottom
  106. # 8 - 2*left + 2*right +2*top + 2*bottom
  107. # Surrounding convex box shape
  108. self.convex_box = FCCheckBox()
  109. self.convex_box_label = QtWidgets.QLabel('%s:' % _("Convex Sh."))
  110. self.convex_box_label.setToolTip(
  111. _("Create a convex shape surrounding the entire PCB.\n"
  112. "Used only if the source object type is Gerber.")
  113. )
  114. form_layout.addRow(self.convex_box_label, self.convex_box)
  115. # Title2
  116. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  117. title_param_label.setToolTip(
  118. _("This section handle creation of automatic bridge gaps.")
  119. )
  120. self.layout.addWidget(title_param_label)
  121. # Form Layout
  122. form_layout_2 = QtWidgets.QFormLayout()
  123. self.layout.addLayout(form_layout_2)
  124. # Gaps
  125. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  126. gaps_label.setToolTip(
  127. _("Number of gaps used for the Automatic cutout.\n"
  128. "There can be maximum 8 bridges/gaps.\n"
  129. "The choices are:\n"
  130. "- None - no gaps\n"
  131. "- lr - left + right\n"
  132. "- tb - top + bottom\n"
  133. "- 4 - left + right +top + bottom\n"
  134. "- 2lr - 2*left + 2*right\n"
  135. "- 2tb - 2*top + 2*bottom\n"
  136. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  137. )
  138. gaps_label.setMinimumWidth(60)
  139. self.gaps = FCComboBox()
  140. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  141. for it in gaps_items:
  142. self.gaps.addItem(it)
  143. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  144. form_layout_2.addRow(gaps_label, self.gaps)
  145. # Buttons
  146. hlay = QtWidgets.QHBoxLayout()
  147. self.layout.addLayout(hlay)
  148. title_ff_label = QtWidgets.QLabel("<b>%s:</b>" % _('FreeForm'))
  149. title_ff_label.setToolTip(
  150. _("The cutout shape can be of ny shape.\n"
  151. "Useful when the PCB has a non-rectangular shape.")
  152. )
  153. hlay.addWidget(title_ff_label)
  154. hlay.addStretch()
  155. self.ff_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  156. self.ff_cutout_object_btn.setToolTip(
  157. _("Cutout the selected object.\n"
  158. "The cutout shape can be of any shape.\n"
  159. "Useful when the PCB has a non-rectangular shape.")
  160. )
  161. hlay.addWidget(self.ff_cutout_object_btn)
  162. hlay2 = QtWidgets.QHBoxLayout()
  163. self.layout.addLayout(hlay2)
  164. title_rct_label = QtWidgets.QLabel("<b>%s:</b>" % _('Rectangular'))
  165. title_rct_label.setToolTip(
  166. _("The resulting cutout shape is\n"
  167. "always a rectangle shape and it will be\n"
  168. "the bounding box of the Object.")
  169. )
  170. hlay2.addWidget(title_rct_label)
  171. hlay2.addStretch()
  172. self.rect_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  173. self.rect_cutout_object_btn.setToolTip(
  174. _("Cutout the selected object.\n"
  175. "The resulting cutout shape is\n"
  176. "always a rectangle shape and it will be\n"
  177. "the bounding box of the Object.")
  178. )
  179. hlay2.addWidget(self.rect_cutout_object_btn)
  180. # Title5
  181. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  182. title_manual_label.setToolTip(
  183. _("This section handle creation of manual bridge gaps.\n"
  184. "This is done by mouse clicking on the perimeter of the\n"
  185. "Geometry object that is used as a cutout object. ")
  186. )
  187. self.layout.addWidget(title_manual_label)
  188. # Form Layout
  189. form_layout_3 = QtWidgets.QFormLayout()
  190. self.layout.addLayout(form_layout_3)
  191. # Manual Geo Object
  192. self.man_object_combo = QtWidgets.QComboBox()
  193. self.man_object_combo.setModel(self.app.collection)
  194. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  195. self.man_object_combo.setCurrentIndex(1)
  196. self.man_object_label = QtWidgets.QLabel('%s:' % _("Geo Obj"))
  197. self.man_object_label.setToolTip(
  198. _("Geometry object used to create the manual cutout.")
  199. )
  200. self.man_object_label.setMinimumWidth(60)
  201. # e_lab_0 = QtWidgets.QLabel('')
  202. form_layout_3.addRow(self.man_object_label, self.man_object_combo)
  203. # form_layout_3.addRow(e_lab_0)
  204. hlay3 = QtWidgets.QHBoxLayout()
  205. self.layout.addLayout(hlay3)
  206. self.man_geo_label = QtWidgets.QLabel('%s:' % _("Manual Geo"))
  207. self.man_geo_label.setToolTip(
  208. _("If the object to be cutout is a Gerber\n"
  209. "first create a Geometry that surrounds it,\n"
  210. "to be used as the cutout, if one doesn't exist yet.\n"
  211. "Select the source Gerber file in the top object combobox.")
  212. )
  213. hlay3.addWidget(self.man_geo_label)
  214. hlay3.addStretch()
  215. self.man_geo_creation_btn = QtWidgets.QPushButton(_("Generate Geo"))
  216. self.man_geo_creation_btn.setToolTip(
  217. _("If the object to be cutout is a Gerber\n"
  218. "first create a Geometry that surrounds it,\n"
  219. "to be used as the cutout, if one doesn't exist yet.\n"
  220. "Select the source Gerber file in the top object combobox.")
  221. )
  222. hlay3.addWidget(self.man_geo_creation_btn)
  223. hlay4 = QtWidgets.QHBoxLayout()
  224. self.layout.addLayout(hlay4)
  225. self.man_bridge_gaps_label = QtWidgets.QLabel('%s:' % _("Manual Add Bridge Gaps"))
  226. self.man_bridge_gaps_label.setToolTip(
  227. _("Use the left mouse button (LMB) click\n"
  228. "to create a bridge gap to separate the PCB from\n"
  229. "the surrounding material.")
  230. )
  231. hlay4.addWidget(self.man_bridge_gaps_label)
  232. hlay4.addStretch()
  233. self.man_gaps_creation_btn = QtWidgets.QPushButton(_("Generate Gap"))
  234. self.man_gaps_creation_btn.setToolTip(
  235. _("Use the left mouse button (LMB) click\n"
  236. "to create a bridge gap to separate the PCB from\n"
  237. "the surrounding material.\n"
  238. "The LMB click has to be done on the perimeter of\n"
  239. "the Geometry object used as a cutout geometry.")
  240. )
  241. hlay4.addWidget(self.man_gaps_creation_btn)
  242. self.layout.addStretch()
  243. self.cutting_gapsize = 0.0
  244. self.cutting_dia = 0.0
  245. # true if we want to repeat the gap without clicking again on the button
  246. self.repeat_gap = False
  247. self.flat_geometry = []
  248. # this is the Geometry object generated in this class to be used for adding manual gaps
  249. self.man_cutout_obj = None
  250. # if mouse is dragging set the object True
  251. self.mouse_is_dragging = False
  252. # event handlers references
  253. self.kp = None
  254. self.mm = None
  255. self.mr = None
  256. # hold the mouse position here
  257. self.x_pos = None
  258. self.y_pos = None
  259. # Signals
  260. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  261. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  262. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  263. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  264. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  265. def on_type_obj_index_changed(self, index):
  266. obj_type = self.type_obj_combo.currentIndex()
  267. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  268. self.obj_combo.setCurrentIndex(0)
  269. def run(self, toggle=True):
  270. self.app.report_usage("ToolCutOut()")
  271. if toggle:
  272. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  273. if self.app.ui.splitter.sizes()[0] == 0:
  274. self.app.ui.splitter.setSizes([1, 1])
  275. else:
  276. try:
  277. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  278. # if tab is populated with the tool but it does not have the focus, focus on it
  279. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  280. # focus on Tool Tab
  281. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  282. else:
  283. self.app.ui.splitter.setSizes([0, 1])
  284. except AttributeError:
  285. pass
  286. else:
  287. if self.app.ui.splitter.sizes()[0] == 0:
  288. self.app.ui.splitter.setSizes([1, 1])
  289. FlatCAMTool.run(self)
  290. self.set_tool_ui()
  291. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  292. def install(self, icon=None, separator=None, **kwargs):
  293. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  294. def set_tool_ui(self):
  295. self.reset_fields()
  296. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  297. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  298. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  299. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  300. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  301. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  302. def on_freeform_cutout(self):
  303. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  304. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  305. # obj_.subtract_polygon(pts)
  306. name = self.obj_combo.currentText()
  307. # Get source object.
  308. try:
  309. cutout_obj = self.app.collection.get_by_name(str(name))
  310. except Exception as e:
  311. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  312. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  313. return "Could not retrieve object: %s" % name
  314. if cutout_obj is None:
  315. self.app.inform.emit('[ERROR_NOTCL] %s' %
  316. _("There is no object selected for Cutout.\nSelect one and try again."))
  317. return
  318. try:
  319. dia = float(self.dia.get_value())
  320. except ValueError:
  321. # try to convert comma to decimal point. if it's still not working error message and return
  322. try:
  323. dia = float(self.dia.get_value().replace(',', '.'))
  324. except ValueError:
  325. self.app.inform.emit('[WARNING_NOTCL] %s' %
  326. _("Tool diameter value is missing or wrong format. Add it and retry."))
  327. return
  328. if 0 in {dia}:
  329. self.app.inform.emit('[WARNING_NOTCL] %s' %
  330. _("Tool Diameter is zero value. Change it to a positive real number."))
  331. return "Tool Diameter is zero value. Change it to a positive real number."
  332. try:
  333. kind = self.obj_kind_combo.get_value()
  334. except ValueError:
  335. return
  336. try:
  337. margin = float(self.margin.get_value())
  338. except ValueError:
  339. # try to convert comma to decimal point. if it's still not working error message and return
  340. try:
  341. margin = float(self.margin.get_value().replace(',', '.'))
  342. except ValueError:
  343. self.app.inform.emit('[WARNING_NOTCL] %s' %
  344. _("Margin value is missing or wrong format. Add it and retry."))
  345. return
  346. try:
  347. gapsize = float(self.gapsize.get_value())
  348. except ValueError:
  349. # try to convert comma to decimal point. if it's still not working error message and return
  350. try:
  351. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  352. except ValueError:
  353. self.app.inform.emit('[WARNING_NOTCL] %s' %
  354. _("Gap size value is missing or wrong format. Add it and retry."))
  355. return
  356. try:
  357. gaps = self.gaps.get_value()
  358. except TypeError:
  359. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  360. return
  361. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  362. self.app.inform.emit('[WARNING_NOTCL] %s' %
  363. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  364. "Fill in a correct value and retry. "))
  365. return
  366. if cutout_obj.multigeo is True:
  367. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  368. "Optionally, this Multi-geo Geometry can be converted to "
  369. "Single-geo Geometry,\n"
  370. "and after that perform Cutout."))
  371. return
  372. convex_box = self.convex_box.get_value()
  373. gapsize = gapsize / 2 + (dia / 2)
  374. def geo_init(geo_obj, app_obj):
  375. solid_geo = []
  376. if isinstance(cutout_obj, FlatCAMGerber):
  377. if convex_box:
  378. object_geo = cutout_obj.solid_geometry.convex_hull
  379. else:
  380. object_geo = cutout_obj.solid_geometry
  381. else:
  382. object_geo = cutout_obj.solid_geometry
  383. def cutout_handler(geom):
  384. # Get min and max data for each object as we just cut rectangles across X or Y
  385. xmin, ymin, xmax, ymax = recursive_bounds(geom)
  386. px = 0.5 * (xmin + xmax) + margin
  387. py = 0.5 * (ymin + ymax) + margin
  388. lenx = (xmax - xmin) + (margin * 2)
  389. leny = (ymax - ymin) + (margin * 2)
  390. proc_geometry = []
  391. if gaps == 'None':
  392. pass
  393. else:
  394. if gaps == '8' or gaps == '2LR':
  395. geom = self.subtract_poly_from_geo(geom,
  396. xmin - gapsize, # botleft_x
  397. py - gapsize + leny / 4, # botleft_y
  398. xmax + gapsize, # topright_x
  399. py + gapsize + leny / 4) # topright_y
  400. geom = self.subtract_poly_from_geo(geom,
  401. xmin - gapsize,
  402. py - gapsize - leny / 4,
  403. xmax + gapsize,
  404. py + gapsize - leny / 4)
  405. if gaps == '8' or gaps == '2TB':
  406. geom = self.subtract_poly_from_geo(geom,
  407. px - gapsize + lenx / 4,
  408. ymin - gapsize,
  409. px + gapsize + lenx / 4,
  410. ymax + gapsize)
  411. geom = self.subtract_poly_from_geo(geom,
  412. px - gapsize - lenx / 4,
  413. ymin - gapsize,
  414. px + gapsize - lenx / 4,
  415. ymax + gapsize)
  416. if gaps == '4' or gaps == 'LR':
  417. geom = self.subtract_poly_from_geo(geom,
  418. xmin - gapsize,
  419. py - gapsize,
  420. xmax + gapsize,
  421. py + gapsize)
  422. if gaps == '4' or gaps == 'TB':
  423. geom = self.subtract_poly_from_geo(geom,
  424. px - gapsize,
  425. ymin - gapsize,
  426. px + gapsize,
  427. ymax + gapsize)
  428. try:
  429. for g in geom:
  430. proc_geometry.append(g)
  431. except TypeError:
  432. proc_geometry.append(geom)
  433. return proc_geometry
  434. if kind == 'single':
  435. object_geo = unary_union(object_geo)
  436. # for geo in object_geo:
  437. if isinstance(cutout_obj, FlatCAMGerber):
  438. if isinstance(object_geo, MultiPolygon):
  439. x0, y0, x1, y1 = object_geo.bounds
  440. object_geo = box(x0, y0, x1, y1)
  441. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  442. geo = geo_buf.exterior
  443. else:
  444. geo = object_geo
  445. solid_geo = cutout_handler(geom=geo)
  446. else:
  447. try:
  448. __ = iter(object_geo)
  449. except TypeError:
  450. object_geo = [object_geo]
  451. for geom_struct in object_geo:
  452. if isinstance(cutout_obj, FlatCAMGerber):
  453. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  454. solid_geo += cutout_handler(geom=geom_struct)
  455. geo_obj.solid_geometry = deepcopy(solid_geo)
  456. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  457. geo_obj.options['xmin'] = xmin
  458. geo_obj.options['ymin'] = ymin
  459. geo_obj.options['xmax'] = xmax
  460. geo_obj.options['ymax'] = ymax
  461. geo_obj.options['cnctooldia'] = str(dia)
  462. outname = cutout_obj.options["name"] + "_cutout"
  463. self.app.new_object('geometry', outname, geo_init)
  464. cutout_obj.plot()
  465. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  466. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  467. self.app.should_we_save = True
  468. def on_rectangular_cutout(self):
  469. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  470. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  471. # obj_.subtract_polygon(pts)
  472. name = self.obj_combo.currentText()
  473. # Get source object.
  474. try:
  475. cutout_obj = self.app.collection.get_by_name(str(name))
  476. except Exception as e:
  477. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  478. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  479. return "Could not retrieve object: %s" % name
  480. if cutout_obj is None:
  481. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  482. try:
  483. dia = float(self.dia.get_value())
  484. except ValueError:
  485. # try to convert comma to decimal point. if it's still not working error message and return
  486. try:
  487. dia = float(self.dia.get_value().replace(',', '.'))
  488. except ValueError:
  489. self.app.inform.emit('[WARNING_NOTCL] %s' %
  490. _("Tool diameter value is missing or wrong format. Add it and retry."))
  491. return
  492. if 0 in {dia}:
  493. self.app.inform.emit('[ERROR_NOTCL] %s' %
  494. _("Tool Diameter is zero value. Change it to a positive real number."))
  495. return "Tool Diameter is zero value. Change it to a positive real number."
  496. try:
  497. kind = self.obj_kind_combo.get_value()
  498. except ValueError:
  499. return
  500. try:
  501. margin = float(self.margin.get_value())
  502. except ValueError:
  503. # try to convert comma to decimal point. if it's still not working error message and return
  504. try:
  505. margin = float(self.margin.get_value().replace(',', '.'))
  506. except ValueError:
  507. self.app.inform.emit('[WARNING_NOTCL] %s' %
  508. _("Margin value is missing or wrong format. Add it and retry."))
  509. return
  510. try:
  511. gapsize = float(self.gapsize.get_value())
  512. except ValueError:
  513. # try to convert comma to decimal point. if it's still not working error message and return
  514. try:
  515. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  516. except ValueError:
  517. self.app.inform.emit('[WARNING_NOTCL] %s' %
  518. _("Gap size value is missing or wrong format. Add it and retry."))
  519. return
  520. try:
  521. gaps = self.gaps.get_value()
  522. except TypeError:
  523. self.app.inform.emit('[WARNING_NOTCL] %s' %
  524. _("Number of gaps value is missing. Add it and retry."))
  525. return
  526. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  527. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  528. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  529. "Fill in a correct value and retry. "))
  530. return
  531. if cutout_obj.multigeo is True:
  532. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  533. "Optionally, this Multi-geo Geometry can be converted to "
  534. "Single-geo Geometry,\n"
  535. "and after that perform Cutout."))
  536. return
  537. # Get min and max data for each object as we just cut rectangles across X or Y
  538. gapsize = gapsize / 2 + (dia / 2)
  539. def geo_init(geo_obj, app_obj):
  540. solid_geo = []
  541. object_geo = cutout_obj.solid_geometry
  542. def cutout_rect_handler(geom):
  543. proc_geometry = []
  544. px = 0.5 * (xmin + xmax) + margin
  545. py = 0.5 * (ymin + ymax) + margin
  546. lenx = (xmax - xmin) + (margin * 2)
  547. leny = (ymax - ymin) + (margin * 2)
  548. if gaps == 'None':
  549. pass
  550. else:
  551. if gaps == '8' or gaps == '2LR':
  552. geom = self.subtract_poly_from_geo(geom,
  553. xmin - gapsize, # botleft_x
  554. py - gapsize + leny / 4, # botleft_y
  555. xmax + gapsize, # topright_x
  556. py + gapsize + leny / 4) # topright_y
  557. geom = self.subtract_poly_from_geo(geom,
  558. xmin - gapsize,
  559. py - gapsize - leny / 4,
  560. xmax + gapsize,
  561. py + gapsize - leny / 4)
  562. if gaps == '8' or gaps == '2TB':
  563. geom = self.subtract_poly_from_geo(geom,
  564. px - gapsize + lenx / 4,
  565. ymin - gapsize,
  566. px + gapsize + lenx / 4,
  567. ymax + gapsize)
  568. geom = self.subtract_poly_from_geo(geom,
  569. px - gapsize - lenx / 4,
  570. ymin - gapsize,
  571. px + gapsize - lenx / 4,
  572. ymax + gapsize)
  573. if gaps == '4' or gaps == 'LR':
  574. geom = self.subtract_poly_from_geo(geom,
  575. xmin - gapsize,
  576. py - gapsize,
  577. xmax + gapsize,
  578. py + gapsize)
  579. if gaps == '4' or gaps == 'TB':
  580. geom = self.subtract_poly_from_geo(geom,
  581. px - gapsize,
  582. ymin - gapsize,
  583. px + gapsize,
  584. ymax + gapsize)
  585. try:
  586. for g in geom:
  587. proc_geometry.append(g)
  588. except TypeError:
  589. proc_geometry.append(geom)
  590. return proc_geometry
  591. if kind == 'single':
  592. object_geo = unary_union(object_geo)
  593. xmin, ymin, xmax, ymax = object_geo.bounds
  594. geo = box(xmin, ymin, xmax, ymax)
  595. # if Gerber create a buffer at a distance
  596. # if Geometry then cut through the geometry
  597. if isinstance(cutout_obj, FlatCAMGerber):
  598. geo = geo.buffer(margin + abs(dia / 2))
  599. solid_geo = cutout_rect_handler(geom=geo)
  600. else:
  601. try:
  602. __ = iter(object_geo)
  603. except TypeError:
  604. object_geo = [object_geo]
  605. for geom_struct in object_geo:
  606. geom_struct = unary_union(geom_struct)
  607. xmin, ymin, xmax, ymax = geom_struct.bounds
  608. geom_struct = box(xmin, ymin, xmax, ymax)
  609. if isinstance(cutout_obj, FlatCAMGerber):
  610. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  611. solid_geo += cutout_rect_handler(geom=geom_struct)
  612. geo_obj.solid_geometry = deepcopy(solid_geo)
  613. geo_obj.options['cnctooldia'] = str(dia)
  614. outname = cutout_obj.options["name"] + "_cutout"
  615. self.app.new_object('geometry', outname, geo_init)
  616. # cutout_obj.plot()
  617. self.app.inform.emit('[success] %s' %
  618. _("Any form CutOut operation finished."))
  619. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  620. self.app.should_we_save = True
  621. def on_manual_gap_click(self):
  622. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  623. self.app.geo_editor.tool_shape.enabled = True
  624. try:
  625. self.cutting_dia = float(self.dia.get_value())
  626. except ValueError:
  627. # try to convert comma to decimal point. if it's still not working error message and return
  628. try:
  629. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  630. except ValueError:
  631. self.app.inform.emit('[WARNING_NOTCL] %s' %
  632. _("Tool diameter value is missing or wrong format. Add it and retry."))
  633. return
  634. if 0 in {self.cutting_dia}:
  635. self.app.inform.emit('[ERROR_NOTCL] %s' %
  636. _("Tool Diameter is zero value. Change it to a positive real number."))
  637. return "Tool Diameter is zero value. Change it to a positive real number."
  638. try:
  639. self.cutting_gapsize = float(self.gapsize.get_value())
  640. except ValueError:
  641. # try to convert comma to decimal point. if it's still not working error message and return
  642. try:
  643. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  644. except ValueError:
  645. self.app.inform.emit('[WARNING_NOTCL] %s' %
  646. _("Gap size value is missing or wrong format. Add it and retry."))
  647. return
  648. name = self.man_object_combo.currentText()
  649. # Get Geometry source object to be used as target for Manual adding Gaps
  650. try:
  651. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  652. except Exception as e:
  653. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  654. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  655. return "Could not retrieve object: %s" % name
  656. if self.app.is_legacy is False:
  657. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  658. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  659. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  660. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  661. else:
  662. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  663. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  664. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  665. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  666. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  667. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  668. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  669. def on_manual_cutout(self, click_pos):
  670. name = self.man_object_combo.currentText()
  671. # Get source object.
  672. try:
  673. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  674. except Exception as e:
  675. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  676. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  677. return "Could not retrieve object: %s" % name
  678. if self.man_cutout_obj is None:
  679. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  680. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  681. return
  682. # use the snapped position as reference
  683. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  684. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  685. self.man_cutout_obj.subtract_polygon(cut_poly)
  686. self.man_cutout_obj.plot()
  687. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  688. self.app.should_we_save = True
  689. def on_manual_geo(self):
  690. name = self.obj_combo.currentText()
  691. # Get source object.
  692. try:
  693. cutout_obj = self.app.collection.get_by_name(str(name))
  694. except Exception as e:
  695. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  696. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  697. return "Could not retrieve object: %s" % name
  698. if cutout_obj is None:
  699. self.app.inform.emit('[ERROR_NOTCL] %s' %
  700. _("There is no Gerber object selected for Cutout.\n"
  701. "Select one and try again."))
  702. return
  703. if not isinstance(cutout_obj, FlatCAMGerber):
  704. self.app.inform.emit('[ERROR_NOTCL] %s' %
  705. _("The selected object has to be of Gerber type.\n"
  706. "Select a Gerber file and try again."))
  707. return
  708. try:
  709. dia = float(self.dia.get_value())
  710. except ValueError:
  711. # try to convert comma to decimal point. if it's still not working error message and return
  712. try:
  713. dia = float(self.dia.get_value().replace(',', '.'))
  714. except ValueError:
  715. self.app.inform.emit('[WARNING_NOTCL] %s' %
  716. _("Tool diameter value is missing or wrong format. Add it and retry."))
  717. return
  718. if 0 in {dia}:
  719. self.app.inform.emit('[ERROR_NOTCL] %s' %
  720. _("Tool Diameter is zero value. Change it to a positive real number."))
  721. return "Tool Diameter is zero value. Change it to a positive real number."
  722. try:
  723. kind = self.obj_kind_combo.get_value()
  724. except ValueError:
  725. return
  726. try:
  727. margin = float(self.margin.get_value())
  728. except ValueError:
  729. # try to convert comma to decimal point. if it's still not working error message and return
  730. try:
  731. margin = float(self.margin.get_value().replace(',', '.'))
  732. except ValueError:
  733. self.app.inform.emit('[WARNING_NOTCL] %s' %
  734. _("Margin value is missing or wrong format. Add it and retry."))
  735. return
  736. convex_box = self.convex_box.get_value()
  737. def geo_init(geo_obj, app_obj):
  738. geo_union = unary_union(cutout_obj.solid_geometry)
  739. if convex_box:
  740. geo = geo_union.convex_hull
  741. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  742. elif kind == 'single':
  743. if isinstance(geo_union, Polygon) or \
  744. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  745. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  746. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  747. elif isinstance(geo_union, MultiPolygon):
  748. x0, y0, x1, y1 = geo_union.bounds
  749. geo = box(x0, y0, x1, y1)
  750. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  751. else:
  752. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  753. (_("Geometry not supported for cutout"), type(geo_union)))
  754. return 'fail'
  755. else:
  756. geo = geo_union
  757. geo = geo.buffer(margin + abs(dia / 2))
  758. if isinstance(geo, Polygon):
  759. geo_obj.solid_geometry = geo.exterior
  760. elif isinstance(geo, MultiPolygon):
  761. solid_geo = []
  762. for poly in geo:
  763. solid_geo.append(poly.exterior)
  764. geo_obj.solid_geometry = deepcopy(solid_geo)
  765. geo_obj.options['cnctooldia'] = str(dia)
  766. outname = cutout_obj.options["name"] + "_cutout"
  767. self.app.new_object('geometry', outname, geo_init)
  768. def cutting_geo(self, pos):
  769. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  770. # cutting area definition
  771. orig_x = pos[0]
  772. orig_y = pos[1]
  773. xmin = orig_x - offset
  774. ymin = orig_y - offset
  775. xmax = orig_x + offset
  776. ymax = orig_y + offset
  777. cut_poly = box(xmin, ymin, xmax, ymax)
  778. return cut_poly
  779. # To be called after clicking on the plot.
  780. def on_mouse_click_release(self, event):
  781. if self.app.is_legacy is False:
  782. event_pos = event.pos
  783. event_is_dragging = event.is_dragging
  784. right_button = 2
  785. else:
  786. event_pos = (event.xdata, event.ydata)
  787. event_is_dragging = self.app.plotcanvas.is_dragging
  788. right_button = 3
  789. try:
  790. x = float(event_pos[0])
  791. y = float(event_pos[1])
  792. except TypeError:
  793. return
  794. event_pos = (x, y)
  795. # do paint single only for left mouse clicks
  796. if event.button == 1:
  797. self.app.inform.emit(_("Making manual bridge gap..."))
  798. pos = self.app.plotcanvas.translate_coords(event_pos)
  799. self.on_manual_cutout(click_pos=pos)
  800. # if RMB then we exit
  801. elif event.button == right_button and self.mouse_is_dragging is False:
  802. if self.app.is_legacy is False:
  803. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  804. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  805. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  806. else:
  807. self.app.plotcanvas.graph_event_disconnect(self.kp)
  808. self.app.plotcanvas.graph_event_disconnect(self.mm)
  809. self.app.plotcanvas.graph_event_disconnect(self.mr)
  810. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  811. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  812. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  813. self.app.on_mouse_click_release_over_plot)
  814. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  815. # Remove any previous utility shape
  816. self.app.geo_editor.tool_shape.clear(update=True)
  817. self.app.geo_editor.tool_shape.enabled = False
  818. def on_mouse_move(self, event):
  819. self.app.on_mouse_move_over_plot(event=event)
  820. if self.app.is_legacy is False:
  821. event_pos = event.pos
  822. event_is_dragging = event.is_dragging
  823. right_button = 2
  824. else:
  825. event_pos = (event.xdata, event.ydata)
  826. event_is_dragging = self.app.plotcanvas.is_dragging
  827. right_button = 3
  828. try:
  829. x = float(event_pos[0])
  830. y = float(event_pos[1])
  831. except TypeError:
  832. return
  833. event_pos = (x, y)
  834. pos = self.canvas.translate_coords(event_pos)
  835. event.xdata, event.ydata = pos[0], pos[1]
  836. if event_is_dragging is True:
  837. self.mouse_is_dragging = True
  838. else:
  839. self.mouse_is_dragging = False
  840. try:
  841. x = float(event.xdata)
  842. y = float(event.ydata)
  843. except TypeError:
  844. return
  845. if self.app.grid_status() == True:
  846. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  847. else:
  848. snap_x, snap_y = x, y
  849. self.x_pos, self.y_pos = snap_x, snap_y
  850. # #################################################
  851. # ### This section makes the cutting geo to #######
  852. # ### rotate if it intersects the target geo ######
  853. # #################################################
  854. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  855. man_geo = self.man_cutout_obj.solid_geometry
  856. def get_angle(geo):
  857. line = cut_geo.intersection(geo)
  858. try:
  859. pt1_x = line.coords[0][0]
  860. pt1_y = line.coords[0][1]
  861. pt2_x = line.coords[1][0]
  862. pt2_y = line.coords[1][1]
  863. dx = pt1_x - pt2_x
  864. dy = pt1_y - pt2_y
  865. if dx == 0 or dy == 0:
  866. angle = 0
  867. else:
  868. radian = math.atan(dx / dy)
  869. angle = radian * 180 / math.pi
  870. except Exception as e:
  871. angle = 0
  872. return angle
  873. try:
  874. rot_angle = 0
  875. for geo_el in man_geo:
  876. if isinstance(geo_el, Polygon):
  877. work_geo = geo_el.exterior
  878. if cut_geo.intersects(work_geo):
  879. rot_angle = get_angle(geo=work_geo)
  880. else:
  881. rot_angle = 0
  882. else:
  883. rot_angle = 0
  884. if cut_geo.intersects(geo_el):
  885. rot_angle = get_angle(geo=geo_el)
  886. if rot_angle != 0:
  887. break
  888. except TypeError:
  889. if isinstance(man_geo, Polygon):
  890. work_geo = man_geo.exterior
  891. if cut_geo.intersects(work_geo):
  892. rot_angle = get_angle(geo=work_geo)
  893. else:
  894. rot_angle = 0
  895. else:
  896. rot_angle = 0
  897. if cut_geo.intersects(man_geo):
  898. rot_angle = get_angle(geo=man_geo)
  899. # rotate only if there is an angle to rotate to
  900. if rot_angle != 0:
  901. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  902. # Remove any previous utility shape
  903. self.app.geo_editor.tool_shape.clear(update=True)
  904. self.draw_utility_geometry(geo=cut_geo)
  905. def draw_utility_geometry(self, geo):
  906. self.app.geo_editor.tool_shape.add(
  907. shape=geo,
  908. color=(self.app.defaults["global_draw_color"] + '80'),
  909. update=False,
  910. layer=0,
  911. tolerance=None)
  912. self.app.geo_editor.tool_shape.redraw()
  913. def on_key_press(self, event):
  914. # events out of the self.app.collection view (it's about Project Tab) are of type int
  915. if type(event) is int:
  916. key = event
  917. # events from the GUI are of type QKeyEvent
  918. elif type(event) == QtGui.QKeyEvent:
  919. key = event.key()
  920. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  921. key = event.key
  922. key = QtGui.QKeySequence(key)
  923. # check for modifiers
  924. key_string = key.toString().lower()
  925. if '+' in key_string:
  926. mod, __, key_text = key_string.rpartition('+')
  927. if mod.lower() == 'ctrl':
  928. modifiers = QtCore.Qt.ControlModifier
  929. elif mod.lower() == 'alt':
  930. modifiers = QtCore.Qt.AltModifier
  931. elif mod.lower() == 'shift':
  932. modifiers = QtCore.Qt.ShiftModifier
  933. else:
  934. modifiers = QtCore.Qt.NoModifier
  935. key = QtGui.QKeySequence(key_text)
  936. # events from Vispy are of type KeyEvent
  937. else:
  938. key = event.key
  939. # Escape = Deselect All
  940. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  941. if self.app.is_legacy is False:
  942. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  943. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  944. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  945. else:
  946. self.app.plotcanvas.graph_event_disconnect(self.kp)
  947. self.app.plotcanvas.graph_event_disconnect(self.mm)
  948. self.app.plotcanvas.graph_event_disconnect(self.mr)
  949. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  950. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  951. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  952. self.app.on_mouse_click_release_over_plot)
  953. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  954. # Remove any previous utility shape
  955. self.app.geo_editor.tool_shape.clear(update=True)
  956. self.app.geo_editor.tool_shape.enabled = False
  957. # Grid toggle
  958. if key == QtCore.Qt.Key_G or key == 'G':
  959. self.app.ui.grid_snap_btn.trigger()
  960. # Jump to coords
  961. if key == QtCore.Qt.Key_J or key == 'J':
  962. l_x, l_y = self.app.on_jump_to()
  963. self.app.geo_editor.tool_shape.clear(update=True)
  964. geo = self.cutting_geo(pos=(l_x, l_y))
  965. self.draw_utility_geometry(geo=geo)
  966. def subtract_poly_from_geo(self, solid_geo, x0, y0, x1, y1):
  967. """
  968. Subtract polygon made from points from the given object.
  969. This only operates on the paths in the original geometry,
  970. i.e. it converts polygons into paths.
  971. :param x0: x coord for lower left vertice of the polygon.
  972. :param y0: y coord for lower left vertice of the polygon.
  973. :param x1: x coord for upper right vertice of the polygon.
  974. :param y1: y coord for upper right vertice of the polygon.
  975. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  976. :return: none
  977. """
  978. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  979. # pathonly should be allways True, otherwise polygons are not subtracted
  980. flat_geometry = flatten(geometry=solid_geo)
  981. log.debug("%d paths" % len(flat_geometry))
  982. polygon = Polygon(points)
  983. toolgeo = cascaded_union(polygon)
  984. diffs = []
  985. for target in flat_geometry:
  986. if type(target) == LineString or type(target) == LinearRing:
  987. diffs.append(target.difference(toolgeo))
  988. else:
  989. log.warning("Not implemented.")
  990. return unary_union(diffs)
  991. def reset_fields(self):
  992. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  993. def flatten(geometry):
  994. """
  995. Creates a list of non-iterable linear geometry objects.
  996. Polygons are expanded into its exterior and interiors.
  997. Results are placed in self.flat_geometry
  998. :param geometry: Shapely type or list or list of list of such.
  999. """
  1000. flat_geo = []
  1001. try:
  1002. for geo in geometry:
  1003. if type(geo) == Polygon:
  1004. flat_geo.append(geo.exterior)
  1005. for subgeo in geo.interiors:
  1006. flat_geo.append(subgeo)
  1007. else:
  1008. flat_geo.append(geo)
  1009. except TypeError:
  1010. if type(geometry) == Polygon:
  1011. flat_geo.append(geometry.exterior)
  1012. for subgeo in geometry.interiors:
  1013. flat_geo.append(subgeo)
  1014. else:
  1015. flat_geo.append(geometry)
  1016. return flat_geo
  1017. def recursive_bounds(geometry):
  1018. """
  1019. Returns coordinates of rectangular bounds
  1020. of geometry: (xmin, ymin, xmax, ymax).
  1021. """
  1022. # now it can get bounds for nested lists of objects
  1023. def bounds_rec(obj):
  1024. try:
  1025. minx = Inf
  1026. miny = Inf
  1027. maxx = -Inf
  1028. maxy = -Inf
  1029. for k in obj:
  1030. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1031. minx = min(minx, minx_)
  1032. miny = min(miny, miny_)
  1033. maxx = max(maxx, maxx_)
  1034. maxy = max(maxy, maxy_)
  1035. return minx, miny, maxx, maxy
  1036. except TypeError:
  1037. # it's a Shapely object, return it's bounds
  1038. return obj.bounds
  1039. return bounds_rec(geometry)