ToolCutOut.py 93 KB

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