ToolCutOut.py 91 KB

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