ToolCutOut.py 105 KB

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