ToolCutOut.py 51 KB

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