ToolCutOut.py 75 KB

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