ToolCutOut.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. # Gaps
  199. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  200. gaps_label.setToolTip(
  201. _("Number of gaps used for the Automatic cutout.\n"
  202. "There can be maximum 8 bridges/gaps.\n"
  203. "The choices are:\n"
  204. "- None - no gaps\n"
  205. "- lr - left + right\n"
  206. "- tb - top + bottom\n"
  207. "- 4 - left + right +top + bottom\n"
  208. "- 2lr - 2*left + 2*right\n"
  209. "- 2tb - 2*top + 2*bottom\n"
  210. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  211. )
  212. # gaps_label.setMinimumWidth(60)
  213. self.gaps = FCComboBox()
  214. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  215. for it in gaps_items:
  216. self.gaps.addItem(it)
  217. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  218. grid0.addWidget(gaps_label, 19, 0)
  219. grid0.addWidget(self.gaps, 19, 1)
  220. # Buttons
  221. self.ff_cutout_object_btn = FCButton(_("Generate Freeform Geometry"))
  222. self.ff_cutout_object_btn.setToolTip(
  223. _("Cutout the selected object.\n"
  224. "The cutout shape can be of any shape.\n"
  225. "Useful when the PCB has a non-rectangular shape.")
  226. )
  227. self.ff_cutout_object_btn.setStyleSheet("""
  228. QPushButton
  229. {
  230. font-weight: bold;
  231. }
  232. """)
  233. grid0.addWidget(self.ff_cutout_object_btn, 20, 0, 1, 2)
  234. self.rect_cutout_object_btn = FCButton(_("Generate Rectangular Geometry"))
  235. self.rect_cutout_object_btn.setToolTip(
  236. _("Cutout the selected object.\n"
  237. "The resulting cutout shape is\n"
  238. "always a rectangle shape and it will be\n"
  239. "the bounding box of the Object.")
  240. )
  241. self.rect_cutout_object_btn.setStyleSheet("""
  242. QPushButton
  243. {
  244. font-weight: bold;
  245. }
  246. """)
  247. self.layout.addWidget(self.rect_cutout_object_btn)
  248. separator_line = QtWidgets.QFrame()
  249. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  250. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  251. grid0.addWidget(separator_line, 21, 0, 1, 2)
  252. # Title5
  253. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  254. title_manual_label.setToolTip(
  255. _("This section handle creation of manual bridge gaps.\n"
  256. "This is done by mouse clicking on the perimeter of the\n"
  257. "Geometry object that is used as a cutout object. ")
  258. )
  259. grid0.addWidget(title_manual_label, 22, 0, 1, 2)
  260. # Manual Geo Object
  261. self.man_object_combo = FCComboBox()
  262. self.man_object_combo.setModel(self.app.collection)
  263. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  264. self.man_object_combo.is_last = True
  265. self.man_object_combo.obj_type = "Geometry"
  266. self.man_object_label = QtWidgets.QLabel('%s:' % _("Geometry Object"))
  267. self.man_object_label.setToolTip(
  268. _("Geometry object used to create the manual cutout.")
  269. )
  270. # self.man_object_label.setMinimumWidth(60)
  271. grid0.addWidget(self.man_object_label, 23, 0, 1, 2)
  272. grid0.addWidget(self.man_object_combo, 24, 0, 1, 2)
  273. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  274. self.man_geo_creation_btn.setToolTip(
  275. _("If the object to be cutout is a Gerber\n"
  276. "first create a Geometry that surrounds it,\n"
  277. "to be used as the cutout, if one doesn't exist yet.\n"
  278. "Select the source Gerber file in the top object combobox.")
  279. )
  280. self.man_geo_creation_btn.setStyleSheet("""
  281. QPushButton
  282. {
  283. font-weight: bold;
  284. }
  285. """)
  286. grid0.addWidget(self.man_geo_creation_btn, 25, 0, 1, 2)
  287. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  288. self.man_gaps_creation_btn.setToolTip(
  289. _("Use the left mouse button (LMB) click\n"
  290. "to create a bridge gap to separate the PCB from\n"
  291. "the surrounding material.\n"
  292. "The LMB click has to be done on the perimeter of\n"
  293. "the Geometry object used as a cutout geometry.")
  294. )
  295. self.man_gaps_creation_btn.setStyleSheet("""
  296. QPushButton
  297. {
  298. font-weight: bold;
  299. }
  300. """)
  301. grid0.addWidget(self.man_gaps_creation_btn, 27, 0, 1, 2)
  302. self.layout.addStretch()
  303. # ## Reset Tool
  304. self.reset_button = FCButton(_("Reset Tool"))
  305. self.reset_button.setToolTip(
  306. _("Will reset the tool parameters.")
  307. )
  308. self.reset_button.setStyleSheet("""
  309. QPushButton
  310. {
  311. font-weight: bold;
  312. }
  313. """)
  314. self.layout.addWidget(self.reset_button)
  315. self.cutting_gapsize = 0.0
  316. self.cutting_dia = 0.0
  317. # true if we want to repeat the gap without clicking again on the button
  318. self.repeat_gap = False
  319. self.flat_geometry = []
  320. # this is the Geometry object generated in this class to be used for adding manual gaps
  321. self.man_cutout_obj = None
  322. # if mouse is dragging set the object True
  323. self.mouse_is_dragging = False
  324. # event handlers references
  325. self.kp = None
  326. self.mm = None
  327. self.mr = None
  328. # hold the mouse position here
  329. self.x_pos = None
  330. self.y_pos = None
  331. # Signals
  332. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  333. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  334. self.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  335. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  336. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  337. self.reset_button.clicked.connect(self.set_tool_ui)
  338. def on_type_obj_changed(self, val):
  339. obj_type = {'grb': 0, 'geo': 2}[val]
  340. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  341. self.obj_combo.setCurrentIndex(0)
  342. self.obj_combo.obj_type = {"grb": "Gerber", "geo": "Geometry"}[val]
  343. def run(self, toggle=True):
  344. self.app.defaults.report_usage("ToolCutOut()")
  345. if toggle:
  346. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  347. if self.app.ui.splitter.sizes()[0] == 0:
  348. self.app.ui.splitter.setSizes([1, 1])
  349. else:
  350. try:
  351. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  352. # if tab is populated with the tool but it does not have the focus, focus on it
  353. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  354. # focus on Tool Tab
  355. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  356. else:
  357. self.app.ui.splitter.setSizes([0, 1])
  358. except AttributeError:
  359. pass
  360. else:
  361. if self.app.ui.splitter.sizes()[0] == 0:
  362. self.app.ui.splitter.setSizes([1, 1])
  363. FlatCAMTool.run(self)
  364. self.set_tool_ui()
  365. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  366. def install(self, icon=None, separator=None, **kwargs):
  367. FlatCAMTool.install(self, icon, separator, shortcut='Alt+X', **kwargs)
  368. def set_tool_ui(self):
  369. self.reset_fields()
  370. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  371. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  372. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  373. self.cutz_entry.set_value(float(self.app.defaults["tools_cutout_z"]))
  374. self.mpass_cb.set_value(float(self.app.defaults["tools_cutout_mdepth"]))
  375. self.maxdepth_entry.set_value(float(self.app.defaults["tools_cutout_depthperpass"]))
  376. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  377. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  378. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  379. self.type_obj_radio.set_value('grb')
  380. def on_freeform_cutout(self):
  381. log.debug("Cutout.on_freeform_cutout() was launched ...")
  382. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  383. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  384. # obj_.subtract_polygon(pts)
  385. name = self.obj_combo.currentText()
  386. # Get source object.
  387. try:
  388. cutout_obj = self.app.collection.get_by_name(str(name))
  389. except Exception as e:
  390. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  391. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  392. return "Could not retrieve object: %s" % name
  393. if cutout_obj is None:
  394. self.app.inform.emit('[ERROR_NOTCL] %s' %
  395. _("There is no object selected for Cutout.\nSelect one and try again."))
  396. return
  397. dia = float(self.dia.get_value())
  398. if 0 in {dia}:
  399. self.app.inform.emit('[WARNING_NOTCL] %s' %
  400. _("Tool Diameter is zero value. Change it to a positive real number."))
  401. return "Tool Diameter is zero value. Change it to a positive real number."
  402. try:
  403. kind = self.obj_kind_combo.get_value()
  404. except ValueError:
  405. return
  406. margin = float(self.margin.get_value())
  407. gapsize = float(self.gapsize.get_value())
  408. try:
  409. gaps = self.gaps.get_value()
  410. except TypeError:
  411. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  412. return
  413. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  414. self.app.inform.emit('[WARNING_NOTCL] %s' %
  415. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  416. "Fill in a correct value and retry. "))
  417. return
  418. if cutout_obj.multigeo is True:
  419. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  420. "Optionally, this Multi-geo Geometry can be converted to "
  421. "Single-geo Geometry,\n"
  422. "and after that perform Cutout."))
  423. return
  424. convex_box = self.convex_box.get_value()
  425. gapsize = gapsize / 2 + (dia / 2)
  426. def geo_init(geo_obj, app_obj):
  427. solid_geo = []
  428. if cutout_obj.kind == 'gerber':
  429. if isinstance(cutout_obj.solid_geometry, list):
  430. cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
  431. try:
  432. if convex_box:
  433. object_geo = cutout_obj.solid_geometry.convex_hull
  434. else:
  435. object_geo = cutout_obj.solid_geometry
  436. except Exception as err:
  437. log.debug("CutOut.on_freeform_cutout().geo_init() --> %s" % str(err))
  438. object_geo = cutout_obj.solid_geometry
  439. else:
  440. object_geo = cutout_obj.solid_geometry
  441. def cutout_handler(geom):
  442. # Get min and max data for each object as we just cut rectangles across X or Y
  443. xxmin, yymin, xxmax, yymax = recursive_bounds(geom)
  444. px = 0.5 * (xxmin + xxmax) + margin
  445. py = 0.5 * (yymin + yymax) + margin
  446. lenx = (xxmax - xxmin) + (margin * 2)
  447. leny = (yymax - yymin) + (margin * 2)
  448. proc_geometry = []
  449. if gaps == 'None':
  450. pass
  451. else:
  452. if gaps == '8' or gaps == '2LR':
  453. geom = self.subtract_poly_from_geo(geom,
  454. xxmin - gapsize, # botleft_x
  455. py - gapsize + leny / 4, # botleft_y
  456. xxmax + gapsize, # topright_x
  457. py + gapsize + leny / 4) # topright_y
  458. geom = self.subtract_poly_from_geo(geom,
  459. xxmin - gapsize,
  460. py - gapsize - leny / 4,
  461. xxmax + gapsize,
  462. py + gapsize - leny / 4)
  463. if gaps == '8' or gaps == '2TB':
  464. geom = self.subtract_poly_from_geo(geom,
  465. px - gapsize + lenx / 4,
  466. yymin - gapsize,
  467. px + gapsize + lenx / 4,
  468. yymax + gapsize)
  469. geom = self.subtract_poly_from_geo(geom,
  470. px - gapsize - lenx / 4,
  471. yymin - gapsize,
  472. px + gapsize - lenx / 4,
  473. yymax + gapsize)
  474. if gaps == '4' or gaps == 'LR':
  475. geom = self.subtract_poly_from_geo(geom,
  476. xxmin - gapsize,
  477. py - gapsize,
  478. xxmax + gapsize,
  479. py + gapsize)
  480. if gaps == '4' or gaps == 'TB':
  481. geom = self.subtract_poly_from_geo(geom,
  482. px - gapsize,
  483. yymin - gapsize,
  484. px + gapsize,
  485. yymax + gapsize)
  486. try:
  487. for g in geom:
  488. proc_geometry.append(g)
  489. except TypeError:
  490. proc_geometry.append(geom)
  491. return proc_geometry
  492. if kind == 'single':
  493. object_geo = unary_union(object_geo)
  494. # for geo in object_geo:
  495. if cutout_obj.kind == 'gerber':
  496. if isinstance(object_geo, MultiPolygon):
  497. x0, y0, x1, y1 = object_geo.bounds
  498. object_geo = box(x0, y0, x1, y1)
  499. if margin >= 0:
  500. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  501. else:
  502. geo_buf = object_geo.buffer(margin - abs(dia / 2))
  503. geo = geo_buf.exterior
  504. else:
  505. geo = object_geo
  506. solid_geo = cutout_handler(geom=geo)
  507. else:
  508. try:
  509. __ = iter(object_geo)
  510. except TypeError:
  511. object_geo = [object_geo]
  512. for geom_struct in object_geo:
  513. if cutout_obj.kind == 'gerber':
  514. if margin >= 0:
  515. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  516. else:
  517. geom_struct_buff = geom_struct.buffer(-margin + abs(dia / 2))
  518. geom_struct = geom_struct_buff.interiors
  519. solid_geo += cutout_handler(geom=geom_struct)
  520. geo_obj.solid_geometry = deepcopy(solid_geo)
  521. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  522. geo_obj.options['xmin'] = xmin
  523. geo_obj.options['ymin'] = ymin
  524. geo_obj.options['xmax'] = xmax
  525. geo_obj.options['ymax'] = ymax
  526. geo_obj.options['cnctooldia'] = str(dia)
  527. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  528. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  529. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  530. outname = cutout_obj.options["name"] + "_cutout"
  531. self.app.new_object('geometry', outname, geo_init)
  532. cutout_obj.plot()
  533. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  534. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  535. self.app.should_we_save = True
  536. def on_rectangular_cutout(self):
  537. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  538. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  539. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  540. # obj_.subtract_polygon(pts)
  541. name = self.obj_combo.currentText()
  542. # Get source object.
  543. try:
  544. cutout_obj = self.app.collection.get_by_name(str(name))
  545. except Exception as e:
  546. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  547. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  548. return "Could not retrieve object: %s" % name
  549. if cutout_obj is None:
  550. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  551. dia = float(self.dia.get_value())
  552. if 0 in {dia}:
  553. self.app.inform.emit('[ERROR_NOTCL] %s' %
  554. _("Tool Diameter is zero value. Change it to a positive real number."))
  555. return "Tool Diameter is zero value. Change it to a positive real number."
  556. try:
  557. kind = self.obj_kind_combo.get_value()
  558. except ValueError:
  559. return
  560. margin = float(self.margin.get_value())
  561. gapsize = float(self.gapsize.get_value())
  562. try:
  563. gaps = self.gaps.get_value()
  564. except TypeError:
  565. self.app.inform.emit('[WARNING_NOTCL] %s' %
  566. _("Number of gaps value is missing. Add it and retry."))
  567. return
  568. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  569. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  570. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  571. "Fill in a correct value and retry. "))
  572. return
  573. if cutout_obj.multigeo is True:
  574. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  575. "Optionally, this Multi-geo Geometry can be converted to "
  576. "Single-geo Geometry,\n"
  577. "and after that perform Cutout."))
  578. return
  579. # Get min and max data for each object as we just cut rectangles across X or Y
  580. gapsize = gapsize / 2 + (dia / 2)
  581. def geo_init(geo_obj, app_obj):
  582. solid_geo = []
  583. object_geo = cutout_obj.solid_geometry
  584. def cutout_rect_handler(geom):
  585. proc_geometry = []
  586. px = 0.5 * (xmin + xmax) + margin
  587. py = 0.5 * (ymin + ymax) + margin
  588. lenx = (xmax - xmin) + (margin * 2)
  589. leny = (ymax - ymin) + (margin * 2)
  590. if gaps == 'None':
  591. pass
  592. else:
  593. if gaps == '8' or gaps == '2LR':
  594. geom = self.subtract_poly_from_geo(geom,
  595. xmin - gapsize, # botleft_x
  596. py - gapsize + leny / 4, # botleft_y
  597. xmax + gapsize, # topright_x
  598. py + gapsize + leny / 4) # topright_y
  599. geom = self.subtract_poly_from_geo(geom,
  600. xmin - gapsize,
  601. py - gapsize - leny / 4,
  602. xmax + gapsize,
  603. py + gapsize - leny / 4)
  604. if gaps == '8' or gaps == '2TB':
  605. geom = self.subtract_poly_from_geo(geom,
  606. px - gapsize + lenx / 4,
  607. ymin - gapsize,
  608. px + gapsize + lenx / 4,
  609. ymax + gapsize)
  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. if gaps == '4' or gaps == 'LR':
  616. geom = self.subtract_poly_from_geo(geom,
  617. xmin - gapsize,
  618. py - gapsize,
  619. xmax + gapsize,
  620. py + gapsize)
  621. if gaps == '4' or gaps == 'TB':
  622. geom = self.subtract_poly_from_geo(geom,
  623. px - gapsize,
  624. ymin - gapsize,
  625. px + gapsize,
  626. ymax + gapsize)
  627. try:
  628. for g in geom:
  629. proc_geometry.append(g)
  630. except TypeError:
  631. proc_geometry.append(geom)
  632. return proc_geometry
  633. if kind == 'single':
  634. object_geo = unary_union(object_geo)
  635. xmin, ymin, xmax, ymax = object_geo.bounds
  636. geo = box(xmin, ymin, xmax, ymax)
  637. # if Gerber create a buffer at a distance
  638. # if Geometry then cut through the geometry
  639. if cutout_obj.kind == 'gerber':
  640. if margin >= 0:
  641. geo = geo.buffer(margin + abs(dia / 2))
  642. else:
  643. geo = geo.buffer(margin - abs(dia / 2))
  644. solid_geo = cutout_rect_handler(geom=geo)
  645. else:
  646. if cutout_obj.kind == 'geometry':
  647. try:
  648. __ = iter(object_geo)
  649. except TypeError:
  650. object_geo = [object_geo]
  651. for geom_struct in object_geo:
  652. geom_struct = unary_union(geom_struct)
  653. xmin, ymin, xmax, ymax = geom_struct.bounds
  654. geom_struct = box(xmin, ymin, xmax, ymax)
  655. solid_geo += cutout_rect_handler(geom=geom_struct)
  656. elif cutout_obj.kind == 'gerber' and margin >= 0:
  657. try:
  658. __ = iter(object_geo)
  659. except TypeError:
  660. object_geo = [object_geo]
  661. for geom_struct in object_geo:
  662. geom_struct = unary_union(geom_struct)
  663. xmin, ymin, xmax, ymax = geom_struct.bounds
  664. geom_struct = box(xmin, ymin, xmax, ymax)
  665. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  666. solid_geo += cutout_rect_handler(geom=geom_struct)
  667. elif cutout_obj.kind == 'gerber' and margin < 0:
  668. self.app.inform.emit('[WARNING_NOTCL] %s' %
  669. _("Rectangular cutout with negative margin is not possible."))
  670. return "fail"
  671. geo_obj.solid_geometry = deepcopy(solid_geo)
  672. geo_obj.options['cnctooldia'] = str(dia)
  673. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  674. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  675. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  676. outname = cutout_obj.options["name"] + "_cutout"
  677. ret = self.app.new_object('geometry', outname, geo_init)
  678. if ret != 'fail':
  679. # cutout_obj.plot()
  680. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  681. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  682. self.app.should_we_save = True
  683. def on_manual_gap_click(self):
  684. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  685. self.app.geo_editor.tool_shape.enabled = True
  686. self.cutting_dia = float(self.dia.get_value())
  687. if 0 in {self.cutting_dia}:
  688. self.app.inform.emit('[ERROR_NOTCL] %s' %
  689. _("Tool Diameter is zero value. Change it to a positive real number."))
  690. return "Tool Diameter is zero value. Change it to a positive real number."
  691. self.cutting_gapsize = float(self.gapsize.get_value())
  692. name = self.man_object_combo.currentText()
  693. # Get Geometry source object to be used as target for Manual adding Gaps
  694. try:
  695. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  696. except Exception as e:
  697. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  698. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  699. return "Could not retrieve object: %s" % name
  700. if self.app.is_legacy is False:
  701. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  702. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  703. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  704. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  705. else:
  706. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  707. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  708. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  709. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  710. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  711. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  712. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  713. def on_manual_cutout(self, click_pos):
  714. name = self.man_object_combo.currentText()
  715. # Get source object.
  716. try:
  717. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  718. except Exception as e:
  719. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  720. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  721. return "Could not retrieve object: %s" % name
  722. if self.man_cutout_obj is None:
  723. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  724. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  725. return
  726. # use the snapped position as reference
  727. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  728. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  729. self.man_cutout_obj.subtract_polygon(cut_poly)
  730. self.man_cutout_obj.plot()
  731. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  732. self.app.should_we_save = True
  733. def on_manual_geo(self):
  734. name = self.obj_combo.currentText()
  735. # Get source object.
  736. try:
  737. cutout_obj = self.app.collection.get_by_name(str(name))
  738. except Exception as e:
  739. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  740. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  741. return "Could not retrieve object: %s" % name
  742. if cutout_obj is None:
  743. self.app.inform.emit('[ERROR_NOTCL] %s' %
  744. _("There is no Gerber object selected for Cutout.\n"
  745. "Select one and try again."))
  746. return
  747. if cutout_obj.kind != 'gerber':
  748. self.app.inform.emit('[ERROR_NOTCL] %s' %
  749. _("The selected object has to be of Gerber type.\n"
  750. "Select a Gerber file and try again."))
  751. return
  752. dia = float(self.dia.get_value())
  753. if 0 in {dia}:
  754. self.app.inform.emit('[ERROR_NOTCL] %s' %
  755. _("Tool Diameter is zero value. Change it to a positive real number."))
  756. return "Tool Diameter is zero value. Change it to a positive real number."
  757. try:
  758. kind = self.obj_kind_combo.get_value()
  759. except ValueError:
  760. return
  761. margin = float(self.margin.get_value())
  762. convex_box = self.convex_box.get_value()
  763. def geo_init(geo_obj, app_obj):
  764. geo_union = unary_union(cutout_obj.solid_geometry)
  765. if convex_box:
  766. geo = geo_union.convex_hull
  767. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  768. elif kind == 'single':
  769. if isinstance(geo_union, Polygon) or \
  770. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  771. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  772. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  773. elif isinstance(geo_union, MultiPolygon):
  774. x0, y0, x1, y1 = geo_union.bounds
  775. geo = box(x0, y0, x1, y1)
  776. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  777. else:
  778. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  779. (_("Geometry not supported for cutout"), type(geo_union)))
  780. return 'fail'
  781. else:
  782. geo = geo_union
  783. geo = geo.buffer(margin + abs(dia / 2))
  784. if isinstance(geo, Polygon):
  785. geo_obj.solid_geometry = geo.exterior
  786. elif isinstance(geo, MultiPolygon):
  787. solid_geo = []
  788. for poly in geo:
  789. solid_geo.append(poly.exterior)
  790. geo_obj.solid_geometry = deepcopy(solid_geo)
  791. geo_obj.options['cnctooldia'] = str(dia)
  792. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  793. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  794. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  795. outname = cutout_obj.options["name"] + "_cutout"
  796. self.app.new_object('geometry', outname, geo_init)
  797. def cutting_geo(self, pos):
  798. self.cutting_dia = float(self.dia.get_value())
  799. self.cutting_gapsize = float(self.gapsize.get_value())
  800. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  801. # cutting area definition
  802. orig_x = pos[0]
  803. orig_y = pos[1]
  804. xmin = orig_x - offset
  805. ymin = orig_y - offset
  806. xmax = orig_x + offset
  807. ymax = orig_y + offset
  808. cut_poly = box(xmin, ymin, xmax, ymax)
  809. return cut_poly
  810. # To be called after clicking on the plot.
  811. def on_mouse_click_release(self, event):
  812. if self.app.is_legacy is False:
  813. event_pos = event.pos
  814. # event_is_dragging = event.is_dragging
  815. right_button = 2
  816. else:
  817. event_pos = (event.xdata, event.ydata)
  818. # event_is_dragging = self.app.plotcanvas.is_dragging
  819. right_button = 3
  820. try:
  821. x = float(event_pos[0])
  822. y = float(event_pos[1])
  823. except TypeError:
  824. return
  825. event_pos = (x, y)
  826. # do paint single only for left mouse clicks
  827. if event.button == 1:
  828. self.app.inform.emit(_("Making manual bridge gap..."))
  829. pos = self.app.plotcanvas.translate_coords(event_pos)
  830. self.on_manual_cutout(click_pos=pos)
  831. # if RMB then we exit
  832. elif event.button == right_button and self.mouse_is_dragging is False:
  833. if self.app.is_legacy is False:
  834. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  835. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  836. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  837. else:
  838. self.app.plotcanvas.graph_event_disconnect(self.kp)
  839. self.app.plotcanvas.graph_event_disconnect(self.mm)
  840. self.app.plotcanvas.graph_event_disconnect(self.mr)
  841. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  842. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  843. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  844. self.app.on_mouse_click_release_over_plot)
  845. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  846. # Remove any previous utility shape
  847. self.app.geo_editor.tool_shape.clear(update=True)
  848. self.app.geo_editor.tool_shape.enabled = False
  849. def on_mouse_move(self, event):
  850. self.app.on_mouse_move_over_plot(event=event)
  851. if self.app.is_legacy is False:
  852. event_pos = event.pos
  853. event_is_dragging = event.is_dragging
  854. # right_button = 2
  855. else:
  856. event_pos = (event.xdata, event.ydata)
  857. event_is_dragging = self.app.plotcanvas.is_dragging
  858. # right_button = 3
  859. try:
  860. x = float(event_pos[0])
  861. y = float(event_pos[1])
  862. except TypeError:
  863. return
  864. event_pos = (x, y)
  865. pos = self.canvas.translate_coords(event_pos)
  866. event.xdata, event.ydata = pos[0], pos[1]
  867. if event_is_dragging is True:
  868. self.mouse_is_dragging = True
  869. else:
  870. self.mouse_is_dragging = False
  871. try:
  872. x = float(event.xdata)
  873. y = float(event.ydata)
  874. except TypeError:
  875. return
  876. if self.app.grid_status():
  877. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  878. else:
  879. snap_x, snap_y = x, y
  880. self.x_pos, self.y_pos = snap_x, snap_y
  881. # #################################################
  882. # ### This section makes the cutting geo to #######
  883. # ### rotate if it intersects the target geo ######
  884. # #################################################
  885. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  886. man_geo = self.man_cutout_obj.solid_geometry
  887. def get_angle(geo):
  888. line = cut_geo.intersection(geo)
  889. try:
  890. pt1_x = line.coords[0][0]
  891. pt1_y = line.coords[0][1]
  892. pt2_x = line.coords[1][0]
  893. pt2_y = line.coords[1][1]
  894. dx = pt1_x - pt2_x
  895. dy = pt1_y - pt2_y
  896. if dx == 0 or dy == 0:
  897. angle = 0
  898. else:
  899. radian = math.atan(dx / dy)
  900. angle = radian * 180 / math.pi
  901. except Exception:
  902. angle = 0
  903. return angle
  904. try:
  905. rot_angle = 0
  906. for geo_el in man_geo:
  907. if isinstance(geo_el, Polygon):
  908. work_geo = geo_el.exterior
  909. if cut_geo.intersects(work_geo):
  910. rot_angle = get_angle(geo=work_geo)
  911. else:
  912. rot_angle = 0
  913. else:
  914. rot_angle = 0
  915. if cut_geo.intersects(geo_el):
  916. rot_angle = get_angle(geo=geo_el)
  917. if rot_angle != 0:
  918. break
  919. except TypeError:
  920. if isinstance(man_geo, Polygon):
  921. work_geo = man_geo.exterior
  922. if cut_geo.intersects(work_geo):
  923. rot_angle = get_angle(geo=work_geo)
  924. else:
  925. rot_angle = 0
  926. else:
  927. rot_angle = 0
  928. if cut_geo.intersects(man_geo):
  929. rot_angle = get_angle(geo=man_geo)
  930. # rotate only if there is an angle to rotate to
  931. if rot_angle != 0:
  932. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  933. # Remove any previous utility shape
  934. self.app.geo_editor.tool_shape.clear(update=True)
  935. self.draw_utility_geometry(geo=cut_geo)
  936. def draw_utility_geometry(self, geo):
  937. self.app.geo_editor.tool_shape.add(
  938. shape=geo,
  939. color=(self.app.defaults["global_draw_color"] + '80'),
  940. update=False,
  941. layer=0,
  942. tolerance=None)
  943. self.app.geo_editor.tool_shape.redraw()
  944. def on_key_press(self, event):
  945. # events out of the self.app.collection view (it's about Project Tab) are of type int
  946. if type(event) is int:
  947. key = event
  948. # events from the GUI are of type QKeyEvent
  949. elif type(event) == QtGui.QKeyEvent:
  950. key = event.key()
  951. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  952. key = event.key
  953. key = QtGui.QKeySequence(key)
  954. # check for modifiers
  955. key_string = key.toString().lower()
  956. if '+' in key_string:
  957. mod, __, key_text = key_string.rpartition('+')
  958. if mod.lower() == 'ctrl':
  959. # modifiers = QtCore.Qt.ControlModifier
  960. pass
  961. elif mod.lower() == 'alt':
  962. # modifiers = QtCore.Qt.AltModifier
  963. pass
  964. elif mod.lower() == 'shift':
  965. # modifiers = QtCore.Qt.ShiftModifier
  966. pass
  967. else:
  968. # modifiers = QtCore.Qt.NoModifier
  969. pass
  970. key = QtGui.QKeySequence(key_text)
  971. # events from Vispy are of type KeyEvent
  972. else:
  973. key = event.key
  974. # Escape = Deselect All
  975. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  976. if self.app.is_legacy is False:
  977. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  978. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  979. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  980. else:
  981. self.app.plotcanvas.graph_event_disconnect(self.kp)
  982. self.app.plotcanvas.graph_event_disconnect(self.mm)
  983. self.app.plotcanvas.graph_event_disconnect(self.mr)
  984. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  985. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  986. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  987. self.app.on_mouse_click_release_over_plot)
  988. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  989. # Remove any previous utility shape
  990. self.app.geo_editor.tool_shape.clear(update=True)
  991. self.app.geo_editor.tool_shape.enabled = False
  992. # Grid toggle
  993. if key == QtCore.Qt.Key_G or key == 'G':
  994. self.app.ui.grid_snap_btn.trigger()
  995. # Jump to coords
  996. if key == QtCore.Qt.Key_J or key == 'J':
  997. l_x, l_y = self.app.on_jump_to()
  998. self.app.geo_editor.tool_shape.clear(update=True)
  999. geo = self.cutting_geo(pos=(l_x, l_y))
  1000. self.draw_utility_geometry(geo=geo)
  1001. @staticmethod
  1002. def subtract_poly_from_geo(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. :param geometry: a iterable object that holds geometry
  1056. :return: Returns coordinates of rectangular bounds 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)