ToolCutOut.py 105 KB

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