ToolCutOut.py 72 KB

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