ToolCutOut.py 53 KB

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