ToolCutOut.py 53 KB

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