ToolCutOut.py 101 KB

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