ToolCutOut.py 105 KB

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