ToolCutOut.py 51 KB

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