ToolCutOut.py 51 KB

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