ToolCutOut.py 105 KB

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