ToolCutOut.py 50 KB

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