ToolCutOut.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
  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 appTool import AppTool
  9. from appGUI.GUIElements import FCDoubleSpinner, FCCheckBox, RadioSet, FCComboBox, OptionalInputSection, FCButton, \
  10. FCLabel
  11. from shapely.geometry import box, MultiPolygon, Polygon, LineString, LinearRing, MultiLineString
  12. from shapely.ops import unary_union, linemerge
  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 sys
  21. import simplejson as json
  22. import appTranslation as fcTranslate
  23. import builtins
  24. fcTranslate.apply_language('strings')
  25. if '_' not in builtins.__dict__:
  26. _ = gettext.gettext
  27. log = logging.getLogger('base')
  28. settings = QtCore.QSettings("Open Source", "FlatCAM")
  29. if settings.contains("machinist"):
  30. machinist_setting = settings.value('machinist', type=int)
  31. else:
  32. machinist_setting = 0
  33. class CutOut(AppTool):
  34. def __init__(self, app):
  35. AppTool.__init__(self, app)
  36. self.app = app
  37. self.canvas = app.plotcanvas
  38. self.decimals = self.app.decimals
  39. # #############################################################################
  40. # ######################### Tool GUI ##########################################
  41. # #############################################################################
  42. self.ui = CutoutUI(layout=self.layout, app=self.app)
  43. self.toolName = self.ui.toolName
  44. self.cutting_gapsize = 0.0
  45. self.cutting_dia = 0.0
  46. # true if we want to repeat the gap without clicking again on the button
  47. self.repeat_gap = False
  48. self.flat_geometry = []
  49. # this is the Geometry object generated in this class to be used for adding manual gaps
  50. self.man_cutout_obj = None
  51. # if mouse is dragging set the object True
  52. self.mouse_is_dragging = False
  53. # if mouse events are bound to local methods
  54. self.mouse_events_connected = False
  55. # event handlers references
  56. self.kp = None
  57. self.mm = None
  58. self.mr = None
  59. # hold the mouse position here
  60. self.x_pos = None
  61. self.y_pos = None
  62. # store the default data for the resulting Geometry Object
  63. self.default_data = {}
  64. # store the current cursor type to be restored after manual geo
  65. self.old_cursor_type = self.app.defaults["global_cursor_type"]
  66. # store the current selection shape status to be restored after manual geo
  67. self.old_selection_state = self.app.defaults['global_selection_shape']
  68. # store original geometry for manual cutout
  69. self.manual_solid_geo = None
  70. # here will store the original geometry for manual cutout with mouse bytes
  71. self.mb_manual_solid_geo = None
  72. # here will store the geo rests when doing manual cutouts with mouse bites
  73. self.mb_manual_cuts = []
  74. # here store the tool data for the Cutout Tool
  75. self.cut_tool_dict = {}
  76. # Signals
  77. self.ui.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  78. self.ui.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  79. # adding tools
  80. self.ui.add_newtool_button.clicked.connect(lambda: self.on_tool_add())
  81. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  82. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  83. self.ui.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  84. self.ui.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  85. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  86. def on_type_obj_changed(self, val):
  87. obj_type = {'grb': 0, 'geo': 2}[val]
  88. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  89. self.ui.obj_combo.setCurrentIndex(0)
  90. self.ui.obj_combo.obj_type = {"grb": "Gerber", "geo": "Geometry"}[val]
  91. if val == 'grb':
  92. self.ui.convex_box_label.setDisabled(False)
  93. self.ui.convex_box_cb.setDisabled(False)
  94. else:
  95. self.ui.convex_box_label.setDisabled(True)
  96. self.ui.convex_box_cb.setDisabled(True)
  97. def run(self, toggle=True):
  98. self.app.defaults.report_usage("ToolCutOut()")
  99. if toggle:
  100. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  101. if self.app.ui.splitter.sizes()[0] == 0:
  102. self.app.ui.splitter.setSizes([1, 1])
  103. else:
  104. try:
  105. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  106. # if tab is populated with the tool but it does not have the focus, focus on it
  107. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  108. # focus on Tool Tab
  109. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  110. else:
  111. self.app.ui.splitter.setSizes([0, 1])
  112. except AttributeError:
  113. pass
  114. else:
  115. if self.app.ui.splitter.sizes()[0] == 0:
  116. self.app.ui.splitter.setSizes([1, 1])
  117. AppTool.run(self)
  118. self.set_tool_ui()
  119. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  120. def install(self, icon=None, separator=None, **kwargs):
  121. AppTool.install(self, icon, separator, shortcut='Alt+X', **kwargs)
  122. def set_tool_ui(self):
  123. self.reset_fields()
  124. # use the current selected object and make it visible in the object combobox
  125. sel_list = self.app.collection.get_selected()
  126. if len(sel_list) == 1:
  127. active = self.app.collection.get_active()
  128. kind = active.kind
  129. if kind == 'gerber':
  130. self.ui.type_obj_radio.set_value('grb')
  131. else:
  132. self.ui.type_obj_radio.set_value('geo')
  133. # run those once so the obj_type attribute is updated for the FCComboboxes
  134. # so the last loaded object is displayed
  135. if kind == 'gerber':
  136. self.on_type_obj_changed(val='grb')
  137. else:
  138. self.on_type_obj_changed(val='geo')
  139. self.ui.obj_combo.set_value(active.options['name'])
  140. else:
  141. kind = 'gerber'
  142. self.ui.type_obj_radio.set_value('grb')
  143. # run those once so the obj_type attribute is updated for the FCComboboxes
  144. # so the last loaded object is displayed
  145. if kind == 'gerber':
  146. self.on_type_obj_changed(val='grb')
  147. else:
  148. self.on_type_obj_changed(val='geo')
  149. self.ui.dia.set_value(float(self.app.defaults["tools_cutout_tooldia"]))
  150. self.default_data.update({
  151. "plot": True,
  152. "cutz": float(self.app.defaults["geometry_cutz"]),
  153. "multidepth": self.app.defaults["geometry_multidepth"],
  154. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  155. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  156. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  157. "travelz": float(self.app.defaults["geometry_travelz"]),
  158. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  159. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  160. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  161. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  162. "dwell": self.app.defaults["geometry_dwell"],
  163. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  164. "spindledir": self.app.defaults["geometry_spindledir"],
  165. "ppname_g": self.app.defaults["geometry_ppname_g"],
  166. "extracut": self.app.defaults["geometry_extracut"],
  167. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  168. "toolchange": self.app.defaults["geometry_toolchange"],
  169. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  170. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  171. "startz": self.app.defaults["geometry_startz"],
  172. "endz": float(self.app.defaults["geometry_endz"]),
  173. "endxy": self.app.defaults["geometry_endxy"],
  174. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  175. "area_shape": self.app.defaults["geometry_area_shape"],
  176. "area_strategy": self.app.defaults["geometry_area_strategy"],
  177. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  178. "optimization_type": self.app.defaults["geometry_optimization_type"],
  179. # Cutout
  180. "tools_cutout_tooldia": self.app.defaults["tools_cutout_tooldia"],
  181. "tools_cutout_kind": self.app.defaults["tools_cutout_kind"],
  182. "tools_cutout_margin": float(self.app.defaults["tools_cutout_margin"]),
  183. "tools_cutout_z": float(self.app.defaults["tools_cutout_z"]),
  184. "tools_cutout_depthperpass": float(self.app.defaults["tools_cutout_depthperpass"]),
  185. "tools_cutout_mdepth": self.app.defaults["tools_cutout_mdepth"],
  186. "tools_cutout_gapsize": float(self.app.defaults["tools_cutout_gapsize"]),
  187. "tools_cutout_gaps_ff": self.app.defaults["tools_cutout_gaps_ff"],
  188. "tools_cutout_convexshape": self.app.defaults["tools_cutout_convexshape"],
  189. "tools_cutout_big_cursor": self.app.defaults["tools_cutout_big_cursor"],
  190. "tools_cutout_gap_type": self.app.defaults["tools_cutout_gap_type"],
  191. "tools_cutout_gap_depth": float(self.app.defaults["tools_cutout_gap_depth"]),
  192. "tools_cutout_mb_dia": float(self.app.defaults["tools_cutout_mb_dia"]),
  193. "tools_cutout_mb_spacing": float(self.app.defaults["tools_cutout_mb_spacing"]),
  194. })
  195. tool_dia = float(self.app.defaults["tools_cutout_tooldia"])
  196. self.on_tool_add(custom_dia=tool_dia)
  197. def update_ui(self, tool_dict):
  198. self.ui.obj_kind_combo.set_value(self.default_data["tools_cutout_kind"])
  199. self.ui.big_cursor_cb.set_value(self.default_data['tools_cutout_big_cursor'])
  200. # Entries that may be updated from database
  201. self.ui.margin.set_value(float(tool_dict["tools_cutout_margin"]))
  202. self.ui.gapsize.set_value(float(tool_dict["tools_cutout_gapsize"]))
  203. self.ui.gaptype_radio.set_value(tool_dict["tools_cutout_gap_type"])
  204. self.ui.thin_depth_entry.set_value(float(tool_dict["tools_cutout_gap_depth"]))
  205. self.ui.mb_dia_entry.set_value(float(tool_dict["tools_cutout_mb_dia"]))
  206. self.ui.mb_spacing_entry.set_value(float(tool_dict["tools_cutout_mb_spacing"]))
  207. self.ui.convex_box_cb.set_value(tool_dict['tools_cutout_convexshape'])
  208. self.ui.gaps.set_value(tool_dict["tools_cutout_gaps_ff"])
  209. self.ui.cutz_entry.set_value(float(tool_dict["tools_cutout_z"]))
  210. self.ui.mpass_cb.set_value(float(tool_dict["tools_cutout_mdepth"]))
  211. self.ui.maxdepth_entry.set_value(float(tool_dict["tools_cutout_depthperpass"]))
  212. def on_tool_add(self, custom_dia=None):
  213. self.blockSignals(True)
  214. filename = self.app.tools_database_path()
  215. new_tools_dict = deepcopy(self.default_data)
  216. updated_tooldia = None
  217. # determine the new tool diameter
  218. if custom_dia is None:
  219. tool_dia = self.ui.dia.get_value()
  220. else:
  221. tool_dia = custom_dia
  222. if tool_dia is None or tool_dia == 0:
  223. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  224. "in Float format."))
  225. self.blockSignals(False)
  226. return
  227. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  228. # load the database tools from the file
  229. try:
  230. with open(filename) as f:
  231. tools = f.read()
  232. except IOError:
  233. self.app.log.error("Could not load tools DB file.")
  234. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  235. self.blockSignals(False)
  236. self.on_tool_default_add(dia=tool_dia)
  237. return
  238. try:
  239. # store here the tools from Tools Database when searching in Tools Database
  240. tools_db_dict = json.loads(tools)
  241. except Exception:
  242. e = sys.exc_info()[0]
  243. self.app.log.error(str(e))
  244. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  245. self.blockSignals(False)
  246. self.on_tool_default_add(dia=tool_dia)
  247. return
  248. tool_found = 0
  249. offset = 'Path'
  250. offset_val = 0.0
  251. typ = _("Rough")
  252. tool_type = 'V'
  253. # look in database tools
  254. for db_tool, db_tool_val in tools_db_dict.items():
  255. offset = db_tool_val['offset']
  256. offset_val = db_tool_val['offset_value']
  257. typ = db_tool_val['type']
  258. tool_type = db_tool_val['tool_type']
  259. db_tooldia = db_tool_val['tooldia']
  260. low_limit = float(db_tool_val['data']['tol_min'])
  261. high_limit = float(db_tool_val['data']['tol_max'])
  262. # we need only tool marked for Cutout Tool
  263. if db_tool_val['data']['tool_target'] != _('Cutout'):
  264. continue
  265. # if we find a tool with the same diameter in the Tools DB just update it's data
  266. if truncated_tooldia == db_tooldia:
  267. tool_found += 1
  268. for d in db_tool_val['data']:
  269. if d.find('tools_cutout') == 0:
  270. new_tools_dict[d] = db_tool_val['data'][d]
  271. elif d.find('tools_') == 0:
  272. # don't need data for other App Tools; this tests after 'tools_drill_'
  273. continue
  274. else:
  275. new_tools_dict[d] = db_tool_val['data'][d]
  276. # search for a tool that has a tolerance that the tool fits in
  277. elif high_limit >= truncated_tooldia >= low_limit:
  278. tool_found += 1
  279. updated_tooldia = db_tooldia
  280. for d in db_tool_val['data']:
  281. if d.find('tools_cutout') == 0:
  282. new_tools_dict[d] = db_tool_val['data'][d]
  283. elif d.find('tools_') == 0:
  284. # don't need data for other App Tools; this tests after 'tools_drill_'
  285. continue
  286. else:
  287. new_tools_dict[d] = db_tool_val['data'][d]
  288. # test we found a suitable tool in Tools Database or if multiple ones
  289. if tool_found == 0:
  290. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Tool not in Tools Database. Adding a default tool."))
  291. self.on_tool_default_add()
  292. self.blockSignals(False)
  293. return
  294. if tool_found > 1:
  295. self.app.inform.emit(
  296. '[WARNING_NOTCL] %s' % _("Cancelled.\n"
  297. "Multiple tools for one tool diameter found in Tools Database."))
  298. self.blockSignals(False)
  299. return
  300. # FIXME when the Geometry UI milling functionality will be transferred in the Milling Tool this needs changes
  301. new_tools_dict["tools_cutout_z"] = deepcopy(new_tools_dict["cutz"])
  302. new_tools_dict["tools_cutout_mdepth"] = deepcopy(new_tools_dict["multidepth"])
  303. new_tools_dict["tools_cutout_depthperpass"] = deepcopy(new_tools_dict["depthperpass"])
  304. new_tdia = deepcopy(updated_tooldia) if updated_tooldia is not None else deepcopy(truncated_tooldia)
  305. self.cut_tool_dict.update({
  306. 'tooldia': new_tdia,
  307. 'offset': deepcopy(offset),
  308. 'offset_value': deepcopy(offset_val),
  309. 'type': deepcopy(typ),
  310. 'tool_type': deepcopy(tool_type),
  311. 'data': deepcopy(new_tools_dict),
  312. 'solid_geometry': []
  313. })
  314. self.update_ui(new_tools_dict)
  315. self.blockSignals(False)
  316. self.app.inform.emit('[success] %s' % _("Updated tool from Tools Database."))
  317. def on_tool_default_add(self, dia=None, muted=None):
  318. dia = dia
  319. self.default_data.update({
  320. "plot": True,
  321. "cutz": float(self.app.defaults["geometry_cutz"]),
  322. "multidepth": self.app.defaults["geometry_multidepth"],
  323. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  324. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  325. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  326. "travelz": float(self.app.defaults["geometry_travelz"]),
  327. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  328. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  329. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  330. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  331. "dwell": self.app.defaults["geometry_dwell"],
  332. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  333. "spindledir": self.app.defaults["geometry_spindledir"],
  334. "ppname_g": self.app.defaults["geometry_ppname_g"],
  335. "extracut": self.app.defaults["geometry_extracut"],
  336. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  337. "toolchange": self.app.defaults["geometry_toolchange"],
  338. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  339. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  340. "startz": self.app.defaults["geometry_startz"],
  341. "endz": float(self.app.defaults["geometry_endz"]),
  342. "endxy": self.app.defaults["geometry_endxy"],
  343. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  344. "area_shape": self.app.defaults["geometry_area_shape"],
  345. "area_strategy": self.app.defaults["geometry_area_strategy"],
  346. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  347. "optimization_type": self.app.defaults["geometry_optimization_type"],
  348. # Cutout
  349. "tools_cutout_tooldia": self.app.defaults["tools_cutout_tooldia"],
  350. "tools_cutout_kind": self.app.defaults["tools_cutout_kind"],
  351. "tools_cutout_margin": float(self.app.defaults["tools_cutout_margin"]),
  352. "tools_cutout_z": float(self.app.defaults["tools_cutout_z"]),
  353. "tools_cutout_depthperpass": float(self.app.defaults["tools_cutout_depthperpass"]),
  354. "tools_cutout_mdepth": self.app.defaults["tools_cutout_mdepth"],
  355. "tools_cutout_gapsize": float(self.app.defaults["tools_cutout_gapsize"]),
  356. "tools_cutout_gaps_ff": self.app.defaults["tools_cutout_gaps_ff"],
  357. "tools_cutout_convexshape": self.app.defaults["tools_cutout_convexshape"],
  358. "tools_cutout_big_cursor": self.app.defaults["tools_cutout_big_cursor"],
  359. "tools_cutout_gap_type": self.app.defaults["tools_cutout_gap_type"],
  360. "tools_cutout_gap_depth": float(self.app.defaults["tools_cutout_gap_depth"]),
  361. "tools_cutout_mb_dia": float(self.app.defaults["tools_cutout_mb_dia"]),
  362. "tools_cutout_mb_spacing": float(self.app.defaults["tools_cutout_mb_spacing"]),
  363. })
  364. self.cut_tool_dict.update({
  365. 'tooldia': str(self.app.defaults["tools_cutout_tooldia"]),
  366. 'offset': 'Path',
  367. 'offset_value': 0.0,
  368. 'type': _('Rough'),
  369. 'tool_type': 'C1',
  370. 'data': deepcopy(self.default_data),
  371. 'solid_geometry': []
  372. })
  373. self.update_ui(self.default_data)
  374. if muted is None:
  375. self.app.inform.emit('[success] %s' % _("Default tool added."))
  376. def on_cutout_tool_add_from_db_executed(self, tool):
  377. """
  378. Here add the tool from DB in the selected geometry object
  379. :return:
  380. """
  381. if tool['data']['tool_target'] not in [0, 6]: # [General, Cutout Tool]
  382. for idx in range(self.app.ui.plot_tab_area.count()):
  383. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  384. wdg = self.app.ui.plot_tab_area.widget(idx)
  385. wdg.deleteLater()
  386. self.app.ui.plot_tab_area.removeTab(idx)
  387. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  388. return
  389. tool_from_db = deepcopy(self.default_data)
  390. tool_from_db.update(tool)
  391. # FIXME when the Geometry UI milling functionality will be transferred in the Milling Tool this needs changes
  392. tool_from_db['data']["tools_cutout_tooldia"] = deepcopy(tool["tooldia"])
  393. tool_from_db['data']["tools_cutout_z"] = deepcopy(tool_from_db['data']["cutz"])
  394. tool_from_db['data']["tools_cutout_mdepth"] = deepcopy(tool_from_db['data']["multidepth"])
  395. tool_from_db['data']["tools_cutout_depthperpass"] = deepcopy(tool_from_db['data']["depthperpass"])
  396. self.cut_tool_dict.update(tool_from_db)
  397. self.cut_tool_dict['solid_geometry'] = []
  398. self.update_ui(tool_from_db['data'])
  399. self.ui.dia.set_value(float(tool_from_db['data']["tools_cutout_tooldia"]))
  400. for idx in range(self.app.ui.plot_tab_area.count()):
  401. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  402. wdg = self.app.ui.plot_tab_area.widget(idx)
  403. wdg.deleteLater()
  404. self.app.ui.plot_tab_area.removeTab(idx)
  405. self.app.inform.emit('[success] %s' % _("Tool updated from Tools Database."))
  406. def on_tool_from_db_inserted(self, tool):
  407. """
  408. Called from the Tools DB object through a App method when adding a tool from Tools Database
  409. :param tool: a dict with the tool data
  410. :return: None
  411. """
  412. tooldia = float(tool['tooldia'])
  413. truncated_tooldia = self.app.dec_format(tooldia, self.decimals)
  414. self.cutout_tools.update({
  415. 1: {
  416. 'tooldia': truncated_tooldia,
  417. 'offset': tool['offset'],
  418. 'offset_value': tool['offset_value'],
  419. 'type': tool['type'],
  420. 'tool_type': tool['tool_type'],
  421. 'data': deepcopy(tool['data']),
  422. 'solid_geometry': []
  423. }
  424. })
  425. self.cutout_tools[1]['data']['name'] = '_cutout'
  426. return 1
  427. def on_tool_add_from_db_clicked(self):
  428. """
  429. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  430. and display the Tools Database tab in the form needed for the Tool adding
  431. :return: None
  432. """
  433. # if the Tools Database is already opened focus on it
  434. for idx in range(self.app.ui.plot_tab_area.count()):
  435. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  436. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  437. break
  438. ret_val = self.app.on_tools_database(source='cutout')
  439. if ret_val == 'fail':
  440. return
  441. self.app.tools_db_tab.ok_to_add = True
  442. self.app.tools_db_tab.ui.buttons_frame.hide()
  443. self.app.tools_db_tab.ui.add_tool_from_db.show()
  444. self.app.tools_db_tab.ui.cancel_tool_from_db.show()
  445. def on_freeform_cutout(self):
  446. log.debug("Cutout.on_freeform_cutout() was launched ...")
  447. name = self.ui.obj_combo.currentText()
  448. # Get source object.
  449. try:
  450. cutout_obj = self.app.collection.get_by_name(str(name))
  451. except Exception as e:
  452. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  453. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  454. return "Could not retrieve object: %s" % name
  455. if cutout_obj is None:
  456. self.app.inform.emit('[ERROR_NOTCL] %s' %
  457. _("There is no object selected for Cutout.\nSelect one and try again."))
  458. return
  459. dia = self.ui.dia.get_value()
  460. if 0 in {dia}:
  461. self.app.inform.emit('[WARNING_NOTCL] %s' %
  462. _("Tool Diameter is zero value. Change it to a positive real number."))
  463. return "Tool Diameter is zero value. Change it to a positive real number."
  464. try:
  465. kind = self.ui.obj_kind_combo.get_value()
  466. except ValueError:
  467. return
  468. margin = self.ui.margin.get_value()
  469. try:
  470. gaps = self.ui.gaps.get_value()
  471. except TypeError:
  472. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  473. return
  474. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  475. self.app.inform.emit('[WARNING_NOTCL] %s' %
  476. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  477. "Fill in a correct value and retry. "))
  478. return
  479. # if cutout_obj.multigeo is True:
  480. # self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  481. # "Optionally, this Multi-geo Geometry can be converted to "
  482. # "Single-geo Geometry,\n"
  483. # "and after that perform Cutout."))
  484. # return
  485. def cutout_handler(geom, gapsize):
  486. proc_geometry = []
  487. rest_geometry = []
  488. r_temp_geo = []
  489. initial_geo = deepcopy(geom)
  490. # Get min and max data for each object as we just cut rectangles across X or Y
  491. xxmin, yymin, xxmax, yymax = CutOut.recursive_bounds(geom)
  492. px = 0.5 * (xxmin + xxmax) + margin
  493. py = 0.5 * (yymin + yymax) + margin
  494. lenx = (xxmax - xxmin) + (margin * 2)
  495. leny = (yymax - yymin) + (margin * 2)
  496. if gaps == 'None':
  497. pass
  498. else:
  499. if gaps == '8' or gaps == '2LR':
  500. points = (
  501. xxmin - gapsize, # botleft_x
  502. py - gapsize + leny / 4, # botleft_y
  503. xxmax + gapsize, # topright_x
  504. py + gapsize + leny / 4 # topright_y
  505. )
  506. geom = self.subtract_poly_from_geo(geom, points)
  507. r_temp_geo.append(
  508. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  509. )
  510. points = (
  511. xxmin - gapsize,
  512. py - gapsize - leny / 4,
  513. xxmax + gapsize,
  514. py + gapsize - leny / 4
  515. )
  516. geom = self.subtract_poly_from_geo(geom, points)
  517. r_temp_geo.append(
  518. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  519. )
  520. if gaps == '8' or gaps == '2TB':
  521. points = (
  522. px - gapsize + lenx / 4,
  523. yymin - gapsize,
  524. px + gapsize + lenx / 4,
  525. yymax + gapsize
  526. )
  527. geom = self.subtract_poly_from_geo(geom, points)
  528. r_temp_geo.append(
  529. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  530. )
  531. points = (
  532. px - gapsize - lenx / 4,
  533. yymin - gapsize,
  534. px + gapsize - lenx / 4,
  535. yymax + gapsize
  536. )
  537. geom = self.subtract_poly_from_geo(geom, points)
  538. r_temp_geo.append(
  539. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  540. )
  541. if gaps == '4' or gaps == 'LR':
  542. points = (
  543. xxmin - gapsize,
  544. py - gapsize,
  545. xxmax + gapsize,
  546. py + gapsize
  547. )
  548. geom = self.subtract_poly_from_geo(geom, points)
  549. r_temp_geo.append(
  550. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  551. )
  552. if gaps == '4' or gaps == 'TB':
  553. points = (
  554. px - gapsize,
  555. yymin - gapsize,
  556. px + gapsize,
  557. yymax + gapsize
  558. )
  559. geom = self.subtract_poly_from_geo(geom, points)
  560. r_temp_geo.append(
  561. self.intersect_geo(initial_geo, box(points[0], points[1], points[2], points[3]))
  562. )
  563. try:
  564. for g in geom:
  565. if g and not g.is_empty:
  566. proc_geometry.append(g)
  567. except TypeError:
  568. if geom and not geom.is_empty:
  569. proc_geometry.append(geom)
  570. r_temp_geo = CutOut.flatten(r_temp_geo)
  571. for g in r_temp_geo:
  572. if g and not g.is_empty:
  573. rest_geometry.append(g)
  574. return proc_geometry, rest_geometry
  575. with self.app.proc_container.new("Generating Cutout ..."):
  576. outname = cutout_obj.options["name"] + "_cutout"
  577. self.app.collection.promise(outname)
  578. has_mouse_bites = True if self.ui.gaptype_radio.get_value() == 'mb' else False
  579. outname_exc = cutout_obj.options["name"] + "_mouse_bites"
  580. if has_mouse_bites is True:
  581. self.app.collection.promise(outname_exc)
  582. def job_thread(app_obj):
  583. solid_geo = []
  584. gaps_solid_geo = []
  585. mouse_bites_geo = []
  586. convex_box = self.ui.convex_box_cb.get_value()
  587. gapsize = self.ui.gapsize.get_value()
  588. gapsize = gapsize / 2 + (dia / 2)
  589. mb_dia = self.ui.mb_dia_entry.get_value()
  590. mb_buff_val = mb_dia / 2.0
  591. mb_spacing = self.ui.mb_spacing_entry.get_value()
  592. gap_type = self.ui.gaptype_radio.get_value()
  593. thin_entry = self.ui.thin_depth_entry.get_value()
  594. if cutout_obj.kind == 'gerber':
  595. if isinstance(cutout_obj.solid_geometry, list):
  596. cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
  597. try:
  598. if convex_box:
  599. object_geo = cutout_obj.solid_geometry.convex_hull
  600. else:
  601. object_geo = cutout_obj.solid_geometry
  602. except Exception as err:
  603. log.debug("CutOut.on_freeform_cutout().geo_init() --> %s" % str(err))
  604. object_geo = cutout_obj.solid_geometry
  605. else:
  606. if cutout_obj.multigeo is False:
  607. object_geo = cutout_obj.solid_geometry
  608. else:
  609. # first tool in the tools dict
  610. t_first = list(cutout_obj.tools.keys())[0]
  611. object_geo = cutout_obj.tools[t_first]['solid_geometry']
  612. if kind == 'single':
  613. object_geo = unary_union(object_geo)
  614. # for geo in object_geo:
  615. if cutout_obj.kind == 'gerber':
  616. if isinstance(object_geo, MultiPolygon):
  617. x0, y0, x1, y1 = object_geo.bounds
  618. object_geo = box(x0, y0, x1, y1)
  619. if margin >= 0:
  620. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  621. else:
  622. geo_buf = object_geo.buffer(margin - abs(dia / 2))
  623. geo = geo_buf.exterior
  624. else:
  625. if isinstance(object_geo, MultiPolygon):
  626. x0, y0, x1, y1 = object_geo.bounds
  627. object_geo = box(x0, y0, x1, y1)
  628. geo_buf = object_geo.buffer(0)
  629. geo = geo_buf.exterior
  630. solid_geo, rest_geo = cutout_handler(geom=geo, gapsize=gapsize)
  631. if gap_type == 'bt' and thin_entry != 0:
  632. gaps_solid_geo = rest_geo
  633. else:
  634. try:
  635. __ = iter(object_geo)
  636. except TypeError:
  637. object_geo = [object_geo]
  638. for geom_struct in object_geo:
  639. if cutout_obj.kind == 'gerber':
  640. if margin >= 0:
  641. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  642. else:
  643. geom_struct_buff = geom_struct.buffer(-margin + abs(dia / 2))
  644. geom_struct = geom_struct_buff.interiors
  645. c_geo, r_geo = cutout_handler(geom=geom_struct, gapsize=gapsize)
  646. solid_geo += c_geo
  647. if gap_type == 'bt' and thin_entry != 0:
  648. gaps_solid_geo += r_geo
  649. if not solid_geo:
  650. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  651. return "fail"
  652. solid_geo = linemerge(solid_geo)
  653. if has_mouse_bites is True:
  654. gapsize -= dia / 2
  655. mb_object_geo = deepcopy(object_geo)
  656. if kind == 'single':
  657. mb_object_geo = unary_union(mb_object_geo)
  658. # for geo in object_geo:
  659. if cutout_obj.kind == 'gerber':
  660. if isinstance(mb_object_geo, MultiPolygon):
  661. x0, y0, x1, y1 = mb_object_geo.bounds
  662. mb_object_geo = box(x0, y0, x1, y1)
  663. if margin >= 0:
  664. geo_buf = mb_object_geo.buffer(margin + mb_buff_val)
  665. else:
  666. geo_buf = mb_object_geo.buffer(margin - mb_buff_val)
  667. mb_geo = geo_buf.exterior
  668. else:
  669. if isinstance(mb_object_geo, MultiPolygon):
  670. x0, y0, x1, y1 = mb_object_geo.bounds
  671. mb_object_geo = box(x0, y0, x1, y1)
  672. geo_buf = mb_object_geo.buffer(0)
  673. mb_geo = geo_buf.exterior
  674. __, rest_geo = cutout_handler(geom=mb_geo, gapsize=gapsize)
  675. mouse_bites_geo = rest_geo
  676. else:
  677. try:
  678. __ = iter(mb_object_geo)
  679. except TypeError:
  680. mb_object_geo = [mb_object_geo]
  681. for mb_geom_struct in mb_object_geo:
  682. if cutout_obj.kind == 'gerber':
  683. if margin >= 0:
  684. mb_geom_struct = mb_geom_struct.buffer(margin + mb_buff_val)
  685. mb_geom_struct = mb_geom_struct.exterior
  686. else:
  687. mb_geom_struct = mb_geom_struct.buffer(-margin + mb_buff_val)
  688. mb_geom_struct = mb_geom_struct.interiors
  689. __, mb_r_geo = cutout_handler(geom=mb_geom_struct, gapsize=gapsize)
  690. mouse_bites_geo += mb_r_geo
  691. # list of Shapely Points to mark the drill points centers
  692. holes = []
  693. for line in mouse_bites_geo:
  694. calc_len = 0
  695. while calc_len < line.length:
  696. holes.append(line.interpolate(calc_len))
  697. calc_len += mb_dia + mb_spacing
  698. def geo_init(geo_obj, app_object):
  699. geo_obj.multigeo = True
  700. geo_obj.solid_geometry = deepcopy(solid_geo)
  701. xmin, ymin, xmax, ymax = CutOut.recursive_bounds(geo_obj.solid_geometry)
  702. geo_obj.options['xmin'] = xmin
  703. geo_obj.options['ymin'] = ymin
  704. geo_obj.options['xmax'] = xmax
  705. geo_obj.options['ymax'] = ymax
  706. geo_obj.options['cnctooldia'] = str(dia)
  707. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  708. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  709. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  710. geo_obj.tools[1] = deepcopy(self.cut_tool_dict)
  711. geo_obj.tools[1]['tooldia'] = str(dia)
  712. geo_obj.tools[1]['solid_geometry'] = geo_obj.solid_geometry
  713. geo_obj.tools[1]['data']['name'] = outname
  714. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  715. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  716. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  717. if not gaps_solid_geo:
  718. pass
  719. else:
  720. geo_obj.tools[9999] = deepcopy(self.cut_tool_dict)
  721. geo_obj.tools[9999]['tooldia'] = str(dia)
  722. geo_obj.tools[9999]['solid_geometry'] = gaps_solid_geo
  723. geo_obj.tools[9999]['data']['name'] = outname
  724. geo_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  725. geo_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  726. geo_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  727. # plot this tool in a different color
  728. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  729. def excellon_init(exc_obj, app_o):
  730. if not holes:
  731. return 'fail'
  732. tools = {}
  733. tools[1] = {}
  734. tools[1]["tooldia"] = mb_dia
  735. tools[1]['drills'] = holes
  736. tools[1]['solid_geometry'] = []
  737. exc_obj.tools = tools
  738. exc_obj.create_geometry()
  739. exc_obj.source_file = app_o.f_handlers.export_excellon(obj_name=exc_obj.options['name'],
  740. local_use=exc_obj,filename=None,
  741. use_thread=False)
  742. # calculate the bounds
  743. xmin, ymin, xmax, ymax = CutOut.recursive_bounds(exc_obj.solid_geometry)
  744. exc_obj.options['xmin'] = xmin
  745. exc_obj.options['ymin'] = ymin
  746. exc_obj.options['xmax'] = xmax
  747. exc_obj.options['ymax'] = ymax
  748. try:
  749. if self.ui.gaptype_radio.get_value() == 'mb':
  750. ret = app_obj.app_obj.new_object('excellon', outname_exc, excellon_init)
  751. if ret == 'fail':
  752. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Mouse bites failed."))
  753. ret = app_obj.app_obj.new_object('geometry', outname, geo_init)
  754. if ret == 'fail':
  755. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  756. return
  757. # cutout_obj.plot(plot_tool=1)
  758. app_obj.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  759. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  760. app_obj.should_we_save = True
  761. except Exception as ee:
  762. log.debug(str(ee))
  763. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  764. def on_rectangular_cutout(self):
  765. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  766. name = self.ui.obj_combo.currentText()
  767. # Get source object.
  768. try:
  769. cutout_obj = self.app.collection.get_by_name(str(name))
  770. except Exception as e:
  771. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  772. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  773. return "Could not retrieve object: %s" % name
  774. if cutout_obj is None:
  775. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  776. dia = float(self.ui.dia.get_value())
  777. if 0 in {dia}:
  778. self.app.inform.emit('[ERROR_NOTCL] %s' %
  779. _("Tool Diameter is zero value. Change it to a positive real number."))
  780. return "Tool Diameter is zero value. Change it to a positive real number."
  781. try:
  782. kind = self.ui.obj_kind_combo.get_value()
  783. except ValueError:
  784. return
  785. margin = self.ui.margin.get_value()
  786. try:
  787. gaps = self.ui.gaps.get_value()
  788. except TypeError:
  789. self.app.inform.emit('[WARNING_NOTCL] %s' %
  790. _("Number of gaps value is missing. Add it and retry."))
  791. return
  792. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  793. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  794. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  795. "Fill in a correct value and retry. "))
  796. return
  797. # if cutout_obj.multigeo is True:
  798. # self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  799. # "Optionally, this Multi-geo Geometry can be converted to "
  800. # "Single-geo Geometry,\n"
  801. # "and after that perform Cutout."))
  802. # return
  803. def cutout_rect_handler(geom, gapsize, xmin, ymin, xmax, ymax):
  804. proc_geometry = []
  805. px = 0.5 * (xmin + xmax) + margin
  806. py = 0.5 * (ymin + ymax) + margin
  807. lenx = (xmax - xmin) + (margin * 2)
  808. leny = (ymax - ymin) + (margin * 2)
  809. if gaps == 'None':
  810. pass
  811. else:
  812. if gaps == '8' or gaps == '2LR':
  813. points = (
  814. xmin - gapsize, # botleft_x
  815. py - gapsize + leny / 4, # botleft_y
  816. xmax + gapsize, # topright_x
  817. py + gapsize + leny / 4 # topright_y
  818. )
  819. geom = self.subtract_poly_from_geo(geom, points)
  820. points = (
  821. xmin - gapsize,
  822. py - gapsize - leny / 4,
  823. xmax + gapsize,
  824. py + gapsize - leny / 4
  825. )
  826. geom = self.subtract_poly_from_geo(geom, points)
  827. if gaps == '8' or gaps == '2TB':
  828. points = (
  829. px - gapsize + lenx / 4,
  830. ymin - gapsize,
  831. px + gapsize + lenx / 4,
  832. ymax + gapsize
  833. )
  834. geom = self.subtract_poly_from_geo(geom, points)
  835. points = (
  836. px - gapsize - lenx / 4,
  837. ymin - gapsize,
  838. px + gapsize - lenx / 4,
  839. ymax + gapsize
  840. )
  841. geom = self.subtract_poly_from_geo(geom, points)
  842. if gaps == '4' or gaps == 'LR':
  843. points = (
  844. xmin - gapsize,
  845. py - gapsize,
  846. xmax + gapsize,
  847. py + gapsize
  848. )
  849. geom = self.subtract_poly_from_geo(geom, points)
  850. if gaps == '4' or gaps == 'TB':
  851. points = (
  852. px - gapsize,
  853. ymin - gapsize,
  854. px + gapsize,
  855. ymax + gapsize
  856. )
  857. geom = self.subtract_poly_from_geo(geom, points)
  858. try:
  859. for g in geom:
  860. proc_geometry.append(g)
  861. except TypeError:
  862. proc_geometry.append(geom)
  863. return proc_geometry
  864. with self.app.proc_container.new("Generating Cutout ..."):
  865. outname = cutout_obj.options["name"] + "_cutout"
  866. self.app.collection.promise(outname)
  867. has_mouse_bites = True if self.ui.gaptype_radio.get_value() == 'mb' else False
  868. outname_exc = cutout_obj.options["name"] + "_mouse_bites"
  869. if has_mouse_bites is True:
  870. self.app.collection.promise(outname_exc)
  871. def job_thread(app_obj):
  872. solid_geo = []
  873. gaps_solid_geo = []
  874. mouse_bites_geo = []
  875. gapsize = self.ui.gapsize.get_value()
  876. gapsize = gapsize / 2 + (dia / 2)
  877. mb_dia = self.ui.mb_dia_entry.get_value()
  878. mb_buff_val = mb_dia / 2.0
  879. mb_spacing = self.ui.mb_spacing_entry.get_value()
  880. gap_type = self.ui.gaptype_radio.get_value()
  881. thin_entry = self.ui.thin_depth_entry.get_value()
  882. if cutout_obj.multigeo is False:
  883. object_geo = cutout_obj.solid_geometry
  884. else:
  885. # first tool in the tools dict
  886. t_first = list(cutout_obj.tools.keys())[0]
  887. object_geo = cutout_obj.tools[t_first]['solid_geometry']
  888. if kind == 'single':
  889. # fuse the lines
  890. object_geo = unary_union(object_geo)
  891. xmin, ymin, xmax, ymax = object_geo.bounds
  892. geo = box(xmin, ymin, xmax, ymax)
  893. # if Gerber create a buffer at a distance
  894. # if Geometry then cut through the geometry
  895. if cutout_obj.kind == 'gerber':
  896. if margin >= 0:
  897. geo = geo.buffer(margin + abs(dia / 2))
  898. else:
  899. geo = geo.buffer(margin - abs(dia / 2))
  900. solid_geo = cutout_rect_handler(geo, gapsize, xmin, ymin, xmax, ymax)
  901. if gap_type == 'bt' and thin_entry != 0:
  902. gaps_solid_geo = self.subtract_geo(geo, deepcopy(solid_geo))
  903. else:
  904. if cutout_obj.kind == 'geometry':
  905. try:
  906. __ = iter(object_geo)
  907. except TypeError:
  908. object_geo = [object_geo]
  909. for geom_struct in object_geo:
  910. geom_struct = unary_union(geom_struct)
  911. xmin, ymin, xmax, ymax = geom_struct.bounds
  912. geom_struct = box(xmin, ymin, xmax, ymax)
  913. c_geo = cutout_rect_handler(geom_struct, gapsize, xmin, ymin, xmax, ymax)
  914. solid_geo += c_geo
  915. if gap_type == 'bt' and thin_entry != 0:
  916. try:
  917. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  918. except TypeError:
  919. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  920. elif cutout_obj.kind == 'gerber' and margin >= 0:
  921. try:
  922. __ = iter(object_geo)
  923. except TypeError:
  924. object_geo = [object_geo]
  925. for geom_struct in object_geo:
  926. geom_struct = unary_union(geom_struct)
  927. xmin, ymin, xmax, ymax = geom_struct.bounds
  928. geom_struct = box(xmin, ymin, xmax, ymax)
  929. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  930. c_geo = cutout_rect_handler(geom_struct, gapsize, xmin, ymin, xmax, ymax)
  931. solid_geo += c_geo
  932. if gap_type == 'bt' and thin_entry != 0:
  933. try:
  934. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  935. except TypeError:
  936. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  937. elif cutout_obj.kind == 'gerber' and margin < 0:
  938. app_obj.inform.emit(
  939. '[WARNING_NOTCL] %s' % _("Rectangular cutout with negative margin is not possible."))
  940. return "fail"
  941. if not solid_geo:
  942. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  943. return "fail"
  944. solid_geo = linemerge(solid_geo)
  945. if has_mouse_bites is True:
  946. gapsize -= dia / 2
  947. mb_object_geo = deepcopy(object_geo)
  948. if kind == 'single':
  949. # fuse the lines
  950. mb_object_geo = unary_union(mb_object_geo)
  951. xmin, ymin, xmax, ymax = mb_object_geo.bounds
  952. mb_geo = box(xmin, ymin, xmax, ymax)
  953. # if Gerber create a buffer at a distance
  954. # if Geometry then cut through the geometry
  955. if cutout_obj.kind == 'gerber':
  956. if margin >= 0:
  957. mb_geo = mb_geo.buffer(margin + mb_buff_val)
  958. else:
  959. mb_geo = mb_geo.buffer(margin - mb_buff_val)
  960. else:
  961. mb_geo = mb_geo.buffer(0)
  962. mb_solid_geo = cutout_rect_handler(mb_geo, gapsize, xmin, ymin, xmax, ymax)
  963. mouse_bites_geo = self.subtract_geo(mb_geo, mb_solid_geo)
  964. else:
  965. if cutout_obj.kind == 'geometry':
  966. try:
  967. __ = iter(mb_object_geo)
  968. except TypeError:
  969. mb_object_geo = [mb_object_geo]
  970. for mb_geom_struct in mb_object_geo:
  971. mb_geom_struct = unary_union(mb_geom_struct)
  972. xmin, ymin, xmax, ymax = mb_geom_struct.bounds
  973. mb_geom_struct = box(xmin, ymin, xmax, ymax)
  974. c_geo = cutout_rect_handler(mb_geom_struct, gapsize, xmin, ymin, xmax, ymax)
  975. solid_geo += c_geo
  976. try:
  977. mouse_bites_geo += self.subtract_geo(mb_geom_struct, c_geo)
  978. except TypeError:
  979. mouse_bites_geo.append(self.subtract_geo(mb_geom_struct, c_geo))
  980. elif cutout_obj.kind == 'gerber' and margin >= 0:
  981. try:
  982. __ = iter(mb_object_geo)
  983. except TypeError:
  984. mb_object_geo = [mb_object_geo]
  985. for mb_geom_struct in mb_object_geo:
  986. mb_geom_struct = unary_union(mb_geom_struct)
  987. xmin, ymin, xmax, ymax = mb_geom_struct.bounds
  988. mb_geom_struct = box(xmin, ymin, xmax, ymax)
  989. mb_geom_struct = mb_geom_struct.buffer(margin + mb_buff_val)
  990. c_geo = cutout_rect_handler(mb_geom_struct, gapsize, xmin, ymin, xmax, ymax)
  991. solid_geo += c_geo
  992. try:
  993. mouse_bites_geo += self.subtract_geo(mb_geom_struct, c_geo)
  994. except TypeError:
  995. mouse_bites_geo.append(self.subtract_geo(mb_geom_struct, c_geo))
  996. elif cutout_obj.kind == 'gerber' and margin < 0:
  997. msg = '[WARNING_NOTCL] %s' % \
  998. _("Rectangular cutout with negative margin is not possible.")
  999. app_obj.inform.emit(msg)
  1000. return "fail"
  1001. # list of Shapely Points to mark the drill points centers
  1002. holes = []
  1003. for line in mouse_bites_geo:
  1004. calc_len = 0
  1005. while calc_len < line.length:
  1006. holes.append(line.interpolate(calc_len))
  1007. calc_len += mb_dia + mb_spacing
  1008. def geo_init(geo_obj, application_obj):
  1009. geo_obj.multigeo = True
  1010. geo_obj.solid_geometry = deepcopy(solid_geo)
  1011. geo_obj.options['xmin'] = xmin
  1012. geo_obj.options['ymin'] = ymin
  1013. geo_obj.options['xmax'] = xmax
  1014. geo_obj.options['ymax'] = ymax
  1015. geo_obj.options['cnctooldia'] = str(dia)
  1016. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  1017. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  1018. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1019. geo_obj.tools[1] = deepcopy(self.cut_tool_dict)
  1020. geo_obj.tools[1]['tooldia'] = str(dia)
  1021. geo_obj.tools[1]['solid_geometry'] = geo_obj.solid_geometry
  1022. geo_obj.tools[1]['data']['name'] = outname
  1023. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  1024. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1025. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1026. if not gaps_solid_geo:
  1027. pass
  1028. else:
  1029. geo_obj.tools[9999] = deepcopy(self.cut_tool_dict)
  1030. geo_obj.tools[9999]['tooldia'] = str(dia)
  1031. geo_obj.tools[9999]['solid_geometry'] = gaps_solid_geo
  1032. geo_obj.tools[9999]['data']['name'] = outname
  1033. geo_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  1034. geo_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1035. geo_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1036. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  1037. def excellon_init(exc_obj, app_o):
  1038. if not holes:
  1039. return 'fail'
  1040. tools = {}
  1041. tools[1] = {}
  1042. tools[1]["tooldia"] = mb_dia
  1043. tools[1]['drills'] = holes
  1044. tools[1]['solid_geometry'] = []
  1045. exc_obj.tools = tools
  1046. exc_obj.create_geometry()
  1047. exc_obj.source_file = app_o.f_handlers.export_excellon(obj_name=exc_obj.options['name'],
  1048. local_use=exc_obj,
  1049. filename=None,
  1050. use_thread=False)
  1051. # calculate the bounds
  1052. e_xmin, e_ymin, e_xmax, e_ymax = CutOut.recursive_bounds(exc_obj.solid_geometry)
  1053. exc_obj.options['xmin'] = e_xmin
  1054. exc_obj.options['ymin'] = e_ymin
  1055. exc_obj.options['xmax'] = e_xmax
  1056. exc_obj.options['ymax'] = e_ymax
  1057. try:
  1058. if self.ui.gaptype_radio.get_value() == 'mb':
  1059. ret = app_obj.app_obj.new_object('excellon', outname_exc, excellon_init)
  1060. if ret == 'fail':
  1061. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Mouse bites failed."))
  1062. ret = app_obj.app_obj.new_object('geometry', outname, geo_init)
  1063. if ret == 'fail':
  1064. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  1065. return
  1066. # cutout_obj.plot(plot_tool=1)
  1067. app_obj.inform.emit('[success] %s' % _("Rectangular CutOut operation finished."))
  1068. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1069. app_obj.should_we_save = True
  1070. except Exception as ee:
  1071. log.debug(str(ee))
  1072. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1073. def on_manual_gap_click(self):
  1074. name = self.ui.man_object_combo.currentText()
  1075. # Get source object.
  1076. try:
  1077. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  1078. except Exception as e:
  1079. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  1080. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  1081. return
  1082. if self.man_cutout_obj is None:
  1083. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1084. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  1085. return
  1086. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  1087. self.app.geo_editor.tool_shape.enabled = True
  1088. self.manual_solid_geo = deepcopy(self.flatten(self.man_cutout_obj.solid_geometry))
  1089. self.cutting_dia = self.ui.dia.get_value()
  1090. if 0 in {self.cutting_dia}:
  1091. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1092. _("Tool Diameter is zero value. Change it to a positive real number."))
  1093. return
  1094. if self.ui.gaptype_radio.get_value() == 'mb':
  1095. mb_dia = self.ui.mb_dia_entry.get_value()
  1096. b_dia = (self.cutting_dia / 2.0) - (mb_dia / 2.0)
  1097. self.mb_manual_solid_geo = self.flatten(unary_union(self.manual_solid_geo).buffer(b_dia).interiors)
  1098. self.cutting_gapsize = self.ui.gapsize.get_value()
  1099. name = self.ui.man_object_combo.currentText()
  1100. # Get Geometry source object to be used as target for Manual adding Gaps
  1101. try:
  1102. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  1103. except Exception as e:
  1104. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  1105. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  1106. return
  1107. if self.app.is_legacy is False:
  1108. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  1109. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1110. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1111. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1112. else:
  1113. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  1114. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1115. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1116. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1117. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1118. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1119. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  1120. self.mouse_events_connected = True
  1121. if self.ui.big_cursor_cb.get_value():
  1122. self.old_cursor_type = self.app.defaults["global_cursor_type"]
  1123. self.app.on_cursor_type(val="big")
  1124. self.app.defaults['global_selection_shape'] = False
  1125. def on_manual_cutout(self, click_pos):
  1126. if self.man_cutout_obj is None:
  1127. msg = '[ERROR_NOTCL] %s: %s' % (_("Geometry object for manual cutout not found"), self.man_cutout_obj)
  1128. self.app.inform.emit(msg)
  1129. return
  1130. # use the snapped position as reference
  1131. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  1132. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  1133. gap_type = self.ui.gaptype_radio.get_value()
  1134. gaps_solid_geo = None
  1135. if gap_type == 'bt' and self.ui.thin_depth_entry.get_value() != 0:
  1136. gaps_solid_geo = self.intersect_geo(self.manual_solid_geo, cut_poly)
  1137. if gap_type == 'mb':
  1138. rests_geo = self.intersect_geo(self.mb_manual_solid_geo, cut_poly)
  1139. if isinstance(rests_geo, list):
  1140. self.mb_manual_cuts += rests_geo
  1141. else:
  1142. self.mb_manual_cuts.append(rests_geo)
  1143. # first subtract geometry for the total solid_geometry
  1144. new_solid_geometry = CutOut.subtract_geo(self.man_cutout_obj.solid_geometry, cut_poly)
  1145. new_solid_geometry = linemerge(new_solid_geometry)
  1146. self.man_cutout_obj.solid_geometry = new_solid_geometry
  1147. # then do it on each tool in the manual cutout Geometry object
  1148. try:
  1149. self.man_cutout_obj.multigeo = True
  1150. self.man_cutout_obj.tools[1]['solid_geometry'] = new_solid_geometry
  1151. self.man_cutout_obj.tools[1]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  1152. self.man_cutout_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  1153. self.man_cutout_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1154. self.man_cutout_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1155. except KeyError:
  1156. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No tool in the Geometry object."))
  1157. return
  1158. dia = self.ui.dia.get_value()
  1159. if gaps_solid_geo:
  1160. if 9999 not in self.man_cutout_obj.tools:
  1161. self.man_cutout_obj.tools.update({
  1162. 9999: self.cut_tool_dict
  1163. })
  1164. self.man_cutout_obj.tools[9999]['tooldia'] = str(dia)
  1165. self.man_cutout_obj.tools[9999]['solid_geometry'] = [gaps_solid_geo]
  1166. self.man_cutout_obj.tools[9999]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  1167. self.man_cutout_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  1168. self.man_cutout_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1169. self.man_cutout_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1170. self.man_cutout_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  1171. else:
  1172. self.man_cutout_obj.tools[9999]['solid_geometry'].append(gaps_solid_geo)
  1173. self.man_cutout_obj.plot(plot_tool=1)
  1174. self.app.inform.emit('%s' % _("Added manual Bridge Gap. Left click to add another or right click to finish."))
  1175. self.app.should_we_save = True
  1176. def on_manual_geo(self):
  1177. name = self.ui.obj_combo.currentText()
  1178. # Get source object.
  1179. try:
  1180. cutout_obj = self.app.collection.get_by_name(str(name))
  1181. except Exception as e:
  1182. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  1183. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  1184. return "Could not retrieve object: %s" % name
  1185. if cutout_obj is None:
  1186. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1187. _("There is no Gerber object selected for Cutout.\n"
  1188. "Select one and try again."))
  1189. return
  1190. if cutout_obj.kind != 'gerber':
  1191. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1192. _("The selected object has to be of Gerber type.\n"
  1193. "Select a Gerber file and try again."))
  1194. return
  1195. dia = float(self.ui.dia.get_value())
  1196. if 0 in {dia}:
  1197. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1198. _("Tool Diameter is zero value. Change it to a positive real number."))
  1199. return
  1200. try:
  1201. kind = self.ui.obj_kind_combo.get_value()
  1202. except ValueError:
  1203. return
  1204. margin = float(self.ui.margin.get_value())
  1205. convex_box = self.ui.convex_box_cb.get_value()
  1206. def geo_init(geo_obj, app_obj):
  1207. geo_union = unary_union(cutout_obj.solid_geometry)
  1208. if convex_box:
  1209. geo = geo_union.convex_hull
  1210. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  1211. elif kind == 'single':
  1212. if isinstance(geo_union, Polygon) or \
  1213. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  1214. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  1215. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  1216. elif isinstance(geo_union, MultiPolygon):
  1217. x0, y0, x1, y1 = geo_union.bounds
  1218. geo = box(x0, y0, x1, y1)
  1219. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  1220. else:
  1221. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1222. _("Geometry not supported for cutout"), type(geo_union)))
  1223. return 'fail'
  1224. else:
  1225. geo = geo_union
  1226. geo = geo.buffer(margin + abs(dia / 2))
  1227. if isinstance(geo, Polygon):
  1228. geo_obj.solid_geometry = geo.exterior
  1229. elif isinstance(geo, MultiPolygon):
  1230. solid_geo = []
  1231. for poly in geo:
  1232. solid_geo.append(poly.exterior)
  1233. geo_obj.solid_geometry = deepcopy(solid_geo)
  1234. geo_obj.options['cnctooldia'] = str(dia)
  1235. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  1236. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  1237. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1238. geo_obj.multigeo = True
  1239. geo_obj.tools.update({
  1240. 1: self.cut_tool_dict
  1241. })
  1242. geo_obj.tools[1]['tooldia'] = str(dia)
  1243. geo_obj.tools[1]['solid_geometry'] = geo_obj.solid_geometry
  1244. geo_obj.tools[1]['data']['name'] = outname
  1245. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  1246. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1247. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1248. outname = cutout_obj.options["name"] + "_cutout"
  1249. self.app.app_obj.new_object('geometry', outname, geo_init)
  1250. def cutting_geo(self, pos):
  1251. self.cutting_dia = float(self.ui.dia.get_value())
  1252. self.cutting_gapsize = float(self.ui.gapsize.get_value())
  1253. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  1254. # cutting area definition
  1255. orig_x = pos[0]
  1256. orig_y = pos[1]
  1257. xmin = orig_x - offset
  1258. ymin = orig_y - offset
  1259. xmax = orig_x + offset
  1260. ymax = orig_y + offset
  1261. cut_poly = box(xmin, ymin, xmax, ymax)
  1262. return cut_poly
  1263. # To be called after clicking on the plot.
  1264. def on_mouse_click_release(self, event):
  1265. if self.app.is_legacy is False:
  1266. event_pos = event.pos
  1267. # event_is_dragging = event.is_dragging
  1268. right_button = 2
  1269. else:
  1270. event_pos = (event.xdata, event.ydata)
  1271. # event_is_dragging = self.app.plotcanvas.is_dragging
  1272. right_button = 3
  1273. try:
  1274. x = float(event_pos[0])
  1275. y = float(event_pos[1])
  1276. except TypeError:
  1277. return
  1278. event_pos = (x, y)
  1279. # do paint single only for left mouse clicks
  1280. if event.button == 1:
  1281. self.app.inform.emit(_("Making manual bridge gap..."))
  1282. pos = self.app.plotcanvas.translate_coords(event_pos)
  1283. self.on_manual_cutout(click_pos=pos)
  1284. # if RMB then we exit
  1285. elif event.button == right_button and self.mouse_is_dragging is False:
  1286. if self.app.is_legacy is False:
  1287. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1288. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1289. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1290. else:
  1291. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1292. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1293. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1294. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1295. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1296. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1297. self.app.on_mouse_click_release_over_plot)
  1298. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1299. # Remove any previous utility shape
  1300. self.app.geo_editor.tool_shape.clear(update=True)
  1301. self.app.geo_editor.tool_shape.enabled = False
  1302. # signal that the mouse events are disconnected from local methods
  1303. self.mouse_events_connected = False
  1304. if self.ui.big_cursor_cb.get_value():
  1305. # restore cursor
  1306. self.app.on_cursor_type(val=self.old_cursor_type)
  1307. # restore selection
  1308. self.app.defaults['global_selection_shape'] = self.old_selection_state
  1309. # rebuild the manual Geometry object
  1310. self.man_cutout_obj.build_ui()
  1311. # plot the final object
  1312. self.man_cutout_obj.plot()
  1313. # mouse bytes
  1314. if self.ui.gaptype_radio.get_value() == 'mb':
  1315. with self.app.proc_container.new("Generating Excellon ..."):
  1316. outname_exc = self.man_cutout_obj.options["name"] + "_mouse_bites"
  1317. self.app.collection.promise(outname_exc)
  1318. def job_thread(app_obj):
  1319. # list of Shapely Points to mark the drill points centers
  1320. holes = []
  1321. mb_dia = self.ui.mb_dia_entry.get_value()
  1322. mb_spacing = self.ui.mb_spacing_entry.get_value()
  1323. for line in self.mb_manual_cuts:
  1324. calc_len = 0
  1325. while calc_len < line.length:
  1326. holes.append(line.interpolate(calc_len))
  1327. calc_len += mb_dia + mb_spacing
  1328. self.mb_manual_cuts[:] = []
  1329. def excellon_init(exc_obj, app_o):
  1330. if not holes:
  1331. return 'fail'
  1332. tools = {}
  1333. tools[1] = {}
  1334. tools[1]["tooldia"] = mb_dia
  1335. tools[1]['drills'] = holes
  1336. tools[1]['solid_geometry'] = []
  1337. exc_obj.tools = tools
  1338. exc_obj.create_geometry()
  1339. exc_obj.source_file = app_o.f_handlers.export_excellon(obj_name=exc_obj.options['name'],
  1340. local_use=exc_obj,
  1341. filename=None,
  1342. use_thread=False)
  1343. # calculate the bounds
  1344. xmin, ymin, xmax, ymax = CutOut.recursive_bounds(exc_obj.solid_geometry)
  1345. exc_obj.options['xmin'] = xmin
  1346. exc_obj.options['ymin'] = ymin
  1347. exc_obj.options['xmax'] = xmax
  1348. exc_obj.options['ymax'] = ymax
  1349. ret = app_obj.app_obj.new_object('excellon', outname_exc, excellon_init)
  1350. if ret == 'fail':
  1351. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Mouse bites failed."))
  1352. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1353. self.app.inform.emit('[success] %s' % _("Finished manual adding of gaps."))
  1354. def on_mouse_move(self, event):
  1355. self.app.on_mouse_move_over_plot(event=event)
  1356. if self.app.is_legacy is False:
  1357. event_pos = event.pos
  1358. event_is_dragging = event.is_dragging
  1359. # right_button = 2
  1360. else:
  1361. event_pos = (event.xdata, event.ydata)
  1362. event_is_dragging = self.app.plotcanvas.is_dragging
  1363. # right_button = 3
  1364. try:
  1365. x = float(event_pos[0])
  1366. y = float(event_pos[1])
  1367. except TypeError:
  1368. return
  1369. event_pos = (x, y)
  1370. pos = self.canvas.translate_coords(event_pos)
  1371. event.xdata, event.ydata = pos[0], pos[1]
  1372. if event_is_dragging is True:
  1373. self.mouse_is_dragging = True
  1374. else:
  1375. self.mouse_is_dragging = False
  1376. try:
  1377. x = float(event.xdata)
  1378. y = float(event.ydata)
  1379. except TypeError:
  1380. return
  1381. if self.app.grid_status():
  1382. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  1383. else:
  1384. snap_x, snap_y = x, y
  1385. self.x_pos, self.y_pos = snap_x, snap_y
  1386. # #################################################
  1387. # ### This section makes the cutting geo to #######
  1388. # ### rotate if it intersects the target geo ######
  1389. # #################################################
  1390. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  1391. man_geo = self.man_cutout_obj.solid_geometry
  1392. def get_angle(geo):
  1393. line = cut_geo.intersection(geo)
  1394. try:
  1395. pt1_x = line.coords[0][0]
  1396. pt1_y = line.coords[0][1]
  1397. pt2_x = line.coords[1][0]
  1398. pt2_y = line.coords[1][1]
  1399. dx = pt1_x - pt2_x
  1400. dy = pt1_y - pt2_y
  1401. if dx == 0 or dy == 0:
  1402. angle = 0
  1403. else:
  1404. radian = math.atan(dx / dy)
  1405. angle = radian * 180 / math.pi
  1406. except Exception:
  1407. angle = 0
  1408. return angle
  1409. try:
  1410. rot_angle = 0
  1411. for geo_el in man_geo:
  1412. if isinstance(geo_el, Polygon):
  1413. work_geo = geo_el.exterior
  1414. if cut_geo.intersects(work_geo):
  1415. rot_angle = get_angle(geo=work_geo)
  1416. else:
  1417. rot_angle = 0
  1418. else:
  1419. rot_angle = 0
  1420. if cut_geo.intersects(geo_el):
  1421. rot_angle = get_angle(geo=geo_el)
  1422. if rot_angle != 0:
  1423. break
  1424. except TypeError:
  1425. if isinstance(man_geo, Polygon):
  1426. work_geo = man_geo.exterior
  1427. if cut_geo.intersects(work_geo):
  1428. rot_angle = get_angle(geo=work_geo)
  1429. else:
  1430. rot_angle = 0
  1431. else:
  1432. rot_angle = 0
  1433. if cut_geo.intersects(man_geo):
  1434. rot_angle = get_angle(geo=man_geo)
  1435. # rotate only if there is an angle to rotate to
  1436. if rot_angle != 0:
  1437. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  1438. # Remove any previous utility shape
  1439. self.app.geo_editor.tool_shape.clear(update=True)
  1440. self.draw_utility_geometry(geo=cut_geo)
  1441. def draw_utility_geometry(self, geo):
  1442. self.app.geo_editor.tool_shape.add(
  1443. shape=geo,
  1444. color=(self.app.defaults["global_draw_color"] + '80'),
  1445. update=False,
  1446. layer=0,
  1447. tolerance=None)
  1448. self.app.geo_editor.tool_shape.redraw()
  1449. def on_key_press(self, event):
  1450. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1451. if type(event) is int:
  1452. key = event
  1453. # events from the GUI are of type QKeyEvent
  1454. elif type(event) == QtGui.QKeyEvent:
  1455. key = event.key()
  1456. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1457. key = event.key
  1458. key = QtGui.QKeySequence(key)
  1459. # check for modifiers
  1460. key_string = key.toString().lower()
  1461. if '+' in key_string:
  1462. mod, __, key_text = key_string.rpartition('+')
  1463. if mod.lower() == 'ctrl':
  1464. # modifiers = QtCore.Qt.ControlModifier
  1465. pass
  1466. elif mod.lower() == 'alt':
  1467. # modifiers = QtCore.Qt.AltModifier
  1468. pass
  1469. elif mod.lower() == 'shift':
  1470. # modifiers = QtCore.Qt.ShiftModifier
  1471. pass
  1472. else:
  1473. # modifiers = QtCore.Qt.NoModifier
  1474. pass
  1475. key = QtGui.QKeySequence(key_text)
  1476. # events from Vispy are of type KeyEvent
  1477. else:
  1478. key = event.key
  1479. # Escape = Deselect All
  1480. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1481. if self.mouse_events_connected is True:
  1482. self.mouse_events_connected = False
  1483. if self.app.is_legacy is False:
  1484. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1485. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1486. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1487. else:
  1488. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1489. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1490. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1491. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1492. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1493. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1494. self.app.on_mouse_click_release_over_plot)
  1495. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1496. if self.ui.big_cursor_cb.get_value():
  1497. # restore cursor
  1498. self.app.on_cursor_type(val=self.old_cursor_type)
  1499. # restore selection
  1500. self.app.defaults['global_selection_shape'] = self.old_selection_state
  1501. # Remove any previous utility shape
  1502. self.app.geo_editor.tool_shape.clear(update=True)
  1503. self.app.geo_editor.tool_shape.enabled = False
  1504. # Grid toggle
  1505. if key == QtCore.Qt.Key_G or key == 'G':
  1506. self.app.ui.grid_snap_btn.trigger()
  1507. # Jump to coords
  1508. if key == QtCore.Qt.Key_J or key == 'J':
  1509. l_x, l_y = self.app.on_jump_to()
  1510. self.app.geo_editor.tool_shape.clear(update=True)
  1511. geo = self.cutting_geo(pos=(l_x, l_y))
  1512. self.draw_utility_geometry(geo=geo)
  1513. @staticmethod
  1514. def subtract_poly_from_geo(solid_geo, pts):
  1515. """
  1516. Subtract polygon made from points from the given object.
  1517. This only operates on the paths in the original geometry,
  1518. i.e. it converts polygons into paths.
  1519. :param solid_geo: Geometry from which to subtract.
  1520. :param pts: a tuple of coordinates in format (x0, y0, x1, y1)
  1521. :type pts: tuple
  1522. x0: x coord for lower left vertex of the polygon.
  1523. y0: y coord for lower left vertex of the polygon.
  1524. x1: x coord for upper right vertex of the polygon.
  1525. y1: y coord for upper right vertex of the polygon.
  1526. :return: none
  1527. """
  1528. x0 = pts[0]
  1529. y0 = pts[1]
  1530. x1 = pts[2]
  1531. y1 = pts[3]
  1532. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1533. # pathonly should be always True, otherwise polygons are not subtracted
  1534. flat_geometry = CutOut.flatten(geometry=solid_geo)
  1535. log.debug("%d paths" % len(flat_geometry))
  1536. polygon = Polygon(points)
  1537. toolgeo = unary_union(polygon)
  1538. diffs = []
  1539. for target in flat_geometry:
  1540. if type(target) == LineString or type(target) == LinearRing:
  1541. diffs.append(target.difference(toolgeo))
  1542. else:
  1543. log.warning("Not implemented.")
  1544. return unary_union(diffs)
  1545. @staticmethod
  1546. def flatten(geometry):
  1547. """
  1548. Creates a list of non-iterable linear geometry objects.
  1549. Polygons are expanded into its exterior and interiors.
  1550. Results are placed in self.flat_geometry
  1551. :param geometry: Shapely type or list or list of list of such.
  1552. """
  1553. flat_geo = []
  1554. try:
  1555. for geo in geometry:
  1556. if geo:
  1557. flat_geo += CutOut.flatten(geometry=geo)
  1558. except TypeError:
  1559. if isinstance(geometry, Polygon) and not geometry.is_empty:
  1560. flat_geo.append(geometry.exterior)
  1561. CutOut.flatten(geometry=geometry.interiors)
  1562. elif not geometry.is_empty:
  1563. flat_geo.append(geometry)
  1564. return flat_geo
  1565. @staticmethod
  1566. def recursive_bounds(geometry):
  1567. """
  1568. Return the bounds of the biggest bounding box in geometry, one that include all.
  1569. :param geometry: a iterable object that holds geometry
  1570. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1571. """
  1572. # now it can get bounds for nested lists of objects
  1573. def bounds_rec(obj):
  1574. try:
  1575. minx = Inf
  1576. miny = Inf
  1577. maxx = -Inf
  1578. maxy = -Inf
  1579. for k in obj:
  1580. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1581. minx = min(minx, minx_)
  1582. miny = min(miny, miny_)
  1583. maxx = max(maxx, maxx_)
  1584. maxy = max(maxy, maxy_)
  1585. return minx, miny, maxx, maxy
  1586. except TypeError:
  1587. # it's a Shapely object, return it's bounds
  1588. if obj:
  1589. return obj.bounds
  1590. return bounds_rec(geometry)
  1591. @staticmethod
  1592. def subtract_geo(target_geo, subtractor):
  1593. """
  1594. Subtract subtractor polygon from the target_geo. This only operates on the paths in the target_geo,
  1595. i.e. it converts polygons into paths.
  1596. :param target_geo: geometry from which to subtract
  1597. :param subtractor: a list of Points, a LinearRing or a Polygon that will be subtracted from target_geo
  1598. :return: a unary_union of the resulting geometry
  1599. """
  1600. if target_geo is None:
  1601. target_geo = []
  1602. # flatten() takes care of possible empty geometry making sure that is filtered
  1603. flat_geometry = CutOut.flatten(target_geo)
  1604. log.debug("%d paths" % len(flat_geometry))
  1605. toolgeo = unary_union(subtractor)
  1606. diffs = []
  1607. for target in flat_geometry:
  1608. if isinstance(target, LineString) or isinstance(target, LinearRing) or isinstance(target, MultiLineString):
  1609. diffs.append(target.difference(toolgeo))
  1610. else:
  1611. log.warning("Not implemented.")
  1612. return unary_union(diffs)
  1613. @staticmethod
  1614. def intersect_geo(target_geo, second_geo):
  1615. """
  1616. :param target_geo:
  1617. :type target_geo:
  1618. :param second_geo:
  1619. :type second_geo:
  1620. :return:
  1621. :rtype:
  1622. """
  1623. results = []
  1624. try:
  1625. __ = iter(target_geo)
  1626. except TypeError:
  1627. target_geo = [target_geo]
  1628. for geo in target_geo:
  1629. if second_geo.intersects(geo):
  1630. results.append(second_geo.intersection(geo))
  1631. return CutOut.flatten(results)
  1632. def reset_fields(self):
  1633. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1634. class CutoutUI:
  1635. toolName = _("Cutout PCB")
  1636. def __init__(self, layout, app):
  1637. self.app = app
  1638. self.decimals = self.app.decimals
  1639. self.layout = layout
  1640. # Title
  1641. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1642. title_label.setStyleSheet("""
  1643. QLabel
  1644. {
  1645. font-size: 16px;
  1646. font-weight: bold;
  1647. }
  1648. """)
  1649. self.layout.addWidget(title_label)
  1650. self.layout.addWidget(QtWidgets.QLabel(''))
  1651. # Form Layout
  1652. grid0 = QtWidgets.QGridLayout()
  1653. grid0.setColumnStretch(0, 0)
  1654. grid0.setColumnStretch(1, 1)
  1655. self.layout.addLayout(grid0)
  1656. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  1657. self.object_label.setToolTip('%s.' % _("Object to be cutout"))
  1658. grid0.addWidget(self.object_label, 0, 0, 1, 2)
  1659. # Object kind
  1660. self.kindlabel = QtWidgets.QLabel('%s:' % _('Kind'))
  1661. self.kindlabel.setToolTip(
  1662. _("Choice of what kind the object we want to cutout is.<BR>"
  1663. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  1664. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  1665. "out of many individual PCB outlines.")
  1666. )
  1667. self.obj_kind_combo = RadioSet([
  1668. {"label": _("Single"), "value": "single"},
  1669. {"label": _("Panel"), "value": "panel"},
  1670. ])
  1671. grid0.addWidget(self.kindlabel, 2, 0)
  1672. grid0.addWidget(self.obj_kind_combo, 2, 1)
  1673. # Type of object to be cutout
  1674. self.type_obj_radio = RadioSet([
  1675. {"label": _("Gerber"), "value": "grb"},
  1676. {"label": _("Geometry"), "value": "geo"},
  1677. ])
  1678. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Type"))
  1679. self.type_obj_combo_label.setToolTip(
  1680. _("Specify the type of object to be cutout.\n"
  1681. "It can be of type: Gerber or Geometry.\n"
  1682. "What is selected here will dictate the kind\n"
  1683. "of objects that will populate the 'Object' combobox.")
  1684. )
  1685. grid0.addWidget(self.type_obj_combo_label, 4, 0)
  1686. grid0.addWidget(self.type_obj_radio, 4, 1)
  1687. # Object to be cutout
  1688. self.obj_combo = FCComboBox()
  1689. self.obj_combo.setModel(self.app.collection)
  1690. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1691. self.obj_combo.is_last = True
  1692. grid0.addWidget(self.obj_combo, 6, 0, 1, 2)
  1693. # Convex Shape
  1694. # Surrounding convex box shape
  1695. self.convex_box_label = QtWidgets.QLabel('%s:' % _("Convex Shape"))
  1696. self.convex_box_label.setToolTip(
  1697. _("Create a convex shape surrounding the entire PCB.\n"
  1698. "Used only if the source object type is Gerber.")
  1699. )
  1700. self.convex_box_cb = FCCheckBox()
  1701. self.convex_box_cb.setToolTip(
  1702. _("Create a convex shape surrounding the entire PCB.\n"
  1703. "Used only if the source object type is Gerber.")
  1704. )
  1705. grid0.addWidget(self.convex_box_label, 8, 0)
  1706. grid0.addWidget(self.convex_box_cb, 8, 1)
  1707. separator_line = QtWidgets.QFrame()
  1708. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1709. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1710. grid0.addWidget(separator_line, 10, 0, 1, 2)
  1711. self.tool_sel_label = FCLabel('<b>%s</b>' % _('Cutout Tool'))
  1712. grid0.addWidget(self.tool_sel_label, 12, 0, 1, 2)
  1713. # Tool Diameter
  1714. self.dia = FCDoubleSpinner(callback=self.confirmation_message)
  1715. self.dia.set_precision(self.decimals)
  1716. self.dia.set_range(0.0000, 9999.9999)
  1717. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool Dia"))
  1718. self.dia_label.setToolTip(
  1719. _("Diameter of the tool used to cutout\n"
  1720. "the PCB shape out of the surrounding material.")
  1721. )
  1722. grid0.addWidget(self.dia_label, 14, 0)
  1723. grid0.addWidget(self.dia, 14, 1)
  1724. hlay = QtWidgets.QHBoxLayout()
  1725. # Search and Add new Tool
  1726. self.add_newtool_button = FCButton(_('Search and Add'))
  1727. self.add_newtool_button.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
  1728. self.add_newtool_button.setToolTip(
  1729. _("Add a new tool to the Tool Table\n"
  1730. "with the diameter specified above.\n"
  1731. "This is done by a background search\n"
  1732. "in the Tools Database. If nothing is found\n"
  1733. "in the Tools DB then a default tool is added.")
  1734. )
  1735. hlay.addWidget(self.add_newtool_button)
  1736. # Pick from DB new Tool
  1737. self.addtool_from_db_btn = FCButton(_('Pick from DB'))
  1738. self.addtool_from_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/search_db32.png'))
  1739. self.addtool_from_db_btn.setToolTip(
  1740. _("Add a new tool to the Tool Table\n"
  1741. "from the Tools Database.\n"
  1742. "Tools database administration in in:\n"
  1743. "Menu: Options -> Tools Database")
  1744. )
  1745. hlay.addWidget(self.addtool_from_db_btn)
  1746. grid0.addLayout(hlay, 16, 0, 1, 2)
  1747. separator_line = QtWidgets.QFrame()
  1748. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1749. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1750. grid0.addWidget(separator_line, 18, 0, 1, 2)
  1751. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _("Tool Parameters"))
  1752. grid0.addWidget(self.param_label, 20, 0, 1, 2)
  1753. # Cut Z
  1754. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1755. cutzlabel.setToolTip(
  1756. _(
  1757. "Cutting depth (negative)\n"
  1758. "below the copper surface."
  1759. )
  1760. )
  1761. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1762. self.cutz_entry.set_precision(self.decimals)
  1763. if machinist_setting == 0:
  1764. self.cutz_entry.setRange(-9999.9999, -0.00001)
  1765. else:
  1766. self.cutz_entry.setRange(-9999.9999, 9999.9999)
  1767. self.cutz_entry.setSingleStep(0.1)
  1768. grid0.addWidget(cutzlabel, 22, 0)
  1769. grid0.addWidget(self.cutz_entry, 22, 1)
  1770. # Multi-pass
  1771. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  1772. self.mpass_cb.setToolTip(
  1773. _(
  1774. "Use multiple passes to limit\n"
  1775. "the cut depth in each pass. Will\n"
  1776. "cut multiple times until Cut Z is\n"
  1777. "reached."
  1778. )
  1779. )
  1780. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1781. self.maxdepth_entry.set_precision(self.decimals)
  1782. self.maxdepth_entry.setRange(0, 9999.9999)
  1783. self.maxdepth_entry.setSingleStep(0.1)
  1784. self.maxdepth_entry.setToolTip(
  1785. _(
  1786. "Depth of each pass (positive)."
  1787. )
  1788. )
  1789. grid0.addWidget(self.mpass_cb, 24, 0)
  1790. grid0.addWidget(self.maxdepth_entry, 24, 1)
  1791. self.ois_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  1792. # Margin
  1793. self.margin = FCDoubleSpinner(callback=self.confirmation_message)
  1794. self.margin.set_range(-9999.9999, 9999.9999)
  1795. self.margin.setSingleStep(0.1)
  1796. self.margin.set_precision(self.decimals)
  1797. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  1798. self.margin_label.setToolTip(
  1799. _("Margin over bounds. A positive value here\n"
  1800. "will make the cutout of the PCB further from\n"
  1801. "the actual PCB border")
  1802. )
  1803. grid0.addWidget(self.margin_label, 26, 0)
  1804. grid0.addWidget(self.margin, 26, 1)
  1805. # Gapsize
  1806. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size"))
  1807. self.gapsize_label.setToolTip(
  1808. _("The size of the bridge gaps in the cutout\n"
  1809. "used to keep the board connected to\n"
  1810. "the surrounding material (the one \n"
  1811. "from which the PCB is cutout).")
  1812. )
  1813. self.gapsize = FCDoubleSpinner(callback=self.confirmation_message)
  1814. self.gapsize.set_precision(self.decimals)
  1815. grid0.addWidget(self.gapsize_label, 28, 0)
  1816. grid0.addWidget(self.gapsize, 28, 1)
  1817. # Gap Type
  1818. self.gaptype_label = FCLabel('%s:' % _("Gap type"))
  1819. self.gaptype_label.setToolTip(
  1820. _("The type of gap:\n"
  1821. "- Bridge -> the cutout will be interrupted by bridges\n"
  1822. "- Thin -> same as 'bridge' but it will be thinner by partially milling the gap\n"
  1823. "- M-Bites -> 'Mouse Bites' - same as 'bridge' but covered with drill holes")
  1824. )
  1825. self.gaptype_radio = RadioSet(
  1826. [
  1827. {'label': _('Bridge'), 'value': 'b'},
  1828. {'label': _('Thin'), 'value': 'bt'},
  1829. {'label': "M-Bites", 'value': 'mb'}
  1830. ],
  1831. stretch=True
  1832. )
  1833. grid0.addWidget(self.gaptype_label, 30, 0)
  1834. grid0.addWidget(self.gaptype_radio, 30, 1)
  1835. # Thin gaps Depth
  1836. self.thin_depth_label = FCLabel('%s:' % _("Depth"))
  1837. self.thin_depth_label.setToolTip(
  1838. _("The depth until the milling is done\n"
  1839. "in order to thin the gaps.")
  1840. )
  1841. self.thin_depth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1842. self.thin_depth_entry.set_precision(self.decimals)
  1843. if machinist_setting == 0:
  1844. self.thin_depth_entry.setRange(-9999.9999, -0.00001)
  1845. else:
  1846. self.thin_depth_entry.setRange(-9999.9999, 9999.9999)
  1847. self.thin_depth_entry.setSingleStep(0.1)
  1848. grid0.addWidget(self.thin_depth_label, 32, 0)
  1849. grid0.addWidget(self.thin_depth_entry, 32, 1)
  1850. # Mouse Bites Tool Diameter
  1851. self.mb_dia_label = FCLabel('%s:' % _("Tool Diameter"))
  1852. self.mb_dia_label.setToolTip(
  1853. _("The drill hole diameter when doing mouse bites.")
  1854. )
  1855. self.mb_dia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1856. self.mb_dia_entry.set_precision(self.decimals)
  1857. self.mb_dia_entry.setRange(0, 100.0000)
  1858. grid0.addWidget(self.mb_dia_label, 34, 0)
  1859. grid0.addWidget(self.mb_dia_entry, 34, 1)
  1860. # Mouse Bites Holes Spacing
  1861. self.mb_spacing_label = FCLabel('%s:' % _("Spacing"))
  1862. self.mb_spacing_label.setToolTip(
  1863. _("The spacing between drill holes when doing mouse bites.")
  1864. )
  1865. self.mb_spacing_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1866. self.mb_spacing_entry.set_precision(self.decimals)
  1867. self.mb_spacing_entry.setRange(0, 100.0000)
  1868. grid0.addWidget(self.mb_spacing_label, 36, 0)
  1869. grid0.addWidget(self.mb_spacing_entry, 36, 1)
  1870. separator_line = QtWidgets.QFrame()
  1871. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1872. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1873. grid0.addWidget(separator_line, 38, 0, 1, 2)
  1874. # Title2
  1875. title_param_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Automatic'), _("Bridge Gaps")))
  1876. title_param_label.setToolTip(
  1877. _("This section handle creation of automatic bridge gaps.")
  1878. )
  1879. grid0.addWidget(title_param_label, 40, 0, 1, 2)
  1880. # Gaps
  1881. # How gaps wil be rendered:
  1882. # lr - left + right
  1883. # tb - top + bottom
  1884. # 4 - left + right +top + bottom
  1885. # 2lr - 2*left + 2*right
  1886. # 2tb - 2*top + 2*bottom
  1887. # 8 - 2*left + 2*right +2*top + 2*bottom
  1888. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  1889. gaps_label.setToolTip(
  1890. _("Number of gaps used for the Automatic cutout.\n"
  1891. "There can be maximum 8 bridges/gaps.\n"
  1892. "The choices are:\n"
  1893. "- None - no gaps\n"
  1894. "- lr - left + right\n"
  1895. "- tb - top + bottom\n"
  1896. "- 4 - left + right +top + bottom\n"
  1897. "- 2lr - 2*left + 2*right\n"
  1898. "- 2tb - 2*top + 2*bottom\n"
  1899. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  1900. )
  1901. # gaps_label.setMinimumWidth(60)
  1902. self.gaps = FCComboBox()
  1903. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  1904. for it in gaps_items:
  1905. self.gaps.addItem(it)
  1906. # self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  1907. grid0.addWidget(gaps_label, 42, 0)
  1908. grid0.addWidget(self.gaps, 42, 1)
  1909. # Buttons
  1910. self.ff_cutout_object_btn = FCButton(_("Generate Geometry"))
  1911. self.ff_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/irregular32.png'))
  1912. self.ff_cutout_object_btn.setToolTip(
  1913. _("Cutout the selected object.\n"
  1914. "The cutout shape can be of any shape.\n"
  1915. "Useful when the PCB has a non-rectangular shape.")
  1916. )
  1917. self.ff_cutout_object_btn.setStyleSheet("""
  1918. QPushButton
  1919. {
  1920. font-weight: bold;
  1921. }
  1922. """)
  1923. grid0.addWidget(self.ff_cutout_object_btn, 44, 0, 1, 2)
  1924. self.rect_cutout_object_btn = FCButton(_("Generate Geometry"))
  1925. self.rect_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1926. self.rect_cutout_object_btn.setToolTip(
  1927. _("Cutout the selected object.\n"
  1928. "The resulting cutout shape is\n"
  1929. "always a rectangle shape and it will be\n"
  1930. "the bounding box of the Object.")
  1931. )
  1932. self.rect_cutout_object_btn.setStyleSheet("""
  1933. QPushButton
  1934. {
  1935. font-weight: bold;
  1936. }
  1937. """)
  1938. grid0.addWidget(self.rect_cutout_object_btn, 46, 0, 1, 2)
  1939. separator_line = QtWidgets.QFrame()
  1940. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1941. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1942. grid0.addWidget(separator_line, 48, 0, 1, 2)
  1943. # MANUAL BRIDGE GAPS
  1944. title_manual_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Manual'), _("Bridge Gaps")))
  1945. title_manual_label.setToolTip(
  1946. _("This section handle creation of manual bridge gaps.\n"
  1947. "This is done by mouse clicking on the perimeter of the\n"
  1948. "Geometry object that is used as a cutout object. ")
  1949. )
  1950. grid0.addWidget(title_manual_label, 50, 0, 1, 2)
  1951. # Big Cursor
  1952. big_cursor_label = QtWidgets.QLabel('%s:' % _("Big cursor"))
  1953. big_cursor_label.setToolTip(
  1954. _("Use a big cursor when adding manual gaps."))
  1955. self.big_cursor_cb = FCCheckBox()
  1956. grid0.addWidget(big_cursor_label, 52, 0)
  1957. grid0.addWidget(self.big_cursor_cb, 52, 1)
  1958. # Generate a surrounding Geometry object
  1959. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  1960. self.man_geo_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1961. self.man_geo_creation_btn.setToolTip(
  1962. _("If the object to be cutout is a Gerber\n"
  1963. "first create a Geometry that surrounds it,\n"
  1964. "to be used as the cutout, if one doesn't exist yet.\n"
  1965. "Select the source Gerber file in the top object combobox.")
  1966. )
  1967. # self.man_geo_creation_btn.setStyleSheet("""
  1968. # QPushButton
  1969. # {
  1970. # font-weight: bold;
  1971. # }
  1972. # """)
  1973. grid0.addWidget(self.man_geo_creation_btn, 54, 0, 1, 2)
  1974. # Manual Geo Object
  1975. self.man_object_combo = FCComboBox()
  1976. self.man_object_combo.setModel(self.app.collection)
  1977. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1978. self.man_object_combo.is_last = True
  1979. self.man_object_combo.obj_type = "Geometry"
  1980. self.man_object_label = QtWidgets.QLabel('%s:' % _("Manual cutout Geometry"))
  1981. self.man_object_label.setToolTip(
  1982. _("Geometry object used to create the manual cutout.")
  1983. )
  1984. # self.man_object_label.setMinimumWidth(60)
  1985. grid0.addWidget(self.man_object_label, 56, 0, 1, 2)
  1986. grid0.addWidget(self.man_object_combo, 56, 0, 1, 2)
  1987. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  1988. self.man_gaps_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/gaps32.png'))
  1989. self.man_gaps_creation_btn.setToolTip(
  1990. _("Use the left mouse button (LMB) click\n"
  1991. "to create a bridge gap to separate the PCB from\n"
  1992. "the surrounding material.\n"
  1993. "The LMB click has to be done on the perimeter of\n"
  1994. "the Geometry object used as a cutout geometry.")
  1995. )
  1996. self.man_gaps_creation_btn.setStyleSheet("""
  1997. QPushButton
  1998. {
  1999. font-weight: bold;
  2000. }
  2001. """)
  2002. grid0.addWidget(self.man_gaps_creation_btn, 58, 0, 1, 2)
  2003. self.layout.addStretch()
  2004. # ## Reset Tool
  2005. self.reset_button = FCButton(_("Reset Tool"))
  2006. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  2007. self.reset_button.setToolTip(
  2008. _("Will reset the tool parameters.")
  2009. )
  2010. self.reset_button.setStyleSheet("""
  2011. QPushButton
  2012. {
  2013. font-weight: bold;
  2014. }
  2015. """)
  2016. self.layout.addWidget(self.reset_button)
  2017. self.gaptype_radio.activated_custom.connect(self.on_gap_type_radio)
  2018. # ############################ FINSIHED GUI ###################################
  2019. # #############################################################################
  2020. def on_gap_type_radio(self, val):
  2021. if val == 'b':
  2022. self.thin_depth_label.hide()
  2023. self.thin_depth_entry.hide()
  2024. self.mb_dia_label.hide()
  2025. self.mb_dia_entry.hide()
  2026. self.mb_spacing_label.hide()
  2027. self.mb_spacing_entry.hide()
  2028. elif val == 'bt':
  2029. self.thin_depth_label.show()
  2030. self.thin_depth_entry.show()
  2031. self.mb_dia_label.hide()
  2032. self.mb_dia_entry.hide()
  2033. self.mb_spacing_label.hide()
  2034. self.mb_spacing_entry.hide()
  2035. elif val == 'mb':
  2036. self.thin_depth_label.hide()
  2037. self.thin_depth_entry.hide()
  2038. self.mb_dia_label.show()
  2039. self.mb_dia_entry.show()
  2040. self.mb_spacing_label.show()
  2041. self.mb_spacing_entry.show()
  2042. def confirmation_message(self, accepted, minval, maxval):
  2043. if accepted is False:
  2044. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2045. self.decimals,
  2046. minval,
  2047. self.decimals,
  2048. maxval), False)
  2049. else:
  2050. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2051. def confirmation_message_int(self, accepted, minval, maxval):
  2052. if accepted is False:
  2053. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2054. (_("Edited value is out of range"), minval, maxval), False)
  2055. else:
  2056. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)