ToolCutOut.py 102 KB

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