ToolCutOut.py 53 KB

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