ToolCutOut.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467
  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 if dia else str(self.app.defaults["tools_cutout_tooldia"])
  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': dia,
  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.\n"
  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. 1: {
  734. "tooldia": mb_dia,
  735. "drills": holes,
  736. "solid_geometry": []
  737. }
  738. }
  739. exc_obj.tools = tools
  740. exc_obj.create_geometry()
  741. exc_obj.source_file = app_o.f_handlers.export_excellon(obj_name=exc_obj.options['name'],
  742. local_use=exc_obj, filename=None,
  743. use_thread=False)
  744. # calculate the bounds
  745. xmin, ymin, xmax, ymax = CutOut.recursive_bounds(exc_obj.solid_geometry)
  746. exc_obj.options['xmin'] = xmin
  747. exc_obj.options['ymin'] = ymin
  748. exc_obj.options['xmax'] = xmax
  749. exc_obj.options['ymax'] = ymax
  750. try:
  751. if self.ui.gaptype_radio.get_value() == 'mb':
  752. ret = app_obj.app_obj.new_object('excellon', outname_exc, excellon_init)
  753. if ret == 'fail':
  754. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Mouse bites failed."))
  755. ret = app_obj.app_obj.new_object('geometry', outname, geo_init)
  756. if ret == 'fail':
  757. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  758. return
  759. # cutout_obj.plot(plot_tool=1)
  760. app_obj.inform.emit('[success] %s' % _("Any-form Cutout operation finished."))
  761. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  762. app_obj.should_we_save = True
  763. except Exception as ee:
  764. log.debug(str(ee))
  765. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  766. def on_rectangular_cutout(self):
  767. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  768. name = self.ui.obj_combo.currentText()
  769. # Get source object.
  770. try:
  771. cutout_obj = self.app.collection.get_by_name(str(name))
  772. except Exception as e:
  773. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  774. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  775. return "Could not retrieve object: %s" % name
  776. if cutout_obj is None:
  777. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  778. dia = float(self.ui.dia.get_value())
  779. if 0 in {dia}:
  780. self.app.inform.emit('[ERROR_NOTCL] %s' %
  781. _("Tool Diameter is zero value. Change it to a positive real number."))
  782. return "Tool Diameter is zero value. Change it to a positive real number."
  783. try:
  784. kind = self.ui.obj_kind_combo.get_value()
  785. except ValueError:
  786. return
  787. margin = self.ui.margin.get_value()
  788. try:
  789. gaps = self.ui.gaps.get_value()
  790. except TypeError:
  791. self.app.inform.emit('[WARNING_NOTCL] %s' %
  792. _("Number of gaps value is missing. Add it and retry."))
  793. return
  794. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  795. msg = '[WARNING_NOTCL] %s' % _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8.\n"
  796. "Fill in a correct value and retry.")
  797. self.app.inform.emit(msg)
  798. return
  799. # if cutout_obj.multigeo is True:
  800. # self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  801. # "Optionally, this Multi-geo Geometry can be converted to "
  802. # "Single-geo Geometry,\n"
  803. # "and after that perform Cutout."))
  804. # return
  805. def cutout_rect_handler(geom, gapsize, xmin, ymin, xmax, ymax):
  806. proc_geometry = []
  807. px = 0.5 * (xmin + xmax) + margin
  808. py = 0.5 * (ymin + ymax) + margin
  809. lenx = (xmax - xmin) + (margin * 2)
  810. leny = (ymax - ymin) + (margin * 2)
  811. if gaps == 'None':
  812. pass
  813. else:
  814. if gaps == '8' or gaps == '2LR':
  815. points = (
  816. xmin - gapsize, # botleft_x
  817. py - gapsize + leny / 4, # botleft_y
  818. xmax + gapsize, # topright_x
  819. py + gapsize + leny / 4 # topright_y
  820. )
  821. geom = self.subtract_poly_from_geo(geom, points)
  822. points = (
  823. xmin - gapsize,
  824. py - gapsize - leny / 4,
  825. xmax + gapsize,
  826. py + gapsize - leny / 4
  827. )
  828. geom = self.subtract_poly_from_geo(geom, points)
  829. if gaps == '8' or gaps == '2TB':
  830. points = (
  831. px - gapsize + lenx / 4,
  832. ymin - gapsize,
  833. px + gapsize + lenx / 4,
  834. ymax + gapsize
  835. )
  836. geom = self.subtract_poly_from_geo(geom, points)
  837. points = (
  838. px - gapsize - lenx / 4,
  839. ymin - gapsize,
  840. px + gapsize - lenx / 4,
  841. ymax + gapsize
  842. )
  843. geom = self.subtract_poly_from_geo(geom, points)
  844. if gaps == '4' or gaps == 'LR':
  845. points = (
  846. xmin - gapsize,
  847. py - gapsize,
  848. xmax + gapsize,
  849. py + gapsize
  850. )
  851. geom = self.subtract_poly_from_geo(geom, points)
  852. if gaps == '4' or gaps == 'TB':
  853. points = (
  854. px - gapsize,
  855. ymin - gapsize,
  856. px + gapsize,
  857. ymax + gapsize
  858. )
  859. geom = self.subtract_poly_from_geo(geom, points)
  860. try:
  861. for g in geom:
  862. proc_geometry.append(g)
  863. except TypeError:
  864. proc_geometry.append(geom)
  865. return proc_geometry
  866. with self.app.proc_container.new("Generating Cutout ..."):
  867. outname = cutout_obj.options["name"] + "_cutout"
  868. self.app.collection.promise(outname)
  869. has_mouse_bites = True if self.ui.gaptype_radio.get_value() == 'mb' else False
  870. outname_exc = cutout_obj.options["name"] + "_mouse_bites"
  871. if has_mouse_bites is True:
  872. self.app.collection.promise(outname_exc)
  873. def job_thread(app_obj):
  874. solid_geo = []
  875. gaps_solid_geo = []
  876. mouse_bites_geo = []
  877. gapsize = self.ui.gapsize.get_value()
  878. gapsize = gapsize / 2 + (dia / 2)
  879. mb_dia = self.ui.mb_dia_entry.get_value()
  880. mb_buff_val = mb_dia / 2.0
  881. mb_spacing = self.ui.mb_spacing_entry.get_value()
  882. gap_type = self.ui.gaptype_radio.get_value()
  883. thin_entry = self.ui.thin_depth_entry.get_value()
  884. if cutout_obj.multigeo is False:
  885. object_geo = cutout_obj.solid_geometry
  886. else:
  887. # first tool in the tools dict
  888. t_first = list(cutout_obj.tools.keys())[0]
  889. object_geo = cutout_obj.tools[t_first]['solid_geometry']
  890. if kind == 'single':
  891. # fuse the lines
  892. object_geo = unary_union(object_geo)
  893. xmin, ymin, xmax, ymax = object_geo.bounds
  894. geo = box(xmin, ymin, xmax, ymax)
  895. # if Gerber create a buffer at a distance
  896. # if Geometry then cut through the geometry
  897. if cutout_obj.kind == 'gerber':
  898. if margin >= 0:
  899. geo = geo.buffer(margin + abs(dia / 2))
  900. else:
  901. geo = geo.buffer(margin - abs(dia / 2))
  902. solid_geo = cutout_rect_handler(geo, gapsize, xmin, ymin, xmax, ymax)
  903. if gap_type == 'bt' and thin_entry != 0:
  904. gaps_solid_geo = self.subtract_geo(geo, deepcopy(solid_geo))
  905. else:
  906. if cutout_obj.kind == 'geometry':
  907. try:
  908. __ = iter(object_geo)
  909. except TypeError:
  910. object_geo = [object_geo]
  911. for geom_struct in object_geo:
  912. geom_struct = unary_union(geom_struct)
  913. xmin, ymin, xmax, ymax = geom_struct.bounds
  914. geom_struct = box(xmin, ymin, xmax, ymax)
  915. c_geo = cutout_rect_handler(geom_struct, gapsize, xmin, ymin, xmax, ymax)
  916. solid_geo += c_geo
  917. if gap_type == 'bt' and thin_entry != 0:
  918. try:
  919. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  920. except TypeError:
  921. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  922. elif cutout_obj.kind == 'gerber' and margin >= 0:
  923. try:
  924. __ = iter(object_geo)
  925. except TypeError:
  926. object_geo = [object_geo]
  927. for geom_struct in object_geo:
  928. geom_struct = unary_union(geom_struct)
  929. xmin, ymin, xmax, ymax = geom_struct.bounds
  930. geom_struct = box(xmin, ymin, xmax, ymax)
  931. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  932. c_geo = cutout_rect_handler(geom_struct, gapsize, xmin, ymin, xmax, ymax)
  933. solid_geo += c_geo
  934. if gap_type == 'bt' and thin_entry != 0:
  935. try:
  936. gaps_solid_geo += self.subtract_geo(geom_struct, c_geo)
  937. except TypeError:
  938. gaps_solid_geo.append(self.subtract_geo(geom_struct, c_geo))
  939. elif cutout_obj.kind == 'gerber' and margin < 0:
  940. app_obj.inform.emit(
  941. '[WARNING_NOTCL] %s' % _("Rectangular cutout with negative margin is not possible."))
  942. return "fail"
  943. if not solid_geo:
  944. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  945. return "fail"
  946. solid_geo = linemerge(solid_geo)
  947. if has_mouse_bites is True:
  948. gapsize -= dia / 2
  949. mb_object_geo = deepcopy(object_geo)
  950. if kind == 'single':
  951. # fuse the lines
  952. mb_object_geo = unary_union(mb_object_geo)
  953. xmin, ymin, xmax, ymax = mb_object_geo.bounds
  954. mb_geo = box(xmin, ymin, xmax, ymax)
  955. # if Gerber create a buffer at a distance
  956. # if Geometry then cut through the geometry
  957. if cutout_obj.kind == 'gerber':
  958. if margin >= 0:
  959. mb_geo = mb_geo.buffer(margin + mb_buff_val)
  960. else:
  961. mb_geo = mb_geo.buffer(margin - mb_buff_val)
  962. else:
  963. mb_geo = mb_geo.buffer(0)
  964. mb_solid_geo = cutout_rect_handler(mb_geo, gapsize, xmin, ymin, xmax, ymax)
  965. mouse_bites_geo = self.subtract_geo(mb_geo, mb_solid_geo)
  966. else:
  967. if cutout_obj.kind == 'geometry':
  968. try:
  969. __ = iter(mb_object_geo)
  970. except TypeError:
  971. mb_object_geo = [mb_object_geo]
  972. for mb_geom_struct in mb_object_geo:
  973. mb_geom_struct = unary_union(mb_geom_struct)
  974. xmin, ymin, xmax, ymax = mb_geom_struct.bounds
  975. mb_geom_struct = box(xmin, ymin, xmax, ymax)
  976. c_geo = cutout_rect_handler(mb_geom_struct, gapsize, xmin, ymin, xmax, ymax)
  977. solid_geo += c_geo
  978. try:
  979. mouse_bites_geo += self.subtract_geo(mb_geom_struct, c_geo)
  980. except TypeError:
  981. mouse_bites_geo.append(self.subtract_geo(mb_geom_struct, c_geo))
  982. elif cutout_obj.kind == 'gerber' and margin >= 0:
  983. try:
  984. __ = iter(mb_object_geo)
  985. except TypeError:
  986. mb_object_geo = [mb_object_geo]
  987. for mb_geom_struct in mb_object_geo:
  988. mb_geom_struct = unary_union(mb_geom_struct)
  989. xmin, ymin, xmax, ymax = mb_geom_struct.bounds
  990. mb_geom_struct = box(xmin, ymin, xmax, ymax)
  991. mb_geom_struct = mb_geom_struct.buffer(margin + mb_buff_val)
  992. c_geo = cutout_rect_handler(mb_geom_struct, gapsize, xmin, ymin, xmax, ymax)
  993. solid_geo += c_geo
  994. try:
  995. mouse_bites_geo += self.subtract_geo(mb_geom_struct, c_geo)
  996. except TypeError:
  997. mouse_bites_geo.append(self.subtract_geo(mb_geom_struct, c_geo))
  998. elif cutout_obj.kind == 'gerber' and margin < 0:
  999. msg = '[WARNING_NOTCL] %s' % \
  1000. _("Rectangular cutout with negative margin is not possible.")
  1001. app_obj.inform.emit(msg)
  1002. return "fail"
  1003. # list of Shapely Points to mark the drill points centers
  1004. holes = []
  1005. for line in mouse_bites_geo:
  1006. calc_len = 0
  1007. while calc_len < line.length:
  1008. holes.append(line.interpolate(calc_len))
  1009. calc_len += mb_dia + mb_spacing
  1010. def geo_init(geo_obj, application_obj):
  1011. geo_obj.multigeo = True
  1012. geo_obj.solid_geometry = deepcopy(solid_geo)
  1013. geo_obj.options['xmin'] = xmin
  1014. geo_obj.options['ymin'] = ymin
  1015. geo_obj.options['xmax'] = xmax
  1016. geo_obj.options['ymax'] = ymax
  1017. geo_obj.options['cnctooldia'] = str(dia)
  1018. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  1019. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  1020. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1021. geo_obj.tools[1] = deepcopy(self.cut_tool_dict)
  1022. geo_obj.tools[1]['tooldia'] = str(dia)
  1023. geo_obj.tools[1]['solid_geometry'] = geo_obj.solid_geometry
  1024. geo_obj.tools[1]['data']['name'] = outname
  1025. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  1026. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1027. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1028. if not gaps_solid_geo:
  1029. pass
  1030. else:
  1031. geo_obj.tools[9999] = deepcopy(self.cut_tool_dict)
  1032. geo_obj.tools[9999]['tooldia'] = str(dia)
  1033. geo_obj.tools[9999]['solid_geometry'] = gaps_solid_geo
  1034. geo_obj.tools[9999]['data']['name'] = outname
  1035. geo_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  1036. geo_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1037. geo_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1038. geo_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  1039. def excellon_init(exc_obj, app_o):
  1040. if not holes:
  1041. return 'fail'
  1042. tools = {
  1043. 1: {
  1044. "tooldia": mb_dia,
  1045. "drills": holes,
  1046. "solid_geometry": []
  1047. }
  1048. }
  1049. exc_obj.tools = tools
  1050. exc_obj.create_geometry()
  1051. exc_obj.source_file = app_o.f_handlers.export_excellon(obj_name=exc_obj.options['name'],
  1052. local_use=exc_obj,
  1053. filename=None,
  1054. use_thread=False)
  1055. # calculate the bounds
  1056. e_xmin, e_ymin, e_xmax, e_ymax = CutOut.recursive_bounds(exc_obj.solid_geometry)
  1057. exc_obj.options['xmin'] = e_xmin
  1058. exc_obj.options['ymin'] = e_ymin
  1059. exc_obj.options['xmax'] = e_xmax
  1060. exc_obj.options['ymax'] = e_ymax
  1061. try:
  1062. if self.ui.gaptype_radio.get_value() == 'mb':
  1063. ret = app_obj.app_obj.new_object('excellon', outname_exc, excellon_init)
  1064. if ret == 'fail':
  1065. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Mouse bites failed."))
  1066. ret = app_obj.app_obj.new_object('geometry', outname, geo_init)
  1067. if ret == 'fail':
  1068. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Failed."))
  1069. return
  1070. # cutout_obj.plot(plot_tool=1)
  1071. app_obj.inform.emit('[success] %s' % _("Rectangular CutOut operation finished."))
  1072. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1073. app_obj.should_we_save = True
  1074. except Exception as ee:
  1075. log.debug(str(ee))
  1076. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1077. def on_manual_gap_click(self):
  1078. name = self.ui.man_object_combo.currentText()
  1079. # Get source object.
  1080. try:
  1081. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  1082. except Exception as e:
  1083. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  1084. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  1085. return
  1086. if self.man_cutout_obj is None:
  1087. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1088. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  1089. return
  1090. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  1091. self.app.geo_editor.tool_shape.enabled = True
  1092. self.manual_solid_geo = deepcopy(self.flatten(self.man_cutout_obj.solid_geometry))
  1093. self.cutting_dia = self.ui.dia.get_value()
  1094. if 0 in {self.cutting_dia}:
  1095. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1096. _("Tool Diameter is zero value. Change it to a positive real number."))
  1097. return
  1098. if self.ui.gaptype_radio.get_value() == 'mb':
  1099. mb_dia = self.ui.mb_dia_entry.get_value()
  1100. b_dia = (self.cutting_dia / 2.0) - (mb_dia / 2.0)
  1101. self.mb_manual_solid_geo = self.flatten(unary_union(self.manual_solid_geo).buffer(b_dia).interiors)
  1102. self.cutting_gapsize = self.ui.gapsize.get_value()
  1103. name = self.ui.man_object_combo.currentText()
  1104. # Get Geometry source object to be used as target for Manual adding Gaps
  1105. try:
  1106. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  1107. except Exception as e:
  1108. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  1109. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  1110. return
  1111. if self.app.is_legacy is False:
  1112. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  1113. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1114. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1115. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1116. else:
  1117. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  1118. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1119. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1120. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1121. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1122. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1123. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  1124. self.mouse_events_connected = True
  1125. if self.ui.big_cursor_cb.get_value():
  1126. self.old_cursor_type = self.app.defaults["global_cursor_type"]
  1127. self.app.on_cursor_type(val="big")
  1128. self.app.defaults['global_selection_shape'] = False
  1129. def on_manual_cutout(self, click_pos):
  1130. if self.man_cutout_obj is None:
  1131. msg = '[ERROR_NOTCL] %s: %s' % (_("Geometry object for manual cutout not found"), self.man_cutout_obj)
  1132. self.app.inform.emit(msg)
  1133. return
  1134. # use the snapped position as reference
  1135. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  1136. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  1137. gap_type = self.ui.gaptype_radio.get_value()
  1138. gaps_solid_geo = None
  1139. if gap_type == 'bt' and self.ui.thin_depth_entry.get_value() != 0:
  1140. gaps_solid_geo = self.intersect_geo(self.manual_solid_geo, cut_poly)
  1141. if gap_type == 'mb':
  1142. rests_geo = self.intersect_geo(self.mb_manual_solid_geo, cut_poly)
  1143. if isinstance(rests_geo, list):
  1144. self.mb_manual_cuts += rests_geo
  1145. else:
  1146. self.mb_manual_cuts.append(rests_geo)
  1147. # first subtract geometry for the total solid_geometry
  1148. new_solid_geometry = CutOut.subtract_geo(self.man_cutout_obj.solid_geometry, cut_poly)
  1149. new_solid_geometry = linemerge(new_solid_geometry)
  1150. self.man_cutout_obj.solid_geometry = new_solid_geometry
  1151. # then do it on each tool in the manual cutout Geometry object
  1152. try:
  1153. self.man_cutout_obj.multigeo = True
  1154. self.man_cutout_obj.tools[1]['solid_geometry'] = new_solid_geometry
  1155. self.man_cutout_obj.tools[1]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  1156. self.man_cutout_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  1157. self.man_cutout_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1158. self.man_cutout_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1159. except KeyError:
  1160. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No tool in the Geometry object."))
  1161. return
  1162. dia = self.ui.dia.get_value()
  1163. if gaps_solid_geo:
  1164. if 9999 not in self.man_cutout_obj.tools:
  1165. self.man_cutout_obj.tools.update({
  1166. 9999: self.cut_tool_dict
  1167. })
  1168. self.man_cutout_obj.tools[9999]['tooldia'] = str(dia)
  1169. self.man_cutout_obj.tools[9999]['solid_geometry'] = [gaps_solid_geo]
  1170. self.man_cutout_obj.tools[9999]['data']['name'] = self.man_cutout_obj.options['name'] + '_cutout'
  1171. self.man_cutout_obj.tools[9999]['data']['cutz'] = self.ui.thin_depth_entry.get_value()
  1172. self.man_cutout_obj.tools[9999]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1173. self.man_cutout_obj.tools[9999]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1174. self.man_cutout_obj.tools[9999]['data']['override_color'] = "#29a3a3fa"
  1175. else:
  1176. self.man_cutout_obj.tools[9999]['solid_geometry'].append(gaps_solid_geo)
  1177. self.man_cutout_obj.plot(plot_tool=1)
  1178. self.app.inform.emit('%s' % _("Added manual Bridge Gap. Left click to add another or right click to finish."))
  1179. self.app.should_we_save = True
  1180. def on_manual_geo(self):
  1181. name = self.ui.obj_combo.currentText()
  1182. # Get source object.
  1183. try:
  1184. cutout_obj = self.app.collection.get_by_name(str(name))
  1185. except Exception as e:
  1186. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  1187. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  1188. return "Could not retrieve object: %s" % name
  1189. if cutout_obj is None:
  1190. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1191. _("There is no Gerber object selected for Cutout.\n"
  1192. "Select one and try again."))
  1193. return
  1194. if cutout_obj.kind != 'gerber':
  1195. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1196. _("The selected object has to be of Gerber type.\n"
  1197. "Select a Gerber file and try again."))
  1198. return
  1199. dia = float(self.ui.dia.get_value())
  1200. if 0 in {dia}:
  1201. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1202. _("Tool Diameter is zero value. Change it to a positive real number."))
  1203. return
  1204. try:
  1205. kind = self.ui.obj_kind_combo.get_value()
  1206. except ValueError:
  1207. return
  1208. margin = float(self.ui.margin.get_value())
  1209. convex_box = self.ui.convex_box_cb.get_value()
  1210. def geo_init(geo_obj, app_obj):
  1211. geo_union = unary_union(cutout_obj.solid_geometry)
  1212. if convex_box:
  1213. geo = geo_union.convex_hull
  1214. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  1215. elif kind == 'single':
  1216. if isinstance(geo_union, Polygon) or \
  1217. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  1218. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  1219. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  1220. elif isinstance(geo_union, MultiPolygon):
  1221. x0, y0, x1, y1 = geo_union.bounds
  1222. geo = box(x0, y0, x1, y1)
  1223. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  1224. else:
  1225. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1226. _("Geometry not supported"), type(geo_union)))
  1227. return 'fail'
  1228. else:
  1229. geo = geo_union
  1230. geo = geo.buffer(margin + abs(dia / 2))
  1231. if isinstance(geo, Polygon):
  1232. geo_obj.solid_geometry = geo.exterior
  1233. elif isinstance(geo, MultiPolygon):
  1234. solid_geo = []
  1235. for poly in geo:
  1236. solid_geo.append(poly.exterior)
  1237. geo_obj.solid_geometry = deepcopy(solid_geo)
  1238. geo_obj.options['cnctooldia'] = str(dia)
  1239. geo_obj.options['cutz'] = self.ui.cutz_entry.get_value()
  1240. geo_obj.options['multidepth'] = self.ui.mpass_cb.get_value()
  1241. geo_obj.options['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1242. geo_obj.multigeo = True
  1243. geo_obj.tools.update({
  1244. 1: self.cut_tool_dict
  1245. })
  1246. geo_obj.tools[1]['tooldia'] = str(dia)
  1247. geo_obj.tools[1]['solid_geometry'] = geo_obj.solid_geometry
  1248. geo_obj.tools[1]['data']['name'] = outname
  1249. geo_obj.tools[1]['data']['cutz'] = self.ui.cutz_entry.get_value()
  1250. geo_obj.tools[1]['data']['multidepth'] = self.ui.mpass_cb.get_value()
  1251. geo_obj.tools[1]['data']['depthperpass'] = self.ui.maxdepth_entry.get_value()
  1252. outname = cutout_obj.options["name"] + "_cutout"
  1253. self.app.app_obj.new_object('geometry', outname, geo_init)
  1254. def cutting_geo(self, pos):
  1255. self.cutting_dia = float(self.ui.dia.get_value())
  1256. self.cutting_gapsize = float(self.ui.gapsize.get_value())
  1257. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  1258. # cutting area definition
  1259. orig_x = pos[0]
  1260. orig_y = pos[1]
  1261. xmin = orig_x - offset
  1262. ymin = orig_y - offset
  1263. xmax = orig_x + offset
  1264. ymax = orig_y + offset
  1265. cut_poly = box(xmin, ymin, xmax, ymax)
  1266. return cut_poly
  1267. # To be called after clicking on the plot.
  1268. def on_mouse_click_release(self, event):
  1269. if self.app.is_legacy is False:
  1270. event_pos = event.pos
  1271. # event_is_dragging = event.is_dragging
  1272. right_button = 2
  1273. else:
  1274. event_pos = (event.xdata, event.ydata)
  1275. # event_is_dragging = self.app.plotcanvas.is_dragging
  1276. right_button = 3
  1277. try:
  1278. x = float(event_pos[0])
  1279. y = float(event_pos[1])
  1280. except TypeError:
  1281. return
  1282. event_pos = (x, y)
  1283. # do paint single only for left mouse clicks
  1284. if event.button == 1:
  1285. self.app.inform.emit(_("Making manual bridge gap..."))
  1286. pos = self.app.plotcanvas.translate_coords(event_pos)
  1287. self.on_manual_cutout(click_pos=pos)
  1288. # if RMB then we exit
  1289. elif event.button == right_button and self.mouse_is_dragging is False:
  1290. if self.app.is_legacy is False:
  1291. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1292. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1293. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1294. else:
  1295. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1296. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1297. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1298. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1299. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1300. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1301. self.app.on_mouse_click_release_over_plot)
  1302. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1303. # Remove any previous utility shape
  1304. self.app.geo_editor.tool_shape.clear(update=True)
  1305. self.app.geo_editor.tool_shape.enabled = False
  1306. # signal that the mouse events are disconnected from local methods
  1307. self.mouse_events_connected = False
  1308. if self.ui.big_cursor_cb.get_value():
  1309. # restore cursor
  1310. self.app.on_cursor_type(val=self.old_cursor_type)
  1311. # restore selection
  1312. self.app.defaults['global_selection_shape'] = self.old_selection_state
  1313. # rebuild the manual Geometry object
  1314. self.man_cutout_obj.build_ui()
  1315. # plot the final object
  1316. self.man_cutout_obj.plot()
  1317. # mouse bytes
  1318. if self.ui.gaptype_radio.get_value() == 'mb':
  1319. with self.app.proc_container.new("Generating Excellon ..."):
  1320. outname_exc = self.man_cutout_obj.options["name"] + "_mouse_bites"
  1321. self.app.collection.promise(outname_exc)
  1322. def job_thread(app_obj):
  1323. # list of Shapely Points to mark the drill points centers
  1324. holes = []
  1325. mb_dia = self.ui.mb_dia_entry.get_value()
  1326. mb_spacing = self.ui.mb_spacing_entry.get_value()
  1327. for line in self.mb_manual_cuts:
  1328. calc_len = 0
  1329. while calc_len < line.length:
  1330. holes.append(line.interpolate(calc_len))
  1331. calc_len += mb_dia + mb_spacing
  1332. self.mb_manual_cuts[:] = []
  1333. def excellon_init(exc_obj, app_o):
  1334. if not holes:
  1335. return 'fail'
  1336. tools = {
  1337. 1: {
  1338. "tooldia": mb_dia,
  1339. "drills": holes,
  1340. "solid_geometry": []
  1341. }
  1342. }
  1343. exc_obj.tools = tools
  1344. exc_obj.create_geometry()
  1345. exc_obj.source_file = app_o.f_handlers.export_excellon(obj_name=exc_obj.options['name'],
  1346. local_use=exc_obj,
  1347. filename=None,
  1348. use_thread=False)
  1349. # calculate the bounds
  1350. xmin, ymin, xmax, ymax = CutOut.recursive_bounds(exc_obj.solid_geometry)
  1351. exc_obj.options['xmin'] = xmin
  1352. exc_obj.options['ymin'] = ymin
  1353. exc_obj.options['xmax'] = xmax
  1354. exc_obj.options['ymax'] = ymax
  1355. ret = app_obj.app_obj.new_object('excellon', outname_exc, excellon_init)
  1356. if ret == 'fail':
  1357. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Mouse bites failed."))
  1358. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1359. self.app.inform.emit('[success] %s' % _("Finished manual adding of gaps."))
  1360. def on_mouse_move(self, event):
  1361. self.app.on_mouse_move_over_plot(event=event)
  1362. if self.app.is_legacy is False:
  1363. event_pos = event.pos
  1364. event_is_dragging = event.is_dragging
  1365. # right_button = 2
  1366. else:
  1367. event_pos = (event.xdata, event.ydata)
  1368. event_is_dragging = self.app.plotcanvas.is_dragging
  1369. # right_button = 3
  1370. try:
  1371. x = float(event_pos[0])
  1372. y = float(event_pos[1])
  1373. except TypeError:
  1374. return
  1375. event_pos = (x, y)
  1376. pos = self.canvas.translate_coords(event_pos)
  1377. event.xdata, event.ydata = pos[0], pos[1]
  1378. if event_is_dragging is True:
  1379. self.mouse_is_dragging = True
  1380. else:
  1381. self.mouse_is_dragging = False
  1382. try:
  1383. x = float(event.xdata)
  1384. y = float(event.ydata)
  1385. except TypeError:
  1386. return
  1387. if self.app.grid_status():
  1388. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  1389. else:
  1390. snap_x, snap_y = x, y
  1391. self.x_pos, self.y_pos = snap_x, snap_y
  1392. # #################################################
  1393. # ### This section makes the cutting geo to #######
  1394. # ### rotate if it intersects the target geo ######
  1395. # #################################################
  1396. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  1397. man_geo = self.man_cutout_obj.solid_geometry
  1398. def get_angle(geo):
  1399. line = cut_geo.intersection(geo)
  1400. try:
  1401. pt1_x = line.coords[0][0]
  1402. pt1_y = line.coords[0][1]
  1403. pt2_x = line.coords[1][0]
  1404. pt2_y = line.coords[1][1]
  1405. dx = pt1_x - pt2_x
  1406. dy = pt1_y - pt2_y
  1407. if dx == 0 or dy == 0:
  1408. angle = 0
  1409. else:
  1410. radian = math.atan(dx / dy)
  1411. angle = radian * 180 / math.pi
  1412. except Exception:
  1413. angle = 0
  1414. return angle
  1415. try:
  1416. rot_angle = 0
  1417. for geo_el in man_geo:
  1418. if isinstance(geo_el, Polygon):
  1419. work_geo = geo_el.exterior
  1420. if cut_geo.intersects(work_geo):
  1421. rot_angle = get_angle(geo=work_geo)
  1422. else:
  1423. rot_angle = 0
  1424. else:
  1425. rot_angle = 0
  1426. if cut_geo.intersects(geo_el):
  1427. rot_angle = get_angle(geo=geo_el)
  1428. if rot_angle != 0:
  1429. break
  1430. except TypeError:
  1431. if isinstance(man_geo, Polygon):
  1432. work_geo = man_geo.exterior
  1433. if cut_geo.intersects(work_geo):
  1434. rot_angle = get_angle(geo=work_geo)
  1435. else:
  1436. rot_angle = 0
  1437. else:
  1438. rot_angle = 0
  1439. if cut_geo.intersects(man_geo):
  1440. rot_angle = get_angle(geo=man_geo)
  1441. # rotate only if there is an angle to rotate to
  1442. if rot_angle != 0:
  1443. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  1444. # Remove any previous utility shape
  1445. self.app.geo_editor.tool_shape.clear(update=True)
  1446. self.draw_utility_geometry(geo=cut_geo)
  1447. def draw_utility_geometry(self, geo):
  1448. self.app.geo_editor.tool_shape.add(
  1449. shape=geo,
  1450. color=(self.app.defaults["global_draw_color"] + '80'),
  1451. update=False,
  1452. layer=0,
  1453. tolerance=None)
  1454. self.app.geo_editor.tool_shape.redraw()
  1455. def on_key_press(self, event):
  1456. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1457. if type(event) is int:
  1458. key = event
  1459. # events from the GUI are of type QKeyEvent
  1460. elif type(event) == QtGui.QKeyEvent:
  1461. key = event.key()
  1462. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1463. key = event.key
  1464. key = QtGui.QKeySequence(key)
  1465. # check for modifiers
  1466. key_string = key.toString().lower()
  1467. if '+' in key_string:
  1468. mod, __, key_text = key_string.rpartition('+')
  1469. if mod.lower() == 'ctrl':
  1470. # modifiers = QtCore.Qt.ControlModifier
  1471. pass
  1472. elif mod.lower() == 'alt':
  1473. # modifiers = QtCore.Qt.AltModifier
  1474. pass
  1475. elif mod.lower() == 'shift':
  1476. # modifiers = QtCore.Qt.ShiftModifier
  1477. pass
  1478. else:
  1479. # modifiers = QtCore.Qt.NoModifier
  1480. pass
  1481. key = QtGui.QKeySequence(key_text)
  1482. # events from Vispy are of type KeyEvent
  1483. else:
  1484. key = event.key
  1485. # Escape = Deselect All
  1486. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1487. if self.mouse_events_connected is True:
  1488. self.mouse_events_connected = False
  1489. if self.app.is_legacy is False:
  1490. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1491. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1492. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1493. else:
  1494. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1495. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1496. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1497. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1498. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1499. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1500. self.app.on_mouse_click_release_over_plot)
  1501. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1502. if self.ui.big_cursor_cb.get_value():
  1503. # restore cursor
  1504. self.app.on_cursor_type(val=self.old_cursor_type)
  1505. # restore selection
  1506. self.app.defaults['global_selection_shape'] = self.old_selection_state
  1507. # Remove any previous utility shape
  1508. self.app.geo_editor.tool_shape.clear(update=True)
  1509. self.app.geo_editor.tool_shape.enabled = False
  1510. # Grid toggle
  1511. if key == QtCore.Qt.Key_G or key == 'G':
  1512. self.app.ui.grid_snap_btn.trigger()
  1513. # Jump to coords
  1514. if key == QtCore.Qt.Key_J or key == 'J':
  1515. l_x, l_y = self.app.on_jump_to()
  1516. self.app.geo_editor.tool_shape.clear(update=True)
  1517. geo = self.cutting_geo(pos=(l_x, l_y))
  1518. self.draw_utility_geometry(geo=geo)
  1519. @staticmethod
  1520. def subtract_poly_from_geo(solid_geo, pts):
  1521. """
  1522. Subtract polygon made from points from the given object.
  1523. This only operates on the paths in the original geometry,
  1524. i.e. it converts polygons into paths.
  1525. :param solid_geo: Geometry from which to subtract.
  1526. :param pts: a tuple of coordinates in format (x0, y0, x1, y1)
  1527. :type pts: tuple
  1528. x0: x coord for lower left vertex of the polygon.
  1529. y0: y coord for lower left vertex of the polygon.
  1530. x1: x coord for upper right vertex of the polygon.
  1531. y1: y coord for upper right vertex of the polygon.
  1532. :return: none
  1533. """
  1534. x0 = pts[0]
  1535. y0 = pts[1]
  1536. x1 = pts[2]
  1537. y1 = pts[3]
  1538. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1539. # pathonly should be always True, otherwise polygons are not subtracted
  1540. flat_geometry = CutOut.flatten(geometry=solid_geo)
  1541. log.debug("%d paths" % len(flat_geometry))
  1542. polygon = Polygon(points)
  1543. toolgeo = unary_union(polygon)
  1544. diffs = []
  1545. for target in flat_geometry:
  1546. if type(target) == LineString or type(target) == LinearRing:
  1547. diffs.append(target.difference(toolgeo))
  1548. else:
  1549. log.warning("Not implemented.")
  1550. return unary_union(diffs)
  1551. @staticmethod
  1552. def flatten(geometry):
  1553. """
  1554. Creates a list of non-iterable linear geometry objects.
  1555. Polygons are expanded into its exterior and interiors.
  1556. Results are placed in self.flat_geometry
  1557. :param geometry: Shapely type or list or list of list of such.
  1558. """
  1559. flat_geo = []
  1560. try:
  1561. for geo in geometry:
  1562. if geo:
  1563. flat_geo += CutOut.flatten(geometry=geo)
  1564. except TypeError:
  1565. if isinstance(geometry, Polygon) and not geometry.is_empty:
  1566. flat_geo.append(geometry.exterior)
  1567. CutOut.flatten(geometry=geometry.interiors)
  1568. elif not geometry.is_empty:
  1569. flat_geo.append(geometry)
  1570. return flat_geo
  1571. @staticmethod
  1572. def recursive_bounds(geometry):
  1573. """
  1574. Return the bounds of the biggest bounding box in geometry, one that include all.
  1575. :param geometry: a iterable object that holds geometry
  1576. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1577. """
  1578. # now it can get bounds for nested lists of objects
  1579. def bounds_rec(obj):
  1580. try:
  1581. minx = Inf
  1582. miny = Inf
  1583. maxx = -Inf
  1584. maxy = -Inf
  1585. for k in obj:
  1586. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1587. minx = min(minx, minx_)
  1588. miny = min(miny, miny_)
  1589. maxx = max(maxx, maxx_)
  1590. maxy = max(maxy, maxy_)
  1591. return minx, miny, maxx, maxy
  1592. except TypeError:
  1593. # it's a Shapely object, return it's bounds
  1594. if obj:
  1595. return obj.bounds
  1596. return bounds_rec(geometry)
  1597. @staticmethod
  1598. def subtract_geo(target_geo, subtractor):
  1599. """
  1600. Subtract subtractor polygon from the target_geo. This only operates on the paths in the target_geo,
  1601. i.e. it converts polygons into paths.
  1602. :param target_geo: geometry from which to subtract
  1603. :param subtractor: a list of Points, a LinearRing or a Polygon that will be subtracted from target_geo
  1604. :return: a unary_union of the resulting geometry
  1605. """
  1606. if target_geo is None:
  1607. target_geo = []
  1608. # flatten() takes care of possible empty geometry making sure that is filtered
  1609. flat_geometry = CutOut.flatten(target_geo)
  1610. log.debug("%d paths" % len(flat_geometry))
  1611. toolgeo = unary_union(subtractor)
  1612. diffs = []
  1613. for target in flat_geometry:
  1614. if isinstance(target, LineString) or isinstance(target, LinearRing) or isinstance(target, MultiLineString):
  1615. diffs.append(target.difference(toolgeo))
  1616. else:
  1617. log.warning("Not implemented.")
  1618. return unary_union(diffs)
  1619. @staticmethod
  1620. def intersect_geo(target_geo, second_geo):
  1621. """
  1622. :param target_geo:
  1623. :type target_geo:
  1624. :param second_geo:
  1625. :type second_geo:
  1626. :return:
  1627. :rtype:
  1628. """
  1629. results = []
  1630. try:
  1631. __ = iter(target_geo)
  1632. except TypeError:
  1633. target_geo = [target_geo]
  1634. for geo in target_geo:
  1635. if second_geo.intersects(geo):
  1636. results.append(second_geo.intersection(geo))
  1637. return CutOut.flatten(results)
  1638. def reset_fields(self):
  1639. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1640. class CutoutUI:
  1641. toolName = _("Cutout PCB")
  1642. def __init__(self, layout, app):
  1643. self.app = app
  1644. self.decimals = self.app.decimals
  1645. self.layout = layout
  1646. # Title
  1647. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1648. title_label.setStyleSheet("""
  1649. QLabel
  1650. {
  1651. font-size: 16px;
  1652. font-weight: bold;
  1653. }
  1654. """)
  1655. self.layout.addWidget(title_label)
  1656. self.layout.addWidget(QtWidgets.QLabel(''))
  1657. # Form Layout
  1658. grid0 = QtWidgets.QGridLayout()
  1659. grid0.setColumnStretch(0, 0)
  1660. grid0.setColumnStretch(1, 1)
  1661. self.layout.addLayout(grid0)
  1662. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  1663. self.object_label.setToolTip('%s.' % _("Object to be cutout"))
  1664. grid0.addWidget(self.object_label, 0, 0, 1, 2)
  1665. # Object kind
  1666. self.kindlabel = QtWidgets.QLabel('%s:' % _('Kind'))
  1667. self.kindlabel.setToolTip(
  1668. _("Choice of what kind the object we want to cutout is.\n"
  1669. "- Single: contain a single PCB Gerber outline object.\n"
  1670. "- Panel: a panel PCB Gerber object, which is made\n"
  1671. "out of many individual PCB outlines.")
  1672. )
  1673. self.obj_kind_combo = RadioSet([
  1674. {"label": _("Single"), "value": "single"},
  1675. {"label": _("Panel"), "value": "panel"},
  1676. ])
  1677. grid0.addWidget(self.kindlabel, 2, 0)
  1678. grid0.addWidget(self.obj_kind_combo, 2, 1)
  1679. # Type of object to be cutout
  1680. self.type_obj_radio = RadioSet([
  1681. {"label": _("Gerber"), "value": "grb"},
  1682. {"label": _("Geometry"), "value": "geo"},
  1683. ])
  1684. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Type"))
  1685. self.type_obj_combo_label.setToolTip(
  1686. _("Specify the type of object to be cutout.\n"
  1687. "It can be of type: Gerber or Geometry.\n"
  1688. "What is selected here will dictate the kind\n"
  1689. "of objects that will populate the 'Object' combobox.")
  1690. )
  1691. grid0.addWidget(self.type_obj_combo_label, 4, 0)
  1692. grid0.addWidget(self.type_obj_radio, 4, 1)
  1693. # Object to be cutout
  1694. self.obj_combo = FCComboBox()
  1695. self.obj_combo.setModel(self.app.collection)
  1696. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1697. self.obj_combo.is_last = True
  1698. grid0.addWidget(self.obj_combo, 6, 0, 1, 2)
  1699. # Convex Shape
  1700. # Surrounding convex box shape
  1701. self.convex_box_label = QtWidgets.QLabel('%s:' % _("Convex Shape"))
  1702. self.convex_box_label.setToolTip(
  1703. _("Create a convex shape surrounding the entire PCB.\n"
  1704. "Used only if the source object type is Gerber.")
  1705. )
  1706. self.convex_box_cb = FCCheckBox()
  1707. self.convex_box_cb.setToolTip(
  1708. _("Create a convex shape surrounding the entire PCB.\n"
  1709. "Used only if the source object type is Gerber.")
  1710. )
  1711. grid0.addWidget(self.convex_box_label, 8, 0)
  1712. grid0.addWidget(self.convex_box_cb, 8, 1)
  1713. separator_line = QtWidgets.QFrame()
  1714. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1715. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1716. grid0.addWidget(separator_line, 10, 0, 1, 2)
  1717. self.tool_sel_label = FCLabel('<b>%s</b>' % _('Cutout Tool'))
  1718. grid0.addWidget(self.tool_sel_label, 12, 0, 1, 2)
  1719. # Tool Diameter
  1720. self.dia = FCDoubleSpinner(callback=self.confirmation_message)
  1721. self.dia.set_precision(self.decimals)
  1722. self.dia.set_range(0.0000, 10000.0000)
  1723. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool Dia"))
  1724. self.dia_label.setToolTip(
  1725. _("Diameter of the tool used to cutout\n"
  1726. "the PCB shape out of the surrounding material.")
  1727. )
  1728. grid0.addWidget(self.dia_label, 14, 0)
  1729. grid0.addWidget(self.dia, 14, 1)
  1730. hlay = QtWidgets.QHBoxLayout()
  1731. # Search and Add new Tool
  1732. self.add_newtool_button = FCButton(_('Search and Add'))
  1733. self.add_newtool_button.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
  1734. self.add_newtool_button.setToolTip(
  1735. _("Add a new tool to the Tool Table\n"
  1736. "with the diameter specified above.\n"
  1737. "This is done by a background search\n"
  1738. "in the Tools Database. If nothing is found\n"
  1739. "in the Tools DB then a default tool is added.")
  1740. )
  1741. hlay.addWidget(self.add_newtool_button)
  1742. # Pick from DB new Tool
  1743. self.addtool_from_db_btn = FCButton(_('Pick from DB'))
  1744. self.addtool_from_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/search_db32.png'))
  1745. self.addtool_from_db_btn.setToolTip(
  1746. _("Add a new tool to the Tool Table\n"
  1747. "from the Tools Database.\n"
  1748. "Tools database administration in in:\n"
  1749. "Menu: Options -> Tools Database")
  1750. )
  1751. hlay.addWidget(self.addtool_from_db_btn)
  1752. grid0.addLayout(hlay, 16, 0, 1, 2)
  1753. separator_line = QtWidgets.QFrame()
  1754. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1755. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1756. grid0.addWidget(separator_line, 18, 0, 1, 2)
  1757. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _("Tool Parameters"))
  1758. grid0.addWidget(self.param_label, 20, 0, 1, 2)
  1759. # Cut Z
  1760. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1761. cutzlabel.setToolTip(
  1762. _(
  1763. "Cutting depth (negative)\n"
  1764. "below the copper surface."
  1765. )
  1766. )
  1767. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1768. self.cutz_entry.set_precision(self.decimals)
  1769. if machinist_setting == 0:
  1770. self.cutz_entry.setRange(-10000.0000, -0.00001)
  1771. else:
  1772. self.cutz_entry.setRange(-10000.0000, 10000.0000)
  1773. self.cutz_entry.setSingleStep(0.1)
  1774. grid0.addWidget(cutzlabel, 22, 0)
  1775. grid0.addWidget(self.cutz_entry, 22, 1)
  1776. # Multi-pass
  1777. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  1778. self.mpass_cb.setToolTip(
  1779. _(
  1780. "Use multiple passes to limit\n"
  1781. "the cut depth in each pass. Will\n"
  1782. "cut multiple times until Cut Z is\n"
  1783. "reached."
  1784. )
  1785. )
  1786. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1787. self.maxdepth_entry.set_precision(self.decimals)
  1788. self.maxdepth_entry.setRange(0, 10000.0000)
  1789. self.maxdepth_entry.setSingleStep(0.1)
  1790. self.maxdepth_entry.setToolTip(
  1791. _(
  1792. "Depth of each pass (positive)."
  1793. )
  1794. )
  1795. grid0.addWidget(self.mpass_cb, 24, 0)
  1796. grid0.addWidget(self.maxdepth_entry, 24, 1)
  1797. self.ois_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  1798. # Margin
  1799. self.margin = FCDoubleSpinner(callback=self.confirmation_message)
  1800. self.margin.set_range(-10000.0000, 10000.0000)
  1801. self.margin.setSingleStep(0.1)
  1802. self.margin.set_precision(self.decimals)
  1803. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  1804. self.margin_label.setToolTip(
  1805. _("Margin over bounds. A positive value here\n"
  1806. "will make the cutout of the PCB further from\n"
  1807. "the actual PCB border")
  1808. )
  1809. grid0.addWidget(self.margin_label, 26, 0)
  1810. grid0.addWidget(self.margin, 26, 1)
  1811. # Gapsize
  1812. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size"))
  1813. self.gapsize_label.setToolTip(
  1814. _("The size of the bridge gaps in the cutout\n"
  1815. "used to keep the board connected to\n"
  1816. "the surrounding material (the one \n"
  1817. "from which the PCB is cutout).")
  1818. )
  1819. self.gapsize = FCDoubleSpinner(callback=self.confirmation_message)
  1820. self.gapsize.set_precision(self.decimals)
  1821. grid0.addWidget(self.gapsize_label, 28, 0)
  1822. grid0.addWidget(self.gapsize, 28, 1)
  1823. # Gap Type
  1824. self.gaptype_label = FCLabel('%s:' % _("Gap type"))
  1825. self.gaptype_label.setToolTip(
  1826. _("The type of gap:\n"
  1827. "- Bridge -> the cutout will be interrupted by bridges\n"
  1828. "- Thin -> same as 'bridge' but it will be thinner by partially milling the gap\n"
  1829. "- M-Bites -> 'Mouse Bites' - same as 'bridge' but covered with drill holes")
  1830. )
  1831. self.gaptype_radio = RadioSet(
  1832. [
  1833. {'label': _('Bridge'), 'value': 'b'},
  1834. {'label': _('Thin'), 'value': 'bt'},
  1835. {'label': "M-Bites", 'value': 'mb'}
  1836. ],
  1837. stretch=True
  1838. )
  1839. grid0.addWidget(self.gaptype_label, 30, 0)
  1840. grid0.addWidget(self.gaptype_radio, 30, 1)
  1841. # Thin gaps Depth
  1842. self.thin_depth_label = FCLabel('%s:' % _("Depth"))
  1843. self.thin_depth_label.setToolTip(
  1844. _("The depth until the milling is done\n"
  1845. "in order to thin the gaps.")
  1846. )
  1847. self.thin_depth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1848. self.thin_depth_entry.set_precision(self.decimals)
  1849. if machinist_setting == 0:
  1850. self.thin_depth_entry.setRange(-10000.0000, -0.00001)
  1851. else:
  1852. self.thin_depth_entry.setRange(-10000.0000, 10000.0000)
  1853. self.thin_depth_entry.setSingleStep(0.1)
  1854. grid0.addWidget(self.thin_depth_label, 32, 0)
  1855. grid0.addWidget(self.thin_depth_entry, 32, 1)
  1856. # Mouse Bites Tool Diameter
  1857. self.mb_dia_label = FCLabel('%s:' % _("Tool Diameter"))
  1858. self.mb_dia_label.setToolTip(
  1859. _("The drill hole diameter when doing mouse bites.")
  1860. )
  1861. self.mb_dia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1862. self.mb_dia_entry.set_precision(self.decimals)
  1863. self.mb_dia_entry.setRange(0, 100.0000)
  1864. grid0.addWidget(self.mb_dia_label, 34, 0)
  1865. grid0.addWidget(self.mb_dia_entry, 34, 1)
  1866. # Mouse Bites Holes Spacing
  1867. self.mb_spacing_label = FCLabel('%s:' % _("Spacing"))
  1868. self.mb_spacing_label.setToolTip(
  1869. _("The spacing between drill holes when doing mouse bites.")
  1870. )
  1871. self.mb_spacing_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1872. self.mb_spacing_entry.set_precision(self.decimals)
  1873. self.mb_spacing_entry.setRange(0, 100.0000)
  1874. grid0.addWidget(self.mb_spacing_label, 36, 0)
  1875. grid0.addWidget(self.mb_spacing_entry, 36, 1)
  1876. separator_line = QtWidgets.QFrame()
  1877. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1878. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1879. grid0.addWidget(separator_line, 38, 0, 1, 2)
  1880. # Title2
  1881. title_param_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Automatic'), _("Bridge Gaps")))
  1882. title_param_label.setToolTip(
  1883. _("This section handle creation of automatic bridge gaps.")
  1884. )
  1885. grid0.addWidget(title_param_label, 40, 0, 1, 2)
  1886. # Gaps
  1887. # How gaps wil be rendered:
  1888. # lr - left + right
  1889. # tb - top + bottom
  1890. # 4 - left + right +top + bottom
  1891. # 2lr - 2*left + 2*right
  1892. # 2tb - 2*top + 2*bottom
  1893. # 8 - 2*left + 2*right +2*top + 2*bottom
  1894. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  1895. gaps_label.setToolTip(
  1896. _("Number of gaps used for the Automatic cutout.\n"
  1897. "There can be maximum 8 bridges/gaps.\n"
  1898. "The choices are:\n"
  1899. "- None - no gaps\n"
  1900. "- lr - left + right\n"
  1901. "- tb - top + bottom\n"
  1902. "- 4 - left + right +top + bottom\n"
  1903. "- 2lr - 2*left + 2*right\n"
  1904. "- 2tb - 2*top + 2*bottom\n"
  1905. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  1906. )
  1907. # gaps_label.setMinimumWidth(60)
  1908. self.gaps = FCComboBox()
  1909. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  1910. for it in gaps_items:
  1911. self.gaps.addItem(it)
  1912. # self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  1913. grid0.addWidget(gaps_label, 42, 0)
  1914. grid0.addWidget(self.gaps, 42, 1)
  1915. # Buttons
  1916. self.ff_cutout_object_btn = FCButton(_("Generate Geometry"))
  1917. self.ff_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/irregular32.png'))
  1918. self.ff_cutout_object_btn.setToolTip(
  1919. _("Cutout the selected object.\n"
  1920. "The cutout shape can be of any shape.\n"
  1921. "Useful when the PCB has a non-rectangular shape.")
  1922. )
  1923. self.ff_cutout_object_btn.setStyleSheet("""
  1924. QPushButton
  1925. {
  1926. font-weight: bold;
  1927. }
  1928. """)
  1929. grid0.addWidget(self.ff_cutout_object_btn, 44, 0, 1, 2)
  1930. self.rect_cutout_object_btn = FCButton(_("Generate Geometry"))
  1931. self.rect_cutout_object_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1932. self.rect_cutout_object_btn.setToolTip(
  1933. _("Cutout the selected object.\n"
  1934. "The resulting cutout shape is\n"
  1935. "always a rectangle shape and it will be\n"
  1936. "the bounding box of the Object.")
  1937. )
  1938. self.rect_cutout_object_btn.setStyleSheet("""
  1939. QPushButton
  1940. {
  1941. font-weight: bold;
  1942. }
  1943. """)
  1944. grid0.addWidget(self.rect_cutout_object_btn, 46, 0, 1, 2)
  1945. separator_line = QtWidgets.QFrame()
  1946. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1947. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1948. grid0.addWidget(separator_line, 48, 0, 1, 2)
  1949. # MANUAL BRIDGE GAPS
  1950. title_manual_label = QtWidgets.QLabel("<b>%s %s</b>:" % (_('Manual'), _("Bridge Gaps")))
  1951. title_manual_label.setToolTip(
  1952. _("This section handle creation of manual bridge gaps.\n"
  1953. "This is done by mouse clicking on the perimeter of the\n"
  1954. "Geometry object that is used as a cutout object. ")
  1955. )
  1956. grid0.addWidget(title_manual_label, 50, 0, 1, 2)
  1957. # Big Cursor
  1958. big_cursor_label = QtWidgets.QLabel('%s:' % _("Big cursor"))
  1959. big_cursor_label.setToolTip(
  1960. _("Use a big cursor when adding manual gaps."))
  1961. self.big_cursor_cb = FCCheckBox()
  1962. grid0.addWidget(big_cursor_label, 52, 0)
  1963. grid0.addWidget(self.big_cursor_cb, 52, 1)
  1964. # Generate a surrounding Geometry object
  1965. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  1966. self.man_geo_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/rectangle32.png'))
  1967. self.man_geo_creation_btn.setToolTip(
  1968. _("If the object to be cutout is a Gerber\n"
  1969. "first create a Geometry that surrounds it,\n"
  1970. "to be used as the cutout, if one doesn't exist yet.\n"
  1971. "Select the source Gerber file in the top object combobox.")
  1972. )
  1973. # self.man_geo_creation_btn.setStyleSheet("""
  1974. # QPushButton
  1975. # {
  1976. # font-weight: bold;
  1977. # }
  1978. # """)
  1979. grid0.addWidget(self.man_geo_creation_btn, 54, 0, 1, 2)
  1980. # Manual Geo Object
  1981. self.man_object_combo = FCComboBox()
  1982. self.man_object_combo.setModel(self.app.collection)
  1983. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1984. self.man_object_combo.is_last = True
  1985. self.man_object_combo.obj_type = "Geometry"
  1986. self.man_object_label = QtWidgets.QLabel('%s:' % _("Manual cutout Geometry"))
  1987. self.man_object_label.setToolTip(
  1988. _("Geometry object used to create the manual cutout.")
  1989. )
  1990. # self.man_object_label.setMinimumWidth(60)
  1991. grid0.addWidget(self.man_object_label, 56, 0, 1, 2)
  1992. grid0.addWidget(self.man_object_combo, 56, 0, 1, 2)
  1993. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  1994. self.man_gaps_creation_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/gaps32.png'))
  1995. self.man_gaps_creation_btn.setToolTip(
  1996. _("Use the left mouse button (LMB) click\n"
  1997. "to create a bridge gap to separate the PCB from\n"
  1998. "the surrounding material.\n"
  1999. "The LMB click has to be done on the perimeter of\n"
  2000. "the Geometry object used as a cutout geometry.")
  2001. )
  2002. self.man_gaps_creation_btn.setStyleSheet("""
  2003. QPushButton
  2004. {
  2005. font-weight: bold;
  2006. }
  2007. """)
  2008. grid0.addWidget(self.man_gaps_creation_btn, 58, 0, 1, 2)
  2009. self.layout.addStretch()
  2010. # ## Reset Tool
  2011. self.reset_button = FCButton(_("Reset Tool"))
  2012. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  2013. self.reset_button.setToolTip(
  2014. _("Will reset the tool parameters.")
  2015. )
  2016. self.reset_button.setStyleSheet("""
  2017. QPushButton
  2018. {
  2019. font-weight: bold;
  2020. }
  2021. """)
  2022. self.layout.addWidget(self.reset_button)
  2023. self.gaptype_radio.activated_custom.connect(self.on_gap_type_radio)
  2024. # ############################ FINSIHED GUI ###################################
  2025. # #############################################################################
  2026. def on_gap_type_radio(self, val):
  2027. if val == 'b':
  2028. self.thin_depth_label.hide()
  2029. self.thin_depth_entry.hide()
  2030. self.mb_dia_label.hide()
  2031. self.mb_dia_entry.hide()
  2032. self.mb_spacing_label.hide()
  2033. self.mb_spacing_entry.hide()
  2034. elif val == 'bt':
  2035. self.thin_depth_label.show()
  2036. self.thin_depth_entry.show()
  2037. self.mb_dia_label.hide()
  2038. self.mb_dia_entry.hide()
  2039. self.mb_spacing_label.hide()
  2040. self.mb_spacing_entry.hide()
  2041. elif val == 'mb':
  2042. self.thin_depth_label.hide()
  2043. self.thin_depth_entry.hide()
  2044. self.mb_dia_label.show()
  2045. self.mb_dia_entry.show()
  2046. self.mb_spacing_label.show()
  2047. self.mb_spacing_entry.show()
  2048. def confirmation_message(self, accepted, minval, maxval):
  2049. if accepted is False:
  2050. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2051. self.decimals,
  2052. minval,
  2053. self.decimals,
  2054. maxval), False)
  2055. else:
  2056. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2057. def confirmation_message_int(self, accepted, minval, maxval):
  2058. if accepted is False:
  2059. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2060. (_("Edited value is out of range"), minval, maxval), False)
  2061. else:
  2062. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)