ToolCutOut.py 90 KB

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