ToolIsolation.py 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File by: Marius Adrian Stanciu (c) #
  4. # Date: 5/25/2020 #
  5. # License: MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCCheckBox, FCDoubleSpinner, RadioSet, FCTable, FCInputDialog, FCButton, \
  10. FCComboBox, OptionalInputSection, FCSpinner
  11. from appParsers.ParseGerber import Gerber
  12. from copy import deepcopy
  13. import numpy as np
  14. import math
  15. from shapely.ops import cascaded_union
  16. from shapely.geometry import MultiPolygon, Polygon, MultiLineString, LineString, LinearRing, Point
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import logging
  19. import gettext
  20. import appTranslation as fcTranslate
  21. import builtins
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. class ToolIsolation(AppTool, Gerber):
  27. def __init__(self, app):
  28. self.app = app
  29. self.decimals = self.app.decimals
  30. AppTool.__init__(self, app)
  31. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  32. # #############################################################################
  33. # ######################### Tool GUI ##########################################
  34. # #############################################################################
  35. self.ui = IsoUI(layout=self.layout, app=self.app)
  36. # #############################################################################
  37. # ###################### Setup CONTEXT MENU ###################################
  38. # #############################################################################
  39. self.ui.tools_table.setupContextMenu()
  40. self.ui.tools_table.addContextMenu(
  41. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  42. )
  43. self.ui.tools_table.addContextMenu(
  44. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  45. )
  46. self.ui.tools_table.addContextMenu(
  47. _("Delete"), lambda:
  48. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  49. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  50. )
  51. # #############################################################################
  52. # ########################## VARIABLES ########################################
  53. # #############################################################################
  54. self.units = ''
  55. self.iso_tools = {}
  56. self.tooluid = 0
  57. # store here the default data for Geometry Data
  58. self.default_data = {}
  59. self.obj_name = ""
  60. self.grb_obj = None
  61. self.sel_rect = []
  62. self.first_click = False
  63. self.cursor_pos = None
  64. self.mouse_is_dragging = False
  65. # store here the points for the "Polygon" area selection shape
  66. self.points = []
  67. # set this as True when in middle of drawing a "Polygon" area selection shape
  68. # it is made False by first click to signify that the shape is complete
  69. self.poly_drawn = False
  70. self.mm = None
  71. self.mr = None
  72. self.kp = None
  73. # store geometry from Polygon selection
  74. self.poly_dict = {}
  75. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  76. # store here the state of the combine_cb GUI element
  77. # used when the rest machining is toggled
  78. self.old_combine_state = None
  79. # store here solid_geometry when there are tool with isolation job
  80. self.solid_geometry = []
  81. self.tool_type_item_options = []
  82. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  83. self.tooldia = None
  84. # multiprocessing
  85. self.pool = self.app.pool
  86. self.results = []
  87. # disconnect flags
  88. self.area_sel_disconnect_flag = False
  89. self.poly_sel_disconnect_flag = False
  90. self.form_fields = {
  91. "tools_iso_passes": self.ui.passes_entry,
  92. "tools_iso_overlap": self.ui.iso_overlap_entry,
  93. "tools_iso_milling_type": self.ui.milling_type_radio,
  94. "tools_iso_combine": self.ui.combine_passes_cb,
  95. "tools_iso_follow": self.ui.follow_cb,
  96. "tools_iso_isotype": self.ui.iso_type_radio
  97. }
  98. self.name2option = {
  99. "i_passes": "tools_iso_passes",
  100. "i_overlap": "tools_iso_overlap",
  101. "i_milling_type": "tools_iso_milling_type",
  102. "i_combine": "tools_iso_combine",
  103. "i_follow": "tools_iso_follow",
  104. "i_iso_type": "tools_iso_isotype"
  105. }
  106. self.old_tool_dia = None
  107. self.connect_signals_at_init()
  108. def install(self, icon=None, separator=None, **kwargs):
  109. AppTool.install(self, icon, separator, shortcut='Alt+I', **kwargs)
  110. def run(self, toggle=True):
  111. self.app.defaults.report_usage("ToolIsolation()")
  112. log.debug("ToolIsolation().run() was launched ...")
  113. if toggle:
  114. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  115. if self.app.ui.splitter.sizes()[0] == 0:
  116. self.app.ui.splitter.setSizes([1, 1])
  117. else:
  118. try:
  119. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  120. # if tab is populated with the tool but it does not have the focus, focus on it
  121. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  122. # focus on Tool Tab
  123. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  124. else:
  125. self.app.ui.splitter.setSizes([0, 1])
  126. except AttributeError:
  127. pass
  128. else:
  129. if self.app.ui.splitter.sizes()[0] == 0:
  130. self.app.ui.splitter.setSizes([1, 1])
  131. AppTool.run(self)
  132. self.set_tool_ui()
  133. # reset those objects on a new run
  134. self.grb_obj = None
  135. self.obj_name = ''
  136. self.build_ui()
  137. # all the tools are selected by default
  138. self.ui.tools_table.selectAll()
  139. self.app.ui.notebook.setTabText(2, _("Isolation Tool"))
  140. def connect_signals_at_init(self):
  141. # #############################################################################
  142. # ############################ SIGNALS ########################################
  143. # #############################################################################
  144. self.ui.addtool_btn.clicked.connect(self.on_tool_add)
  145. self.ui.addtool_entry.returnPressed.connect(self.on_tooldia_updated)
  146. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  147. self.ui.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  148. self.ui.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  149. self.ui.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  150. self.ui.reference_combo_type.currentIndexChanged.connect(self.on_reference_combo_changed)
  151. self.ui.select_combo.currentIndexChanged.connect(self.on_toggle_reference)
  152. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  153. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  154. self.ui.type_excobj_radio.activated_custom.connect(self.on_type_excobj_index_changed)
  155. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  156. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  157. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  158. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  159. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  160. self.app.cleanup.connect(self.set_tool_ui)
  161. def on_type_excobj_index_changed(self, val):
  162. obj_type = 0 if val == 'gerber' else 2
  163. self.ui.exc_obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  164. self.ui.exc_obj_combo.setCurrentIndex(0)
  165. self.ui.exc_obj_combo.obj_type = {
  166. "gerber": "Gerber", "geometry": "Geometry"
  167. }[self.ui.type_excobj_radio.get_value()]
  168. def set_tool_ui(self):
  169. self.units = self.app.defaults['units'].upper()
  170. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  171. # try to select in the Gerber combobox the active object
  172. try:
  173. selected_obj = self.app.collection.get_active()
  174. if selected_obj.kind == 'gerber':
  175. current_name = selected_obj.options['name']
  176. self.ui.object_combo.set_value(current_name)
  177. except Exception:
  178. pass
  179. app_mode = self.app.defaults["global_app_level"]
  180. # Show/Hide Advanced Options
  181. if app_mode == 'b':
  182. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  183. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  184. self.ui.tool_type_radio.set_value('C1')
  185. self.ui.tool_type_label.hide()
  186. self.ui.tool_type_radio.hide()
  187. self.ui.milling_type_label.hide()
  188. self.ui.milling_type_radio.hide()
  189. self.ui.iso_type_label.hide()
  190. self.ui.iso_type_radio.set_value('full')
  191. self.ui.iso_type_radio.hide()
  192. self.ui.follow_cb.set_value(False)
  193. self.ui.follow_cb.hide()
  194. self.ui.follow_label.hide()
  195. self.ui.rest_cb.set_value(False)
  196. self.ui.rest_cb.hide()
  197. self.ui.except_cb.set_value(False)
  198. self.ui.except_cb.hide()
  199. self.ui.type_excobj_radio.hide()
  200. self.ui.exc_obj_combo.hide()
  201. self.ui.select_combo.setCurrentIndex(0)
  202. self.ui.select_combo.hide()
  203. self.ui.select_label.hide()
  204. else:
  205. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  206. self.ui.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  207. self.ui.tool_type_label.show()
  208. self.ui.tool_type_radio.show()
  209. self.ui.milling_type_label.show()
  210. self.ui.milling_type_radio.show()
  211. self.ui.iso_type_label.show()
  212. self.ui.iso_type_radio.set_value(self.app.defaults["tools_iso_isotype"])
  213. self.ui.iso_type_radio.show()
  214. self.ui.follow_cb.set_value(self.app.defaults["tools_iso_follow"])
  215. self.ui.follow_cb.show()
  216. self.ui.follow_label.show()
  217. self.ui.rest_cb.set_value(self.app.defaults["tools_iso_rest"])
  218. self.ui.rest_cb.show()
  219. self.ui.except_cb.set_value(self.app.defaults["tools_iso_isoexcept"])
  220. self.ui.except_cb.show()
  221. self.ui.select_combo.set_value(self.app.defaults["tools_iso_selection"])
  222. self.ui.select_combo.show()
  223. self.ui.select_label.show()
  224. if self.app.defaults["gerber_buffering"] == 'no':
  225. self.ui.create_buffer_button.show()
  226. try:
  227. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  228. except TypeError:
  229. pass
  230. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  231. else:
  232. self.ui.create_buffer_button.hide()
  233. self.ui.tools_frame.show()
  234. self.ui.type_excobj_radio.set_value('gerber')
  235. # run those once so the obj_type attribute is updated for the FCComboboxes
  236. # so the last loaded object is displayed
  237. self.on_type_excobj_index_changed(val="gerber")
  238. self.on_reference_combo_changed()
  239. self.ui.order_radio.set_value(self.app.defaults["tools_iso_order"])
  240. self.ui.passes_entry.set_value(self.app.defaults["tools_iso_passes"])
  241. self.ui.iso_overlap_entry.set_value(self.app.defaults["tools_iso_overlap"])
  242. self.ui.milling_type_radio.set_value(self.app.defaults["tools_iso_milling_type"])
  243. self.ui.combine_passes_cb.set_value(self.app.defaults["tools_iso_combine_passes"])
  244. self.ui.area_shape_radio.set_value(self.app.defaults["tools_iso_area_shape"])
  245. self.ui.poly_int_cb.set_value(self.app.defaults["tools_iso_poly_ints"])
  246. self.ui.forced_rest_iso_cb.set_value(self.app.defaults["tools_iso_force"])
  247. self.ui.cutz_entry.set_value(self.app.defaults["tools_iso_tool_cutz"])
  248. self.ui.tool_type_radio.set_value(self.app.defaults["tools_iso_tool_type"])
  249. self.ui.tipdia_entry.set_value(self.app.defaults["tools_iso_tool_vtipdia"])
  250. self.ui.tipangle_entry.set_value(self.app.defaults["tools_iso_tool_vtipangle"])
  251. self.ui.addtool_entry.set_value(self.app.defaults["tools_iso_newdia"])
  252. self.on_tool_type(val=self.ui.tool_type_radio.get_value())
  253. loaded_obj = self.app.collection.get_by_name(self.ui.object_combo.get_value())
  254. if loaded_obj:
  255. outname = loaded_obj.options['name']
  256. else:
  257. outname = ''
  258. # init the working variables
  259. self.default_data.clear()
  260. self.default_data = {
  261. "name": outname + '_iso',
  262. "plot": self.app.defaults["geometry_plot"],
  263. "cutz": float(self.app.defaults["tools_iso_tool_cutz"]),
  264. "vtipdia": float(self.app.defaults["tools_iso_tool_vtipdia"]),
  265. "vtipangle": float(self.app.defaults["tools_iso_tool_vtipangle"]),
  266. "travelz": self.app.defaults["geometry_travelz"],
  267. "feedrate": self.app.defaults["geometry_feedrate"],
  268. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  269. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  270. "dwell": self.app.defaults["geometry_dwell"],
  271. "dwelltime": self.app.defaults["geometry_dwelltime"],
  272. "multidepth": self.app.defaults["geometry_multidepth"],
  273. "ppname_g": self.app.defaults["geometry_ppname_g"],
  274. "depthperpass": self.app.defaults["geometry_depthperpass"],
  275. "extracut": self.app.defaults["geometry_extracut"],
  276. "extracut_length": self.app.defaults["geometry_extracut_length"],
  277. "toolchange": self.app.defaults["geometry_toolchange"],
  278. "toolchangez": self.app.defaults["geometry_toolchangez"],
  279. "endz": self.app.defaults["geometry_endz"],
  280. "endxy": self.app.defaults["geometry_endxy"],
  281. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  282. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  283. "startz": self.app.defaults["geometry_startz"],
  284. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  285. "area_shape": self.app.defaults["geometry_area_shape"],
  286. "area_strategy": self.app.defaults["geometry_area_strategy"],
  287. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  288. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  289. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  290. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  291. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  292. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  293. "tools_iso_rest": self.app.defaults["tools_iso_rest"],
  294. "tools_iso_combine_passes": self.app.defaults["tools_iso_combine_passes"],
  295. "tools_iso_isoexcept": self.app.defaults["tools_iso_isoexcept"],
  296. "tools_iso_selection": self.app.defaults["tools_iso_selection"],
  297. "tools_iso_poly_ints": self.app.defaults["tools_iso_poly_ints"],
  298. "tools_iso_force": self.app.defaults["tools_iso_force"],
  299. "tools_iso_area_shape": self.app.defaults["tools_iso_area_shape"]
  300. }
  301. try:
  302. dias = [float(self.app.defaults["tools_iso_tooldia"])]
  303. except (ValueError, TypeError):
  304. dias = [float(eval(dia)) for dia in self.app.defaults["tools_iso_tooldia"].split(",") if dia != '']
  305. if not dias:
  306. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> Isolation Tools.")
  307. return
  308. self.tooluid = 0
  309. self.iso_tools.clear()
  310. for tool_dia in dias:
  311. self.tooluid += 1
  312. self.iso_tools.update({
  313. int(self.tooluid): {
  314. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  315. 'offset': 'Path',
  316. 'offset_value': 0.0,
  317. 'type': 'Iso',
  318. 'tool_type': self.ui.tool_type_radio.get_value(),
  319. 'data': deepcopy(self.default_data),
  320. 'solid_geometry': []
  321. }
  322. })
  323. self.obj_name = ""
  324. self.grb_obj = None
  325. self.first_click = False
  326. self.cursor_pos = None
  327. self.mouse_is_dragging = False
  328. prog_plot = True if self.app.defaults["tools_iso_plotting"] == 'progressive' else False
  329. if prog_plot:
  330. self.temp_shapes.clear(update=True)
  331. self.sel_rect = []
  332. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  333. self.units = self.app.defaults['units'].upper()
  334. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  335. def rebuild_ui(self):
  336. # read the table tools uid
  337. current_uid_list = []
  338. for row in range(self.ui.tools_table.rowCount()):
  339. uid = int(self.ui.tools_table.item(row, 3).text())
  340. current_uid_list.append(uid)
  341. new_tools = {}
  342. new_uid = 1
  343. for current_uid in current_uid_list:
  344. new_tools[new_uid] = deepcopy(self.iso_tools[current_uid])
  345. new_uid += 1
  346. self.iso_tools = new_tools
  347. # the tools table changed therefore we need to rebuild it
  348. QtCore.QTimer.singleShot(20, self.build_ui)
  349. def build_ui(self):
  350. self.ui_disconnect()
  351. # updated units
  352. self.units = self.app.defaults['units'].upper()
  353. sorted_tools = []
  354. for k, v in self.iso_tools.items():
  355. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  356. order = self.ui.order_radio.get_value()
  357. if order == 'fwd':
  358. sorted_tools.sort(reverse=False)
  359. elif order == 'rev':
  360. sorted_tools.sort(reverse=True)
  361. else:
  362. pass
  363. n = len(sorted_tools)
  364. self.ui.tools_table.setRowCount(n)
  365. tool_id = 0
  366. for tool_sorted in sorted_tools:
  367. for tooluid_key, tooluid_value in self.iso_tools.items():
  368. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  369. tool_id += 1
  370. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  371. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  372. row_no = tool_id - 1
  373. self.ui.tools_table.setItem(row_no, 0, id_) # Tool name/id
  374. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  375. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  376. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  377. tool_type_item = FCComboBox()
  378. tool_type_item.addItems(self.tool_type_item_options)
  379. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  380. idx = tool_type_item.findText(tooluid_value['tool_type'])
  381. tool_type_item.setCurrentIndex(idx)
  382. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  383. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  384. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  385. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  386. # make the diameter column editable
  387. for row in range(tool_id):
  388. self.ui.tools_table.item(row, 1).setFlags(
  389. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  390. # all the tools are selected by default
  391. self.ui.tools_table.selectColumn(0)
  392. #
  393. self.ui.tools_table.resizeColumnsToContents()
  394. self.ui.tools_table.resizeRowsToContents()
  395. vertical_header = self.ui.tools_table.verticalHeader()
  396. vertical_header.hide()
  397. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  398. horizontal_header = self.ui.tools_table.horizontalHeader()
  399. horizontal_header.setMinimumSectionSize(10)
  400. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  401. horizontal_header.resizeSection(0, 20)
  402. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  403. # self.ui.tools_table.setSortingEnabled(True)
  404. # sort by tool diameter
  405. # self.ui.tools_table.sortItems(1)
  406. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  407. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  408. self.ui_connect()
  409. # set the text on tool_data_label after loading the object
  410. sel_rows = set()
  411. sel_items = self.ui.tools_table.selectedItems()
  412. for it in sel_items:
  413. sel_rows.add(it.row())
  414. if len(sel_rows) > 1:
  415. self.ui.tool_data_label.setText(
  416. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  417. )
  418. def ui_connect(self):
  419. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  420. # rows selected
  421. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  422. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  423. for row in range(self.ui.tools_table.rowCount()):
  424. try:
  425. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  426. except AttributeError:
  427. pass
  428. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type)
  429. for opt in self.form_fields:
  430. current_widget = self.form_fields[opt]
  431. if isinstance(current_widget, FCCheckBox):
  432. current_widget.stateChanged.connect(self.form_to_storage)
  433. if isinstance(current_widget, RadioSet):
  434. current_widget.activated_custom.connect(self.form_to_storage)
  435. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  436. current_widget.returnPressed.connect(self.form_to_storage)
  437. elif isinstance(current_widget, FCComboBox):
  438. current_widget.currentIndexChanged.connect(self.form_to_storage)
  439. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  440. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  441. def ui_disconnect(self):
  442. try:
  443. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  444. self.ui.tools_table.itemChanged.disconnect()
  445. except (TypeError, AttributeError):
  446. pass
  447. try:
  448. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  449. self.ui.tool_type_radio.activated_custom.disconnect()
  450. except (TypeError, AttributeError):
  451. pass
  452. for row in range(self.ui.tools_table.rowCount()):
  453. try:
  454. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  455. except (TypeError, AttributeError):
  456. pass
  457. for opt in self.form_fields:
  458. current_widget = self.form_fields[opt]
  459. if isinstance(current_widget, FCCheckBox):
  460. try:
  461. current_widget.stateChanged.disconnect(self.form_to_storage)
  462. except (TypeError, ValueError):
  463. pass
  464. if isinstance(current_widget, RadioSet):
  465. try:
  466. current_widget.activated_custom.disconnect(self.form_to_storage)
  467. except (TypeError, ValueError):
  468. pass
  469. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  470. try:
  471. current_widget.returnPressed.disconnect(self.form_to_storage)
  472. except (TypeError, ValueError):
  473. pass
  474. elif isinstance(current_widget, FCComboBox):
  475. try:
  476. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  477. except (TypeError, ValueError):
  478. pass
  479. try:
  480. self.ui.rest_cb.stateChanged.disconnect()
  481. except (TypeError, ValueError):
  482. pass
  483. try:
  484. self.ui.order_radio.activated_custom[str].disconnect()
  485. except (TypeError, ValueError):
  486. pass
  487. # rows selected
  488. try:
  489. self.ui.tools_table.clicked.disconnect()
  490. except (TypeError, AttributeError):
  491. pass
  492. try:
  493. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  494. except (TypeError, AttributeError):
  495. pass
  496. def on_toggle_all_rows(self):
  497. """
  498. will toggle the selection of all rows in Tools table
  499. :return:
  500. """
  501. sel_model = self.ui.tools_table.selectionModel()
  502. sel_indexes = sel_model.selectedIndexes()
  503. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  504. sel_rows = set()
  505. for idx in sel_indexes:
  506. sel_rows.add(idx.row())
  507. if len(sel_rows) == self.ui.tools_table.rowCount():
  508. self.ui.tools_table.clearSelection()
  509. else:
  510. self.ui.tools_table.selectAll()
  511. self.update_ui()
  512. def on_row_selection_change(self):
  513. self.update_ui()
  514. def update_ui(self):
  515. self.blockSignals(True)
  516. sel_rows = set()
  517. table_items = self.ui.tools_table.selectedItems()
  518. if table_items:
  519. for it in table_items:
  520. sel_rows.add(it.row())
  521. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  522. if not sel_rows or len(sel_rows) == 0:
  523. self.ui.generate_iso_button.setDisabled(True)
  524. self.ui.tool_data_label.setText(
  525. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  526. )
  527. self.blockSignals(False)
  528. return
  529. else:
  530. self.ui.generate_iso_button.setDisabled(False)
  531. for current_row in sel_rows:
  532. # populate the form with the data from the tool associated with the row parameter
  533. try:
  534. item = self.ui.tools_table.item(current_row, 3)
  535. if item is not None:
  536. tooluid = int(item.text())
  537. else:
  538. return
  539. except Exception as e:
  540. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  541. return
  542. # update the QLabel that shows for which Tool we have the parameters in the UI form
  543. if len(sel_rows) == 1:
  544. cr = current_row + 1
  545. self.ui.tool_data_label.setText(
  546. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), cr)
  547. )
  548. try:
  549. # set the form with data from the newly selected tool
  550. for tooluid_key, tooluid_value in list(self.iso_tools.items()):
  551. if int(tooluid_key) == tooluid:
  552. for key, value in tooluid_value.items():
  553. if key == 'data':
  554. self.storage_to_form(tooluid_value['data'])
  555. except Exception as e:
  556. log.debug("ToolIsolation ---> update_ui() " + str(e))
  557. else:
  558. self.ui.tool_data_label.setText(
  559. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  560. )
  561. self.blockSignals(False)
  562. def storage_to_form(self, dict_storage):
  563. for form_key in self.form_fields:
  564. for storage_key in dict_storage:
  565. if form_key == storage_key:
  566. try:
  567. self.form_fields[form_key].set_value(dict_storage[form_key])
  568. except Exception as e:
  569. log.debug("ToolIsolation.storage_to_form() --> %s" % str(e))
  570. pass
  571. def form_to_storage(self):
  572. if self.ui.tools_table.rowCount() == 0:
  573. # there is no tool in tool table so we can't save the GUI elements values to storage
  574. return
  575. self.blockSignals(True)
  576. widget_changed = self.sender()
  577. wdg_objname = widget_changed.objectName()
  578. option_changed = self.name2option[wdg_objname]
  579. # row = self.ui.tools_table.currentRow()
  580. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  581. for row in rows:
  582. if row < 0:
  583. row = 0
  584. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  585. for tooluid_key, tooluid_val in self.iso_tools.items():
  586. if int(tooluid_key) == tooluid_item:
  587. new_option_value = self.form_fields[option_changed].get_value()
  588. if option_changed in tooluid_val:
  589. tooluid_val[option_changed] = new_option_value
  590. if option_changed in tooluid_val['data']:
  591. tooluid_val['data'][option_changed] = new_option_value
  592. self.blockSignals(False)
  593. def on_apply_param_to_all_clicked(self):
  594. if self.ui.tools_table.rowCount() == 0:
  595. # there is no tool in tool table so we can't save the GUI elements values to storage
  596. log.debug("ToolIsolation.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  597. return
  598. self.blockSignals(True)
  599. row = self.ui.tools_table.currentRow()
  600. if row < 0:
  601. row = 0
  602. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  603. temp_tool_data = {}
  604. for tooluid_key, tooluid_val in self.iso_tools.items():
  605. if int(tooluid_key) == tooluid_item:
  606. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  607. # the current row in the tool table
  608. temp_tool_data = tooluid_val['data']
  609. break
  610. for tooluid_key, tooluid_val in self.iso_tools.items():
  611. tooluid_val['data'] = deepcopy(temp_tool_data)
  612. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  613. self.blockSignals(False)
  614. def on_add_tool_by_key(self):
  615. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  616. text='%s:' % _('Enter a Tool Diameter'),
  617. min=0.0001, max=9999.9999, decimals=self.decimals)
  618. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  619. val, ok = tool_add_popup.get_value()
  620. if ok:
  621. if float(val) == 0:
  622. self.app.inform.emit('[WARNING_NOTCL] %s' %
  623. _("Please enter a tool diameter with non-zero value, in Float format."))
  624. return
  625. self.on_tool_add(dia=float(val))
  626. else:
  627. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  628. def on_tooldia_updated(self):
  629. if self.ui.tool_type_radio.get_value() == 'C1':
  630. self.old_tool_dia = self.ui.addtool_entry.get_value()
  631. def on_reference_combo_changed(self):
  632. obj_type = self.ui.reference_combo_type.currentIndex()
  633. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  634. self.ui.reference_combo.setCurrentIndex(0)
  635. self.ui.reference_combo.obj_type = {
  636. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  637. }[self.ui.reference_combo_type.get_value()]
  638. def on_toggle_reference(self):
  639. val = self.ui.select_combo.get_value()
  640. if val == _("All"):
  641. self.ui.reference_combo.hide()
  642. self.ui.reference_combo_label.hide()
  643. self.ui.reference_combo_type.hide()
  644. self.ui.reference_combo_type_label.hide()
  645. self.ui.area_shape_label.hide()
  646. self.ui.area_shape_radio.hide()
  647. self.ui.poly_int_cb.hide()
  648. # disable rest-machining for area painting
  649. self.ui.rest_cb.setDisabled(False)
  650. elif val == _("Area Selection"):
  651. self.ui.reference_combo.hide()
  652. self.ui.reference_combo_label.hide()
  653. self.ui.reference_combo_type.hide()
  654. self.ui.reference_combo_type_label.hide()
  655. self.ui.area_shape_label.show()
  656. self.ui.area_shape_radio.show()
  657. self.ui.poly_int_cb.hide()
  658. # disable rest-machining for area isolation
  659. self.ui.rest_cb.set_value(False)
  660. self.ui.rest_cb.setDisabled(True)
  661. elif val == _("Polygon Selection"):
  662. self.ui.reference_combo.hide()
  663. self.ui.reference_combo_label.hide()
  664. self.ui.reference_combo_type.hide()
  665. self.ui.reference_combo_type_label.hide()
  666. self.ui.area_shape_label.hide()
  667. self.ui.area_shape_radio.hide()
  668. self.ui.poly_int_cb.show()
  669. else:
  670. self.ui.reference_combo.show()
  671. self.ui.reference_combo_label.show()
  672. self.ui.reference_combo_type.show()
  673. self.ui.reference_combo_type_label.show()
  674. self.ui.area_shape_label.hide()
  675. self.ui.area_shape_radio.hide()
  676. self.ui.poly_int_cb.hide()
  677. # disable rest-machining for area painting
  678. self.ui.rest_cb.setDisabled(False)
  679. def on_order_changed(self, order):
  680. if order != 'no':
  681. self.build_ui()
  682. def on_rest_machining_check(self, state):
  683. if state:
  684. self.ui.order_radio.set_value('rev')
  685. self.ui.order_label.setDisabled(True)
  686. self.ui.order_radio.setDisabled(True)
  687. self.old_combine_state = self.ui.combine_passes_cb.get_value()
  688. self.ui.combine_passes_cb.set_value(True)
  689. self.ui.combine_passes_cb.setDisabled(True)
  690. self.ui.forced_rest_iso_cb.setDisabled(False)
  691. else:
  692. self.ui.order_label.setDisabled(False)
  693. self.ui.order_radio.setDisabled(False)
  694. self.ui.combine_passes_cb.set_value(self.old_combine_state)
  695. self.ui.combine_passes_cb.setDisabled(False)
  696. self.ui.forced_rest_iso_cb.setDisabled(True)
  697. def on_tooltable_cellwidget_change(self):
  698. cw = self.sender()
  699. assert isinstance(cw, QtWidgets.QComboBox), \
  700. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  701. cw_index = self.ui.tools_table.indexAt(cw.pos())
  702. cw_row = cw_index.row()
  703. cw_col = cw_index.column()
  704. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  705. # if the sender is in the column with index 2 then we update the tool_type key
  706. if cw_col == 2:
  707. tt = cw.currentText()
  708. typ = 'Iso' if tt == 'V' else "Rough"
  709. self.iso_tools[current_uid].update({
  710. 'type': typ,
  711. 'tool_type': tt,
  712. })
  713. def on_tool_type(self, val):
  714. if val == 'V':
  715. self.ui.addtool_entry_lbl.setDisabled(True)
  716. self.ui.addtool_entry.setDisabled(True)
  717. self.ui.tipdialabel.show()
  718. self.ui.tipdia_entry.show()
  719. self.ui.tipanglelabel.show()
  720. self.ui.tipangle_entry.show()
  721. self.on_calculate_tooldia()
  722. else:
  723. self.ui.addtool_entry_lbl.setDisabled(False)
  724. self.ui.addtool_entry.setDisabled(False)
  725. self.ui.tipdialabel.hide()
  726. self.ui.tipdia_entry.hide()
  727. self.ui.tipanglelabel.hide()
  728. self.ui.tipangle_entry.hide()
  729. self.ui.addtool_entry.set_value(self.old_tool_dia)
  730. def on_calculate_tooldia(self):
  731. if self.ui.tool_type_radio.get_value() == 'V':
  732. tip_dia = float(self.ui.tipdia_entry.get_value())
  733. tip_angle = float(self.ui.tipangle_entry.get_value()) / 2.0
  734. cut_z = float(self.ui.cutz_entry.get_value())
  735. cut_z = -cut_z if cut_z < 0 else cut_z
  736. # calculated tool diameter so the cut_z parameter is obeyed
  737. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  738. # update the default_data so it is used in the iso_tools dict
  739. self.default_data.update({
  740. "vtipdia": tip_dia,
  741. "vtipangle": (tip_angle * 2),
  742. })
  743. self.ui.addtool_entry.set_value(tool_dia)
  744. return tool_dia
  745. else:
  746. return float(self.ui.addtool_entry.get_value())
  747. def on_tool_add(self, dia=None, muted=None):
  748. self.blockSignals(True)
  749. self.units = self.app.defaults['units'].upper()
  750. if dia:
  751. tool_dia = dia
  752. else:
  753. tool_dia = self.on_calculate_tooldia()
  754. if tool_dia is None:
  755. self.build_ui()
  756. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  757. return
  758. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  759. if tool_dia == 0:
  760. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  761. "in Float format."))
  762. return
  763. # construct a list of all 'tooluid' in the self.tools
  764. tool_uid_list = []
  765. for tooluid_key in self.iso_tools:
  766. tool_uid_item = int(tooluid_key)
  767. tool_uid_list.append(tool_uid_item)
  768. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  769. if not tool_uid_list:
  770. max_uid = 0
  771. else:
  772. max_uid = max(tool_uid_list)
  773. self.tooluid = int(max_uid + 1)
  774. tool_dias = []
  775. for k, v in self.iso_tools.items():
  776. for tool_v in v.keys():
  777. if tool_v == 'tooldia':
  778. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  779. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  780. if muted is None:
  781. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  782. # self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  783. self.blockSignals(False)
  784. return
  785. else:
  786. if muted is None:
  787. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  788. self.iso_tools.update({
  789. int(self.tooluid): {
  790. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  791. 'offset': 'Path',
  792. 'offset_value': 0.0,
  793. 'type': ' Iso',
  794. 'tool_type': self.ui.tool_type_radio.get_value(),
  795. 'data': deepcopy(self.default_data),
  796. 'solid_geometry': []
  797. }
  798. })
  799. self.blockSignals(False)
  800. self.build_ui()
  801. # select the tool just added
  802. for row in range(self.ui.tools_table.rowCount()):
  803. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  804. self.ui.tools_table.selectRow(row)
  805. break
  806. def on_tool_edit(self, item):
  807. self.blockSignals(True)
  808. edited_row = item.row()
  809. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  810. tool_dias = []
  811. try:
  812. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  813. except ValueError:
  814. # try to convert comma to decimal point. if it's still not working error message and return
  815. try:
  816. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  817. except ValueError:
  818. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  819. self.blockSignals(False)
  820. return
  821. for v in self.iso_tools.values():
  822. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  823. # identify the tool that was edited and get it's tooluid
  824. if new_tool_dia not in tool_dias:
  825. self.iso_tools[editeduid]['tooldia'] = deepcopy(float('%.*f' % (self.decimals, new_tool_dia)))
  826. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  827. self.blockSignals(False)
  828. self.build_ui()
  829. return
  830. # identify the old tool_dia and restore the text in tool table
  831. for k, v in self.iso_tools.items():
  832. if k == editeduid:
  833. old_tool_dia = v['tooldia']
  834. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  835. restore_dia_item.setText(str(old_tool_dia))
  836. break
  837. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  838. self.blockSignals(False)
  839. self.build_ui()
  840. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  841. """
  842. Will delete a tool in the tool table
  843. :param rows_to_delete: which rows to delete; can be a list
  844. :param all_tools: delete all tools in the tool table
  845. :return:
  846. """
  847. self.blockSignals(True)
  848. deleted_tools_list = []
  849. if all_tools:
  850. self.iso_tools.clear()
  851. self.blockSignals(False)
  852. self.build_ui()
  853. return
  854. if rows_to_delete:
  855. try:
  856. for row in rows_to_delete:
  857. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  858. deleted_tools_list.append(tooluid_del)
  859. except TypeError:
  860. tooluid_del = int(self.ui.tools_table.item(rows_to_delete, 3).text())
  861. deleted_tools_list.append(tooluid_del)
  862. for t in deleted_tools_list:
  863. self.iso_tools.pop(t, None)
  864. self.blockSignals(False)
  865. self.build_ui()
  866. return
  867. try:
  868. if self.ui.tools_table.selectedItems():
  869. for row_sel in self.ui.tools_table.selectedItems():
  870. row = row_sel.row()
  871. if row < 0:
  872. continue
  873. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  874. deleted_tools_list.append(tooluid_del)
  875. for t in deleted_tools_list:
  876. self.iso_tools.pop(t, None)
  877. except AttributeError:
  878. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  879. self.blockSignals(False)
  880. return
  881. except Exception as e:
  882. log.debug(str(e))
  883. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  884. self.blockSignals(False)
  885. self.build_ui()
  886. def on_generate_buffer(self):
  887. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  888. self.obj_name = self.ui.object_combo.currentText()
  889. # Get source object.
  890. try:
  891. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  892. except Exception as e:
  893. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  894. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  895. if self.grb_obj is None:
  896. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  897. return
  898. def buffer_task(app_obj):
  899. with app_obj.proc_container.new('%s...' % _("Buffering")):
  900. if isinstance(self.grb_obj.solid_geometry, list):
  901. self.grb_obj.solid_geometry = MultiPolygon(self.grb_obj.solid_geometry)
  902. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(0.0000001)
  903. self.grb_obj.solid_geometry = self.grb_obj.solid_geometry.buffer(-0.0000001)
  904. app_obj.inform.emit('[success] %s.' % _("Done"))
  905. self.grb_obj.plot_single_object.emit()
  906. self.app.worker_task.emit({'fcn': buffer_task, 'params': [self.app]})
  907. def on_iso_button_click(self):
  908. self.obj_name = self.ui.object_combo.currentText()
  909. # Get source object.
  910. try:
  911. self.grb_obj = self.app.collection.get_by_name(self.obj_name)
  912. except Exception as e:
  913. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  914. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  915. if self.grb_obj is None:
  916. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  917. return
  918. def worker_task(iso_obj):
  919. with self.app.proc_container.new(_("Isolating...")):
  920. self.isolate_handler(iso_obj)
  921. self.app.worker_task.emit({'fcn': worker_task, 'params': [self.grb_obj]})
  922. def follow_geo(self, followed_obj, outname):
  923. """
  924. Creates a geometry object "following" the gerber paths.
  925. :param followed_obj: Gerber object for which to generate the follow geometry
  926. :type followed_obj: AppObjects.FlatCAMGerber.GerberObject
  927. :param outname: Nme of the resulting Geometry object
  928. :type outname: str
  929. :return: None
  930. """
  931. def follow_init(follow_obj, app_obj):
  932. # Propagate options
  933. follow_obj.options["cnctooldia"] = str(tooldia)
  934. follow_obj.solid_geometry = self.grb_obj.follow_geometry
  935. app_obj.inform.emit('[success] %s.' % _("Following geometry was generated"))
  936. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  937. followed_obj.ui.plot_cb.set_value(False)
  938. follow_name = outname
  939. for tool in self.iso_tools:
  940. tooldia = self.iso_tools[tool]['tooldia']
  941. new_name = "%s_%.*f" % (follow_name, self.decimals, tooldia)
  942. follow_state = self.iso_tools[tool]['data']['tools_iso_follow']
  943. if follow_state:
  944. ret = self.app.app_obj.new_object("geometry", new_name, follow_init)
  945. if ret == 'fail':
  946. self.app.inform.emit("[ERROR_NOTCL] %s: %.*f" % (
  947. _("Failed to create Follow Geometry with tool diameter"), self.decimals, tooldia))
  948. else:
  949. self.app.inform.emit("[success] %s: %.*f" % (
  950. _("Follow Geometry was created with tool diameter"), self.decimals, tooldia))
  951. def isolate_handler(self, isolated_obj):
  952. """
  953. Creates a geometry object with paths around the gerber features.
  954. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  955. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  956. :return: None
  957. """
  958. selection = self.ui.select_combo.get_value()
  959. if selection == _("All"):
  960. self.isolate(isolated_obj=isolated_obj)
  961. elif selection == _("Area Selection"):
  962. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  963. if self.app.is_legacy is False:
  964. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  965. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  966. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  967. else:
  968. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  969. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  970. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  971. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  972. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  973. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  974. # disconnect flags
  975. self.area_sel_disconnect_flag = True
  976. elif selection == _("Polygon Selection"):
  977. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  978. if self.app.ui.grid_snap_btn.isChecked():
  979. self.grid_status_memory = True
  980. self.app.ui.grid_snap_btn.trigger()
  981. else:
  982. self.grid_status_memory = False
  983. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  984. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_poly_mouse_click_release)
  985. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  986. if self.app.is_legacy is False:
  987. self.app.plotcanvas.graph_event_disconnect('mouse_release',
  988. self.app.on_mouse_click_release_over_plot)
  989. else:
  990. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  991. # disconnect flags
  992. self.poly_sel_disconnect_flag = True
  993. elif selection == _("Reference Object"):
  994. ref_obj = self.app.collection.get_by_name(self.ui.reference_combo.get_value())
  995. ref_geo = cascaded_union(ref_obj.solid_geometry)
  996. use_geo = cascaded_union(isolated_obj.solid_geometry).difference(ref_geo)
  997. self.isolate(isolated_obj=isolated_obj, geometry=use_geo)
  998. def isolate(self, isolated_obj, geometry=None, limited_area=None, negative_dia=None, plot=True):
  999. """
  1000. Creates an isolation routing geometry object in the project.
  1001. :param isolated_obj: Gerber object for which to generate the isolating routing geometry
  1002. :type isolated_obj: AppObjects.FlatCAMGerber.GerberObject
  1003. :param geometry: specific geometry to isolate
  1004. :type geometry: List of Shapely polygon
  1005. :param limited_area: if not None isolate only this area
  1006. :type limited_area: Shapely Polygon or a list of them
  1007. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  1008. :type negative_dia: bool
  1009. :param plot: if to plot the resulting geometry object
  1010. :type plot: bool
  1011. :return: None
  1012. """
  1013. combine = self.ui.combine_passes_cb.get_value()
  1014. tools_storage = self.iso_tools
  1015. # update the Common Parameters valuse in the self.iso_tools
  1016. for tool_iso in self.iso_tools:
  1017. for key in self.iso_tools[tool_iso]:
  1018. if key == 'data':
  1019. self.iso_tools[tool_iso][key]["tools_iso_rest"] = self.ui.rest_cb.get_value()
  1020. self.iso_tools[tool_iso][key]["tools_iso_combine_passes"] = combine
  1021. self.iso_tools[tool_iso][key]["tools_iso_isoexcept"] = self.ui.except_cb.get_value()
  1022. self.iso_tools[tool_iso][key]["tools_iso_selection"] = self.ui.select_combo.get_value()
  1023. self.iso_tools[tool_iso][key]["tools_iso_area_shape"] = self.ui.area_shape_radio.get_value()
  1024. if combine:
  1025. if self.ui.rest_cb.get_value():
  1026. self.combined_rest(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1027. lim_area=limited_area, negative_dia=negative_dia, plot=plot)
  1028. else:
  1029. self.combined_normal(iso_obj=isolated_obj, iso2geo=geometry, tools_storage=tools_storage,
  1030. lim_area=limited_area, negative_dia=negative_dia, plot=plot)
  1031. else:
  1032. prog_plot = self.app.defaults["tools_iso_plotting"]
  1033. for tool in tools_storage:
  1034. tool_data = tools_storage[tool]['data']
  1035. to_follow = tool_data['tools_iso_follow']
  1036. work_geo = geometry
  1037. if work_geo is None:
  1038. work_geo = isolated_obj.follow_geometry if to_follow else isolated_obj.solid_geometry
  1039. iso_t = {
  1040. 'ext': 0,
  1041. 'int': 1,
  1042. 'full': 2
  1043. }[tool_data['tools_iso_isotype']]
  1044. passes = tool_data['tools_iso_passes']
  1045. overlap = tool_data['tools_iso_overlap']
  1046. overlap /= 100.0
  1047. milling_type = tool_data['tools_iso_milling_type']
  1048. iso_except = self.ui.except_cb.get_value()
  1049. for i in range(passes):
  1050. tool_dia = tools_storage[tool]['tooldia']
  1051. tool_type = tools_storage[tool]['tool_type']
  1052. iso_offset = tool_dia * ((2 * i + 1) / 2.0000001) - (i * overlap * tool_dia)
  1053. if negative_dia:
  1054. iso_offset = -iso_offset
  1055. outname = "%s_%.*f" % (isolated_obj.options["name"], self.decimals, float(tool_dia))
  1056. if passes > 1:
  1057. iso_name = outname + "_iso" + str(i + 1)
  1058. if iso_t == 0:
  1059. iso_name = outname + "_ext_iso" + str(i + 1)
  1060. elif iso_t == 1:
  1061. iso_name = outname + "_int_iso" + str(i + 1)
  1062. else:
  1063. iso_name = outname + "_iso"
  1064. if iso_t == 0:
  1065. iso_name = outname + "_ext_iso"
  1066. elif iso_t == 1:
  1067. iso_name = outname + "_int_iso"
  1068. # if milling type is climb then the move is counter-clockwise around features
  1069. mill_dir = 1 if milling_type == 'cl' else 0
  1070. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1071. follow=to_follow, nr_passes=i, prog_plot=prog_plot)
  1072. if iso_geo == 'fail':
  1073. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1074. continue
  1075. # ############################################################
  1076. # ########## AREA SUBTRACTION ################################
  1077. # ############################################################
  1078. if iso_except:
  1079. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1080. iso_geo = self.area_subtraction(iso_geo)
  1081. if limited_area:
  1082. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1083. iso_geo = self.area_intersection(iso_geo, intersection_geo=limited_area)
  1084. # make sure that no empty geometry element is in the solid_geometry
  1085. new_solid_geo = [geo for geo in iso_geo if not geo.is_empty]
  1086. tool_data.update({
  1087. "name": iso_name,
  1088. })
  1089. def iso_init(geo_obj, fc_obj):
  1090. # Propagate options
  1091. geo_obj.options["cnctooldia"] = str(tool_dia)
  1092. geo_obj.solid_geometry = deepcopy(new_solid_geo)
  1093. # ############################################################
  1094. # ########## AREA SUBTRACTION ################################
  1095. # ############################################################
  1096. if self.ui.except_cb.get_value():
  1097. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1098. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1099. geo_obj.tools = {}
  1100. geo_obj.tools['1'] = {}
  1101. geo_obj.tools.update({
  1102. '1': {
  1103. 'tooldia': float(tool_dia),
  1104. 'offset': 'Path',
  1105. 'offset_value': 0.0,
  1106. 'type': _('Rough'),
  1107. 'tool_type': tool_type,
  1108. 'data': tool_data,
  1109. 'solid_geometry': geo_obj.solid_geometry
  1110. }
  1111. })
  1112. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1113. # or just looking in the lists (they are one level depth) and if any is not empty
  1114. # proceed with object creation, if there are empty and the number of them is the length
  1115. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1116. empty_cnt = 0
  1117. if not isinstance(geo_obj.solid_geometry, list):
  1118. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1119. for g in geo_obj.solid_geometry:
  1120. if g:
  1121. break
  1122. else:
  1123. empty_cnt += 1
  1124. if empty_cnt == len(geo_obj.solid_geometry):
  1125. fc_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (
  1126. _("Empty Geometry in"), geo_obj.options["name"]))
  1127. return 'fail'
  1128. else:
  1129. fc_obj.inform.emit('[success] %s: %s' %
  1130. (_("Isolation geometry created"), geo_obj.options["name"]))
  1131. geo_obj.multigeo = False
  1132. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1133. # clean the progressive plotted shapes if it was used
  1134. if prog_plot == 'progressive':
  1135. self.temp_shapes.clear(update=True)
  1136. # Switch notebook to Selected page
  1137. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1138. def combined_rest(self, iso_obj, iso2geo, tools_storage, lim_area, negative_dia=None, plot=True):
  1139. """
  1140. Isolate the provided Gerber object using "rest machining" strategy
  1141. :param iso_obj: the isolated Gerber object
  1142. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1143. :param iso2geo: specific geometry to isolate
  1144. :type iso2geo: list of Shapely Polygon
  1145. :param tools_storage: a dictionary that holds the tools and geometry
  1146. :type tools_storage: dict
  1147. :param lim_area: if not None restrict isolation to this area
  1148. :type lim_area: Shapely Polygon or a list of them
  1149. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  1150. :type negative_dia: bool
  1151. :param plot: if to plot the resulting geometry object
  1152. :type plot: bool
  1153. :return: Isolated solid geometry
  1154. :rtype:
  1155. """
  1156. log.debug("ToolIsolation.combine_rest()")
  1157. total_solid_geometry = []
  1158. iso_name = iso_obj.options["name"] + '_iso_rest'
  1159. work_geo = iso_obj.solid_geometry if iso2geo is None else iso2geo
  1160. sorted_tools = []
  1161. for k, v in self.iso_tools.items():
  1162. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  1163. order = self.ui.order_radio.get_value()
  1164. if order == 'fwd':
  1165. sorted_tools.sort(reverse=False)
  1166. elif order == 'rev':
  1167. sorted_tools.sort(reverse=True)
  1168. else:
  1169. pass
  1170. # decide to use "progressive" or "normal" plotting
  1171. prog_plot = self.app.defaults["tools_iso_plotting"]
  1172. for sorted_tool in sorted_tools:
  1173. for tool in tools_storage:
  1174. if float('%.*f' % (self.decimals, tools_storage[tool]['tooldia'])) == sorted_tool:
  1175. tool_dia = tools_storage[tool]['tooldia']
  1176. tool_type = tools_storage[tool]['tool_type']
  1177. tool_data = tools_storage[tool]['data']
  1178. passes = tool_data['tools_iso_passes']
  1179. overlap = tool_data['tools_iso_overlap']
  1180. overlap /= 100.0
  1181. milling_type = tool_data['tools_iso_milling_type']
  1182. # if milling type is climb then the move is counter-clockwise around features
  1183. mill_dir = True if milling_type == 'cl' else False
  1184. iso_t = {
  1185. 'ext': 0,
  1186. 'int': 1,
  1187. 'full': 2
  1188. }[tool_data['tools_iso_isotype']]
  1189. forced_rest = self.ui.forced_rest_iso_cb.get_value()
  1190. iso_except = self.ui.except_cb.get_value()
  1191. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1192. internal_name = outname + "_iso"
  1193. if iso_t == 0:
  1194. internal_name = outname + "_ext_iso"
  1195. elif iso_t == 1:
  1196. internal_name = outname + "_int_iso"
  1197. tool_data.update({
  1198. "name": internal_name,
  1199. })
  1200. solid_geo, work_geo = self.generate_rest_geometry(geometry=work_geo, tooldia=tool_dia,
  1201. passes=passes, overlap=overlap, invert=mill_dir,
  1202. env_iso_type=iso_t, negative_dia=negative_dia,
  1203. forced_rest=forced_rest,
  1204. prog_plot=prog_plot,
  1205. prog_plot_handler=self.plot_temp_shapes)
  1206. # ############################################################
  1207. # ########## AREA SUBTRACTION ################################
  1208. # ############################################################
  1209. if iso_except:
  1210. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1211. solid_geo = self.area_subtraction(solid_geo)
  1212. if lim_area:
  1213. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1214. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1215. # make sure that no empty geometry element is in the solid_geometry
  1216. new_solid_geo = [geo for geo in solid_geo if not geo.is_empty]
  1217. tools_storage.update({
  1218. tool: {
  1219. 'tooldia': float(tool_dia),
  1220. 'offset': 'Path',
  1221. 'offset_value': 0.0,
  1222. 'type': _('Rough'),
  1223. 'tool_type': tool_type,
  1224. 'data': tool_data,
  1225. 'solid_geometry': deepcopy(new_solid_geo)
  1226. }
  1227. })
  1228. total_solid_geometry += new_solid_geo
  1229. # if the geometry is all isolated
  1230. if not work_geo:
  1231. break
  1232. # clean the progressive plotted shapes if it was used
  1233. if self.app.defaults["tools_iso_plotting"] == 'progressive':
  1234. self.temp_shapes.clear(update=True)
  1235. def iso_init(geo_obj, app_obj):
  1236. geo_obj.options["cnctooldia"] = str(tool_dia)
  1237. geo_obj.tools = dict(tools_storage)
  1238. geo_obj.solid_geometry = total_solid_geometry
  1239. # even if combine is checked, one pass is still single-geo
  1240. # remove the tools that have no geometry
  1241. for geo_tool in list(geo_obj.tools.keys()):
  1242. if not geo_obj.tools[geo_tool]['solid_geometry']:
  1243. geo_obj.tools.pop(geo_tool, None)
  1244. if len(tools_storage) > 1:
  1245. geo_obj.multigeo = True
  1246. else:
  1247. for ky in tools_storage.keys():
  1248. passes_no = float(tools_storage[ky]['data']['tools_iso_passes'])
  1249. geo_obj.multigeo = True if passes_no > 1 else False
  1250. break
  1251. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1252. # or just looking in the lists (they are one level depth) and if any is not empty
  1253. # proceed with object creation, if there are empty and the number of them is the length
  1254. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1255. empty_cnt = 0
  1256. if not isinstance(geo_obj.solid_geometry, list) and \
  1257. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1258. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1259. for g in geo_obj.solid_geometry:
  1260. if g:
  1261. break
  1262. else:
  1263. empty_cnt += 1
  1264. if empty_cnt == len(geo_obj.solid_geometry):
  1265. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1266. return 'fail'
  1267. else:
  1268. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1269. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1270. # the tools are finished but the isolation is not finished therefore it failed
  1271. if work_geo:
  1272. self.app.inform.emit("[WARNING] %s" % _("Partial failure. The geometry was processed with all tools.\n"
  1273. "But there are still not-isolated geometry elements. "
  1274. "Try to include a tool with smaller diameter."))
  1275. msg = _("The following are coordinates for the copper features that could not be isolated:")
  1276. self.app.inform_shell.emit(msg)
  1277. msg = ''
  1278. for geo in work_geo:
  1279. pt = geo.representative_point()
  1280. coords = '(%s, %s), ' % (str(pt.x), str(pt.y))
  1281. msg += coords
  1282. self.app.inform_shell.emit(msg=msg)
  1283. def combined_normal(self, iso_obj, iso2geo, tools_storage, lim_area, negative_dia=None, plot=True):
  1284. """
  1285. :param iso_obj: the isolated Gerber object
  1286. :type iso_obj: AppObjects.FlatCAMGerber.GerberObject
  1287. :param iso2geo: specific geometry to isolate
  1288. :type iso2geo: list of Shapely Polygon
  1289. :param tools_storage: a dictionary that holds the tools and geometry
  1290. :type tools_storage: dict
  1291. :param lim_area: if not None restrict isolation to this area
  1292. :type lim_area: Shapely Polygon or a list of them
  1293. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  1294. :type negative_dia: bool
  1295. :param plot: if to plot the resulting geometry object
  1296. :type plot: bool
  1297. :return: Isolated solid geometry
  1298. :rtype:
  1299. """
  1300. log.debug("ToolIsolation.combined_normal()")
  1301. total_solid_geometry = []
  1302. iso_name = iso_obj.options["name"] + '_iso_combined'
  1303. geometry = iso2geo
  1304. prog_plot = self.app.defaults["tools_iso_plotting"]
  1305. for tool in tools_storage:
  1306. tool_dia = tools_storage[tool]['tooldia']
  1307. tool_type = tools_storage[tool]['tool_type']
  1308. tool_data = tools_storage[tool]['data']
  1309. to_follow = tool_data['tools_iso_follow']
  1310. # TODO what to do when the iso2geo param is not None but the Follow cb is checked
  1311. # for the case when limited area is used .... the follow geo should be clipped too
  1312. work_geo = geometry
  1313. if work_geo is None:
  1314. work_geo = iso_obj.follow_geometry if to_follow else iso_obj.solid_geometry
  1315. iso_t = {
  1316. 'ext': 0,
  1317. 'int': 1,
  1318. 'full': 2
  1319. }[tool_data['tools_iso_isotype']]
  1320. passes = tool_data['tools_iso_passes']
  1321. overlap = tool_data['tools_iso_overlap']
  1322. overlap /= 100.0
  1323. milling_type = tool_data['tools_iso_milling_type']
  1324. iso_except = self.ui.except_cb.get_value()
  1325. outname = "%s_%.*f" % (iso_obj.options["name"], self.decimals, float(tool_dia))
  1326. internal_name = outname + "_iso"
  1327. if iso_t == 0:
  1328. internal_name = outname + "_ext_iso"
  1329. elif iso_t == 1:
  1330. internal_name = outname + "_int_iso"
  1331. tool_data.update({
  1332. "name": internal_name,
  1333. })
  1334. solid_geo = []
  1335. for nr_pass in range(passes):
  1336. iso_offset = tool_dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * tool_dia)
  1337. if negative_dia:
  1338. iso_offset = -iso_offset
  1339. # if milling type is climb then the move is counter-clockwise around features
  1340. mill_dir = 1 if milling_type == 'cl' else 0
  1341. iso_geo = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1342. follow=to_follow, nr_passes=nr_pass, prog_plot=prog_plot)
  1343. if iso_geo == 'fail':
  1344. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1345. continue
  1346. try:
  1347. for geo in iso_geo:
  1348. solid_geo.append(geo)
  1349. except TypeError:
  1350. solid_geo.append(iso_geo)
  1351. # ############################################################
  1352. # ########## AREA SUBTRACTION ################################
  1353. # ############################################################
  1354. if iso_except:
  1355. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1356. solid_geo = self.area_subtraction(solid_geo)
  1357. if lim_area:
  1358. self.app.proc_container.update_view_text(' %s' % _("Intersecting Geo"))
  1359. solid_geo = self.area_intersection(solid_geo, intersection_geo=lim_area)
  1360. # make sure that no empty geometry element is in the solid_geometry
  1361. new_solid_geo = [geo for geo in solid_geo if not geo.is_empty]
  1362. tools_storage.update({
  1363. tool: {
  1364. 'tooldia': float(tool_dia),
  1365. 'offset': 'Path',
  1366. 'offset_value': 0.0,
  1367. 'type': _('Rough'),
  1368. 'tool_type': tool_type,
  1369. 'data': tool_data,
  1370. 'solid_geometry': deepcopy(new_solid_geo)
  1371. }
  1372. })
  1373. total_solid_geometry += new_solid_geo
  1374. # clean the progressive plotted shapes if it was used
  1375. if prog_plot == 'progressive':
  1376. self.temp_shapes.clear(update=True)
  1377. def iso_init(geo_obj, app_obj):
  1378. geo_obj.options["cnctooldia"] = str(tool_dia)
  1379. geo_obj.tools = dict(tools_storage)
  1380. geo_obj.solid_geometry = total_solid_geometry
  1381. # even if combine is checked, one pass is still single-geo
  1382. if len(tools_storage) > 1:
  1383. geo_obj.multigeo = True
  1384. else:
  1385. if to_follow:
  1386. geo_obj.multigeo = False
  1387. else:
  1388. passes_no = 1
  1389. for ky in tools_storage.keys():
  1390. passes_no = float(tools_storage[ky]['data']['tools_iso_passes'])
  1391. geo_obj.multigeo = True if passes_no > 1 else False
  1392. break
  1393. geo_obj.multigeo = True if passes_no > 1 else False
  1394. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1395. # or just looking in the lists (they are one level depth) and if any is not empty
  1396. # proceed with object creation, if there are empty and the number of them is the length
  1397. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1398. empty_cnt = 0
  1399. if not isinstance(geo_obj.solid_geometry, list) and \
  1400. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1401. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1402. for g in geo_obj.solid_geometry:
  1403. if g:
  1404. break
  1405. else:
  1406. empty_cnt += 1
  1407. if empty_cnt == len(geo_obj.solid_geometry):
  1408. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Empty Geometry in"), geo_obj.options["name"]))
  1409. return 'fail'
  1410. else:
  1411. app_obj.inform.emit('[success] %s: %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1412. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  1413. def area_subtraction(self, geo, subtraction_geo=None):
  1414. """
  1415. Subtracts the subtraction_geo (if present else self.solid_geometry) from the geo
  1416. :param geo: target geometry from which to subtract
  1417. :param subtraction_geo: geometry that acts as subtraction geo
  1418. :return:
  1419. """
  1420. new_geometry = []
  1421. target_geo = geo
  1422. if subtraction_geo:
  1423. sub_union = cascaded_union(subtraction_geo)
  1424. else:
  1425. name = self.ui.exc_obj_combo.currentText()
  1426. subtractor_obj = self.app.collection.get_by_name(name)
  1427. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1428. try:
  1429. for geo_elem in target_geo:
  1430. if isinstance(geo_elem, Polygon):
  1431. for ring in self.poly2rings(geo_elem):
  1432. new_geo = ring.difference(sub_union)
  1433. if new_geo and not new_geo.is_empty:
  1434. new_geometry.append(new_geo)
  1435. elif isinstance(geo_elem, MultiPolygon):
  1436. for poly in geo_elem:
  1437. for ring in self.poly2rings(poly):
  1438. new_geo = ring.difference(sub_union)
  1439. if new_geo and not new_geo.is_empty:
  1440. new_geometry.append(new_geo)
  1441. elif isinstance(geo_elem, LineString) or isinstance(geo_elem, LinearRing):
  1442. new_geo = geo_elem.difference(sub_union)
  1443. if new_geo:
  1444. if not new_geo.is_empty:
  1445. new_geometry.append(new_geo)
  1446. elif isinstance(geo_elem, MultiLineString):
  1447. for line_elem in geo_elem:
  1448. new_geo = line_elem.difference(sub_union)
  1449. if new_geo and not new_geo.is_empty:
  1450. new_geometry.append(new_geo)
  1451. except TypeError:
  1452. if isinstance(target_geo, Polygon):
  1453. for ring in self.poly2rings(target_geo):
  1454. new_geo = ring.difference(sub_union)
  1455. if new_geo:
  1456. if not new_geo.is_empty:
  1457. new_geometry.append(new_geo)
  1458. elif isinstance(target_geo, LineString) or isinstance(target_geo, LinearRing):
  1459. new_geo = target_geo.difference(sub_union)
  1460. if new_geo and not new_geo.is_empty:
  1461. new_geometry.append(new_geo)
  1462. elif isinstance(target_geo, MultiLineString):
  1463. for line_elem in target_geo:
  1464. new_geo = line_elem.difference(sub_union)
  1465. if new_geo and not new_geo.is_empty:
  1466. new_geometry.append(new_geo)
  1467. return new_geometry
  1468. def area_intersection(self, geo, intersection_geo=None):
  1469. """
  1470. Return the intersection geometry between geo and intersection_geo
  1471. :param geo: target geometry
  1472. :param intersection_geo: second geometry
  1473. :return:
  1474. """
  1475. new_geometry = []
  1476. target_geo = geo
  1477. intersect_union = cascaded_union(intersection_geo)
  1478. try:
  1479. for geo_elem in target_geo:
  1480. if isinstance(geo_elem, Polygon):
  1481. for ring in self.poly2rings(geo_elem):
  1482. new_geo = ring.intersection(intersect_union)
  1483. if new_geo and not new_geo.is_empty:
  1484. new_geometry.append(new_geo)
  1485. elif isinstance(geo_elem, MultiPolygon):
  1486. for poly in geo_elem:
  1487. for ring in self.poly2rings(poly):
  1488. new_geo = ring.intersection(intersect_union)
  1489. if new_geo and not new_geo.is_empty:
  1490. new_geometry.append(new_geo)
  1491. elif isinstance(geo_elem, LineString) or isinstance(geo_elem, LinearRing):
  1492. new_geo = geo_elem.intersection(intersect_union)
  1493. if new_geo:
  1494. if not new_geo.is_empty:
  1495. new_geometry.append(new_geo)
  1496. elif isinstance(geo_elem, MultiLineString):
  1497. for line_elem in geo_elem:
  1498. new_geo = line_elem.intersection(intersect_union)
  1499. if new_geo and not new_geo.is_empty:
  1500. new_geometry.append(new_geo)
  1501. except TypeError:
  1502. if isinstance(target_geo, Polygon):
  1503. for ring in self.poly2rings(target_geo):
  1504. new_geo = ring.intersection(intersect_union)
  1505. if new_geo:
  1506. if not new_geo.is_empty:
  1507. new_geometry.append(new_geo)
  1508. elif isinstance(target_geo, LineString) or isinstance(target_geo, LinearRing):
  1509. new_geo = target_geo.intersection(intersect_union)
  1510. if new_geo and not new_geo.is_empty:
  1511. new_geometry.append(new_geo)
  1512. elif isinstance(target_geo, MultiLineString):
  1513. for line_elem in target_geo:
  1514. new_geo = line_elem.intersection(intersect_union)
  1515. if new_geo and not new_geo.is_empty:
  1516. new_geometry.append(new_geo)
  1517. return new_geometry
  1518. def on_poly_mouse_click_release(self, event):
  1519. if self.app.is_legacy is False:
  1520. event_pos = event.pos
  1521. right_button = 2
  1522. self.app.event_is_dragging = self.app.event_is_dragging
  1523. else:
  1524. event_pos = (event.xdata, event.ydata)
  1525. right_button = 3
  1526. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1527. try:
  1528. x = float(event_pos[0])
  1529. y = float(event_pos[1])
  1530. except TypeError:
  1531. return
  1532. event_pos = (x, y)
  1533. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1534. if self.app.grid_status():
  1535. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1536. else:
  1537. curr_pos = (curr_pos[0], curr_pos[1])
  1538. if event.button == 1:
  1539. if self.ui.poly_int_cb.get_value() is True:
  1540. clicked_poly = self.find_polygon_ignore_interiors(point=(curr_pos[0], curr_pos[1]),
  1541. geoset=self.grb_obj.solid_geometry)
  1542. clicked_poly = self.get_selected_interior(clicked_poly, point=(curr_pos[0], curr_pos[1]))
  1543. else:
  1544. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.grb_obj.solid_geometry)
  1545. if self.app.selection_type is not None:
  1546. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  1547. self.app.selection_type = None
  1548. elif clicked_poly:
  1549. if clicked_poly not in self.poly_dict.values():
  1550. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  1551. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1552. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1553. visible=True)
  1554. self.poly_dict[shape_id] = clicked_poly
  1555. self.app.inform.emit(
  1556. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  1557. _("Click to add next polygon or right click to start isolation."))
  1558. )
  1559. else:
  1560. try:
  1561. for k, v in list(self.poly_dict.items()):
  1562. if v == clicked_poly:
  1563. self.app.tool_shapes.remove(k)
  1564. self.poly_dict.pop(k)
  1565. break
  1566. except TypeError:
  1567. return
  1568. self.app.inform.emit(
  1569. '%s. %s' % (_("Removed polygon"),
  1570. _("Click to add/remove next polygon or right click to start isolation."))
  1571. )
  1572. self.app.tool_shapes.redraw()
  1573. else:
  1574. self.app.inform.emit(_("No polygon detected under click position."))
  1575. elif event.button == right_button and self.app.event_is_dragging is False:
  1576. # restore the Grid snapping if it was active before
  1577. if self.grid_status_memory is True:
  1578. self.app.ui.grid_snap_btn.trigger()
  1579. if self.app.is_legacy is False:
  1580. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  1581. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1582. else:
  1583. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1584. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1585. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1586. self.app.on_mouse_click_release_over_plot)
  1587. # disconnect flags
  1588. self.poly_sel_disconnect_flag = False
  1589. self.app.tool_shapes.clear(update=True)
  1590. if self.poly_dict:
  1591. poly_list = deepcopy(list(self.poly_dict.values()))
  1592. if self.ui.poly_int_cb.get_value() is True:
  1593. # isolate the interior polygons with a negative tool
  1594. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list, negative_dia=True)
  1595. else:
  1596. self.isolate(isolated_obj=self.grb_obj, geometry=poly_list)
  1597. self.poly_dict.clear()
  1598. else:
  1599. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1600. def selection_area_handler(self, start_pos, end_pos, sel_type):
  1601. """
  1602. :param start_pos: mouse position when the selection LMB click was done
  1603. :param end_pos: mouse position when the left mouse button is released
  1604. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  1605. :return:
  1606. """
  1607. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  1608. # delete previous selection shape
  1609. self.app.delete_selection_shape()
  1610. added_poly_count = 0
  1611. try:
  1612. for geo in self.solid_geometry:
  1613. if geo not in self.poly_dict.values():
  1614. if sel_type is True:
  1615. if geo.within(poly_selection):
  1616. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1617. shape=geo,
  1618. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1619. face_color=self.app.defaults[
  1620. 'global_sel_draw_color'] + 'AF',
  1621. visible=True)
  1622. self.poly_dict[shape_id] = geo
  1623. added_poly_count += 1
  1624. else:
  1625. if poly_selection.intersects(geo):
  1626. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1627. shape=geo,
  1628. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1629. face_color=self.app.defaults[
  1630. 'global_sel_draw_color'] + 'AF',
  1631. visible=True)
  1632. self.poly_dict[shape_id] = geo
  1633. added_poly_count += 1
  1634. except TypeError:
  1635. if self.solid_geometry not in self.poly_dict.values():
  1636. if sel_type is True:
  1637. if self.solid_geometry.within(poly_selection):
  1638. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1639. shape=self.solid_geometry,
  1640. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1641. face_color=self.app.defaults[
  1642. 'global_sel_draw_color'] + 'AF',
  1643. visible=True)
  1644. self.poly_dict[shape_id] = self.solid_geometry
  1645. added_poly_count += 1
  1646. else:
  1647. if poly_selection.intersects(self.solid_geometry):
  1648. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1649. shape=self.solid_geometry,
  1650. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1651. face_color=self.app.defaults[
  1652. 'global_sel_draw_color'] + 'AF',
  1653. visible=True)
  1654. self.poly_dict[shape_id] = self.solid_geometry
  1655. added_poly_count += 1
  1656. if added_poly_count > 0:
  1657. self.app.tool_shapes.redraw()
  1658. self.app.inform.emit(
  1659. '%s: %d. %s' % (_("Added polygon"),
  1660. int(added_poly_count),
  1661. _("Click to add next polygon or right click to start isolation."))
  1662. )
  1663. else:
  1664. self.app.inform.emit(_("No polygon in selection."))
  1665. # To be called after clicking on the plot.
  1666. def on_mouse_release(self, event):
  1667. if self.app.is_legacy is False:
  1668. event_pos = event.pos
  1669. # event_is_dragging = event.is_dragging
  1670. right_button = 2
  1671. else:
  1672. event_pos = (event.xdata, event.ydata)
  1673. # event_is_dragging = self.app.plotcanvas.is_dragging
  1674. right_button = 3
  1675. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1676. if self.app.grid_status():
  1677. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1678. else:
  1679. curr_pos = (event_pos[0], event_pos[1])
  1680. x1, y1 = curr_pos[0], curr_pos[1]
  1681. shape_type = self.area_shape_radio.get_value()
  1682. # do clear area only for left mouse clicks
  1683. if event.button == 1:
  1684. if shape_type == "square":
  1685. if self.first_click is False:
  1686. self.first_click = True
  1687. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  1688. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1689. if self.app.grid_status():
  1690. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1691. else:
  1692. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1693. self.app.delete_selection_shape()
  1694. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1695. pt1 = (x0, y0)
  1696. pt2 = (x1, y0)
  1697. pt3 = (x1, y1)
  1698. pt4 = (x0, y1)
  1699. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1700. self.sel_rect.append(new_rectangle)
  1701. # add a temporary shape on canvas
  1702. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1703. self.first_click = False
  1704. return
  1705. else:
  1706. self.points.append((x1, y1))
  1707. if len(self.points) > 1:
  1708. self.poly_drawn = True
  1709. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1710. return ""
  1711. elif event.button == right_button and self.mouse_is_dragging is False:
  1712. shape_type = self.ui.area_shape_radio.get_value()
  1713. if shape_type == "square":
  1714. self.first_click = False
  1715. else:
  1716. # if we finish to add a polygon
  1717. if self.poly_drawn is True:
  1718. try:
  1719. # try to add the point where we last clicked if it is not already in the self.points
  1720. last_pt = (x1, y1)
  1721. if last_pt != self.points[-1]:
  1722. self.points.append(last_pt)
  1723. except IndexError:
  1724. pass
  1725. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1726. if len(self.points) > 2:
  1727. self.delete_moving_selection_shape()
  1728. pol = Polygon(self.points)
  1729. # do not add invalid polygons even if they are drawn by utility geometry
  1730. if pol.is_valid:
  1731. self.sel_rect.append(pol)
  1732. self.draw_selection_shape_polygon(points=self.points)
  1733. self.app.inform.emit(
  1734. _("Zone added. Click to start adding next zone or right click to finish."))
  1735. self.points = []
  1736. self.poly_drawn = False
  1737. return
  1738. self.delete_tool_selection_shape()
  1739. if self.app.is_legacy is False:
  1740. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1741. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1742. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1743. else:
  1744. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1745. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1746. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1747. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1748. self.app.on_mouse_click_over_plot)
  1749. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1750. self.app.on_mouse_move_over_plot)
  1751. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1752. self.app.on_mouse_click_release_over_plot)
  1753. # disconnect flags
  1754. self.area_sel_disconnect_flag = False
  1755. if len(self.sel_rect) == 0:
  1756. return
  1757. self.sel_rect = cascaded_union(self.sel_rect)
  1758. self.isolate(isolated_obj=self.grb_obj, limited_area=self.sel_rect, plot=True)
  1759. self.sel_rect = []
  1760. # called on mouse move
  1761. def on_mouse_move(self, event):
  1762. shape_type = self.ui.area_shape_radio.get_value()
  1763. if self.app.is_legacy is False:
  1764. event_pos = event.pos
  1765. event_is_dragging = event.is_dragging
  1766. # right_button = 2
  1767. else:
  1768. event_pos = (event.xdata, event.ydata)
  1769. event_is_dragging = self.app.plotcanvas.is_dragging
  1770. # right_button = 3
  1771. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1772. # detect mouse dragging motion
  1773. if event_is_dragging is True:
  1774. self.mouse_is_dragging = True
  1775. else:
  1776. self.mouse_is_dragging = False
  1777. # update the cursor position
  1778. if self.app.grid_status():
  1779. # Update cursor
  1780. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1781. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1782. symbol='++', edge_color=self.app.cursor_color_3D,
  1783. edge_width=self.app.defaults["global_cursor_width"],
  1784. size=self.app.defaults["global_cursor_size"])
  1785. if self.cursor_pos is None:
  1786. self.cursor_pos = (0, 0)
  1787. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1788. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1789. # # update the positions on status bar
  1790. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1791. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1792. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1793. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1794. units = self.app.defaults["units"].lower()
  1795. self.app.plotcanvas.text_hud.text = \
  1796. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1797. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1798. # draw the utility geometry
  1799. if shape_type == "square":
  1800. if self.first_click:
  1801. self.app.delete_selection_shape()
  1802. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1803. coords=(curr_pos[0], curr_pos[1]))
  1804. else:
  1805. self.delete_moving_selection_shape()
  1806. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1807. def on_key_press(self, event):
  1808. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1809. # matplotlib_key_flag = False
  1810. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1811. if type(event) is int:
  1812. key = event
  1813. # events from the GUI are of type QKeyEvent
  1814. elif type(event) == QtGui.QKeyEvent:
  1815. key = event.key()
  1816. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1817. # matplotlib_key_flag = True
  1818. key = event.key
  1819. key = QtGui.QKeySequence(key)
  1820. # check for modifiers
  1821. key_string = key.toString().lower()
  1822. if '+' in key_string:
  1823. mod, __, key_text = key_string.rpartition('+')
  1824. if mod.lower() == 'ctrl':
  1825. # modifiers = QtCore.Qt.ControlModifier
  1826. pass
  1827. elif mod.lower() == 'alt':
  1828. # modifiers = QtCore.Qt.AltModifier
  1829. pass
  1830. elif mod.lower() == 'shift':
  1831. # modifiers = QtCore.Qt.ShiftModifier
  1832. pass
  1833. else:
  1834. # modifiers = QtCore.Qt.NoModifier
  1835. pass
  1836. key = QtGui.QKeySequence(key_text)
  1837. # events from Vispy are of type KeyEvent
  1838. else:
  1839. key = event.key
  1840. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1841. if self.area_sel_disconnect_flag is True:
  1842. if self.app.is_legacy is False:
  1843. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1844. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1845. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1846. else:
  1847. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1848. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1849. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1850. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1851. self.app.on_mouse_click_over_plot)
  1852. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1853. self.app.on_mouse_move_over_plot)
  1854. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1855. self.app.on_mouse_click_release_over_plot)
  1856. if self.poly_sel_disconnect_flag is False:
  1857. # restore the Grid snapping if it was active before
  1858. if self.grid_status_memory is True:
  1859. self.app.ui.grid_snap_btn.trigger()
  1860. if self.app.is_legacy is False:
  1861. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_poly_mouse_click_release)
  1862. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1863. else:
  1864. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1865. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1866. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1867. self.app.on_mouse_click_release_over_plot)
  1868. self.points = []
  1869. self.poly_drawn = False
  1870. self.delete_moving_selection_shape()
  1871. self.delete_tool_selection_shape()
  1872. def on_iso_tool_add_from_db_executed(self, tool):
  1873. """
  1874. Here add the tool from DB in the selected geometry object
  1875. :return:
  1876. """
  1877. tool_from_db = deepcopy(tool)
  1878. res = self.on_tool_from_db_inserted(tool=tool_from_db)
  1879. for idx in range(self.app.ui.plot_tab_area.count()):
  1880. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  1881. wdg = self.app.ui.plot_tab_area.widget(idx)
  1882. wdg.deleteLater()
  1883. self.app.ui.plot_tab_area.removeTab(idx)
  1884. if res == 'fail':
  1885. return
  1886. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  1887. # select last tool added
  1888. toolid = res
  1889. for row in range(self.ui.tools_table.rowCount()):
  1890. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  1891. self.ui.tools_table.selectRow(row)
  1892. self.on_row_selection_change()
  1893. def on_tool_from_db_inserted(self, tool):
  1894. """
  1895. Called from the Tools DB object through a App method when adding a tool from Tools Database
  1896. :param tool: a dict with the tool data
  1897. :return: None
  1898. """
  1899. self.ui_disconnect()
  1900. self.units = self.app.defaults['units'].upper()
  1901. tooldia = float(tool['tooldia'])
  1902. # construct a list of all 'tooluid' in the self.tools
  1903. tool_uid_list = []
  1904. for tooluid_key in self.iso_tools:
  1905. tool_uid_item = int(tooluid_key)
  1906. tool_uid_list.append(tool_uid_item)
  1907. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1908. if not tool_uid_list:
  1909. max_uid = 0
  1910. else:
  1911. max_uid = max(tool_uid_list)
  1912. tooluid = max_uid + 1
  1913. tooldia = float('%.*f' % (self.decimals, tooldia))
  1914. tool_dias = []
  1915. for k, v in self.iso_tools.items():
  1916. for tool_v in v.keys():
  1917. if tool_v == 'tooldia':
  1918. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1919. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  1920. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  1921. self.ui_connect()
  1922. return 'fail'
  1923. self.iso_tools.update({
  1924. tooluid: {
  1925. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  1926. 'offset': tool['offset'],
  1927. 'offset_value': tool['offset_value'],
  1928. 'type': tool['type'],
  1929. 'tool_type': tool['tool_type'],
  1930. 'data': deepcopy(tool['data']),
  1931. 'solid_geometry': []
  1932. }
  1933. })
  1934. self.iso_tools[tooluid]['data']['name'] = '_iso'
  1935. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1936. self.ui_connect()
  1937. self.build_ui()
  1938. # select the tool just added
  1939. for row in range(self.ui.tools_table.rowCount()):
  1940. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  1941. self.ui.tools_table.selectRow(row)
  1942. break
  1943. # if self.ui.tools_table.rowCount() != 0:
  1944. # self.param_frame.setDisabled(False)
  1945. def on_tool_add_from_db_clicked(self):
  1946. """
  1947. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  1948. and display the Tools Database tab in the form needed for the Tool adding
  1949. :return: None
  1950. """
  1951. # if the Tools Database is already opened focus on it
  1952. for idx in range(self.app.ui.plot_tab_area.count()):
  1953. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  1954. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  1955. break
  1956. self.app.on_tools_database(source='iso')
  1957. self.app.tools_db_tab.ok_to_add = True
  1958. self.app.tools_db_tab.buttons_frame.hide()
  1959. self.app.tools_db_tab.add_tool_from_db.show()
  1960. self.app.tools_db_tab.cancel_tool_from_db.show()
  1961. def reset_fields(self):
  1962. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1963. @staticmethod
  1964. def poly2rings(poly):
  1965. return [poly.exterior] + [interior for interior in poly.interiors]
  1966. @staticmethod
  1967. def poly2ext(poly):
  1968. return [poly.exterior]
  1969. @staticmethod
  1970. def poly2ints(poly):
  1971. return [interior for interior in poly.interiors]
  1972. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0,
  1973. prog_plot=False):
  1974. """
  1975. Isolation_geometry produces an envelope that is going on the left of the geometry
  1976. (the copper features). To leave the least amount of burrs on the features
  1977. the tool needs to travel on the right side of the features (this is called conventional milling)
  1978. the first pass is the one cutting all of the features, so it needs to be reversed
  1979. the other passes overlap preceding ones and cut the left over copper. It is better for them
  1980. to cut on the right side of the left over copper i.e on the left side of the features.
  1981. :param offset: Offset distance to be passed to the obj.isolation_geometry() method
  1982. :type offset: float
  1983. :param invert: If to invert the direction of geometry (CW to CCW or reverse)
  1984. :type invert: int
  1985. :param geometry: Shapely Geometry for which t ogenerate envelope
  1986. :type geometry:
  1987. :param env_iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  1988. :type env_iso_type: int
  1989. :param follow: If the kind of isolation is a "follow" one
  1990. :type follow: bool
  1991. :param nr_passes: Number of passes
  1992. :type nr_passes: int
  1993. :param prog_plot: Type of plotting: "normal" or "progressive"
  1994. :type prog_plot: str
  1995. :return: The buffered geometry
  1996. :rtype: MultiPolygon or Polygon
  1997. """
  1998. if follow:
  1999. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, follow=follow, prog_plot=prog_plot)
  2000. return geom
  2001. else:
  2002. try:
  2003. geom = self.grb_obj.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type,
  2004. passes=nr_passes, prog_plot=prog_plot)
  2005. except Exception as e:
  2006. log.debug('ToolIsolation.generate_envelope() --> %s' % str(e))
  2007. return 'fail'
  2008. if invert:
  2009. try:
  2010. pl = []
  2011. for p in geom:
  2012. if p is not None:
  2013. if isinstance(p, Polygon):
  2014. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2015. elif isinstance(p, LinearRing):
  2016. pl.append(Polygon(p.coords[::-1]))
  2017. geom = MultiPolygon(pl)
  2018. except TypeError:
  2019. if isinstance(geom, Polygon) and geom is not None:
  2020. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2021. elif isinstance(geom, LinearRing) and geom is not None:
  2022. geom = Polygon(geom.coords[::-1])
  2023. else:
  2024. log.debug("ToolIsolation.generate_envelope() Error --> Unexpected Geometry %s" %
  2025. type(geom))
  2026. except Exception as e:
  2027. log.debug("ToolIsolation.generate_envelope() Error --> %s" % str(e))
  2028. return 'fail'
  2029. return geom
  2030. @staticmethod
  2031. def generate_rest_geometry(geometry, tooldia, passes, overlap, invert, env_iso_type=2, negative_dia=None,
  2032. forced_rest=False,
  2033. prog_plot="normal", prog_plot_handler=None):
  2034. """
  2035. Will try to isolate the geometry and return a tuple made of list of paths made through isolation
  2036. and a list of Shapely Polygons that could not be isolated
  2037. :param geometry: A list of Shapely Polygons to be isolated
  2038. :type geometry: list
  2039. :param tooldia: The tool diameter used to do the isolation
  2040. :type tooldia: float
  2041. :param passes: Number of passes that will made the isolation
  2042. :type passes: int
  2043. :param overlap: How much to overlap the previous pass; in percentage [0.00, 99.99]%
  2044. :type overlap: float
  2045. :param invert: If to invert the direction of the resulting isolated geometries
  2046. :type invert: bool
  2047. :param env_iso_type: can be either 0 = keep exteriors or 1 = keep interiors or 2 = keep all paths
  2048. :type env_iso_type: int
  2049. :param negative_dia: isolate the geometry with a negative value for the tool diameter
  2050. :type negative_dia: bool
  2051. :param forced_rest: isolate the polygon even if the interiors can not be isolated
  2052. :type forced_rest: bool
  2053. :param prog_plot: kind of plotting: "progressive" or "normal"
  2054. :type prog_plot: str
  2055. :param prog_plot_handler: method used to plot shapes if plot_prog is "proggressive"
  2056. :type prog_plot_handler:
  2057. :return: Tuple made from list of isolating paths and list of not isolated Polygons
  2058. :rtype: tuple
  2059. """
  2060. isolated_geo = []
  2061. not_isolated_geo = []
  2062. work_geo = []
  2063. for idx, geo in enumerate(geometry):
  2064. good_pass_iso = []
  2065. start_idx = idx + 1
  2066. for nr_pass in range(passes):
  2067. iso_offset = tooldia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * tooldia)
  2068. if negative_dia:
  2069. iso_offset = -iso_offset
  2070. buf_chek = iso_offset * 2
  2071. check_geo = geo.buffer(buf_chek)
  2072. intersect_flag = False
  2073. # find if current pass for current geo is valid (no intersection with other geos))
  2074. for geo_search_idx in range(idx):
  2075. if check_geo.intersects(geometry[geo_search_idx]):
  2076. intersect_flag = True
  2077. break
  2078. if intersect_flag is False:
  2079. for geo_search_idx in range(start_idx, len(geometry)):
  2080. if check_geo.intersects(geometry[geo_search_idx]):
  2081. intersect_flag = True
  2082. break
  2083. # if we had an intersection do nothing, else add the geo to the good pass isolation's
  2084. if intersect_flag is False:
  2085. temp_geo = geo.buffer(iso_offset)
  2086. # this test is done only for the first pass because this is where is relevant
  2087. # test if in the first pass, the geo that is isolated has interiors and if it has then test if the
  2088. # resulting isolated geometry (buffered) number of subgeo is the same as the exterior + interiors
  2089. # if not it means that the geo interiors most likely could not be isolated with this tool so we
  2090. # abandon the whole isolation for this geo and add this geo to the not_isolated_geo
  2091. if nr_pass == 0 and forced_rest is True:
  2092. if geo.interiors:
  2093. len_interiors = len(geo.interiors)
  2094. if len_interiors > 1:
  2095. total_poly_len = 1 + len_interiors # one exterior + len_interiors of interiors
  2096. if isinstance(temp_geo, Polygon):
  2097. # calculate the number of subgeos in the buffered geo
  2098. temp_geo_len = len([1] + list(temp_geo.interiors)) # one exterior + interiors
  2099. if total_poly_len != temp_geo_len:
  2100. # some interiors could not be isolated
  2101. break
  2102. else:
  2103. try:
  2104. temp_geo_len = len(temp_geo)
  2105. if total_poly_len != temp_geo_len:
  2106. # some interiors could not be isolated
  2107. break
  2108. except TypeError:
  2109. # this means that the buffered geo (temp_geo) is not iterable
  2110. # (one geo element only) therefore failure:
  2111. # we have more interiors but the resulting geo is only one
  2112. break
  2113. good_pass_iso.append(temp_geo)
  2114. if prog_plot == 'progressive':
  2115. prog_plot_handler(temp_geo)
  2116. if good_pass_iso:
  2117. work_geo += good_pass_iso
  2118. else:
  2119. not_isolated_geo.append(geo)
  2120. if invert:
  2121. try:
  2122. pl = []
  2123. for p in work_geo:
  2124. if p is not None:
  2125. if isinstance(p, Polygon):
  2126. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2127. elif isinstance(p, LinearRing):
  2128. pl.append(Polygon(p.coords[::-1]))
  2129. work_geo = MultiPolygon(pl)
  2130. except TypeError:
  2131. if isinstance(work_geo, Polygon) and work_geo is not None:
  2132. work_geo = [Polygon(work_geo.exterior.coords[::-1], work_geo.interiors)]
  2133. elif isinstance(work_geo, LinearRing) and work_geo is not None:
  2134. work_geo = [Polygon(work_geo.coords[::-1])]
  2135. else:
  2136. log.debug("ToolIsolation.generate_rest_geometry() Error --> Unexpected Geometry %s" %
  2137. type(work_geo))
  2138. except Exception as e:
  2139. log.debug("ToolIsolation.generate_rest_geometry() Error --> %s" % str(e))
  2140. return 'fail', 'fail'
  2141. if env_iso_type == 0: # exterior
  2142. for geo in work_geo:
  2143. isolated_geo.append(geo.exterior)
  2144. elif env_iso_type == 1: # interiors
  2145. for geo in work_geo:
  2146. isolated_geo += [interior for interior in geo.interiors]
  2147. else: # exterior + interiors
  2148. for geo in work_geo:
  2149. isolated_geo += [geo.exterior] + [interior for interior in geo.interiors]
  2150. return isolated_geo, not_isolated_geo
  2151. @staticmethod
  2152. def get_selected_interior(poly: Polygon, point: tuple) -> [Polygon, None]:
  2153. try:
  2154. ints = [Polygon(x) for x in poly.interiors]
  2155. except AttributeError:
  2156. return None
  2157. for poly in ints:
  2158. if poly.contains(Point(point)):
  2159. return poly
  2160. return None
  2161. def find_polygon_ignore_interiors(self, point, geoset=None):
  2162. """
  2163. Find an object that object.contains(Point(point)) in
  2164. poly, which can can be iterable, contain iterable of, or
  2165. be itself an implementer of .contains(). Will test the Polygon as it is full with no interiors.
  2166. :param point: See description
  2167. :param geoset: a polygon or list of polygons where to find if the param point is contained
  2168. :return: Polygon containing point or None.
  2169. """
  2170. if geoset is None:
  2171. geoset = self.solid_geometry
  2172. try: # Iterable
  2173. for sub_geo in geoset:
  2174. p = self.find_polygon_ignore_interiors(point, geoset=sub_geo)
  2175. if p is not None:
  2176. return p
  2177. except TypeError: # Non-iterable
  2178. try: # Implements .contains()
  2179. if isinstance(geoset, LinearRing):
  2180. geoset = Polygon(geoset)
  2181. poly_ext = Polygon(geoset.exterior)
  2182. if poly_ext.contains(Point(point)):
  2183. return geoset
  2184. except AttributeError: # Does not implement .contains()
  2185. return None
  2186. return None
  2187. class IsoUI:
  2188. toolName = _("Isolation Tool")
  2189. def __init__(self, layout, app):
  2190. self.app = app
  2191. self.decimals = self.app.decimals
  2192. self.layout = layout
  2193. self.tools_frame = QtWidgets.QFrame()
  2194. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2195. self.layout.addWidget(self.tools_frame)
  2196. self.tools_box = QtWidgets.QVBoxLayout()
  2197. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2198. self.tools_frame.setLayout(self.tools_box)
  2199. self.title_box = QtWidgets.QHBoxLayout()
  2200. self.tools_box.addLayout(self.title_box)
  2201. # ## Title
  2202. title_label = QtWidgets.QLabel("%s" % self.toolName)
  2203. title_label.setStyleSheet("""
  2204. QLabel
  2205. {
  2206. font-size: 16px;
  2207. font-weight: bold;
  2208. }
  2209. """)
  2210. title_label.setToolTip(
  2211. _("Create a Geometry object with\n"
  2212. "toolpaths to cut around polygons.")
  2213. )
  2214. self.title_box.addWidget(title_label)
  2215. # App Level label
  2216. self.level = QtWidgets.QLabel("")
  2217. self.level.setToolTip(
  2218. _(
  2219. "BASIC is suitable for a beginner. Many parameters\n"
  2220. "are hidden from the user in this mode.\n"
  2221. "ADVANCED mode will make available all parameters.\n\n"
  2222. "To change the application LEVEL, go to:\n"
  2223. "Edit -> Preferences -> General and check:\n"
  2224. "'APP. LEVEL' radio button."
  2225. )
  2226. )
  2227. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2228. self.title_box.addWidget(self.level)
  2229. # Grid Layout
  2230. grid0 = QtWidgets.QGridLayout()
  2231. grid0.setColumnStretch(0, 0)
  2232. grid0.setColumnStretch(1, 1)
  2233. self.tools_box.addLayout(grid0)
  2234. self.obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("GERBER"))
  2235. self.obj_combo_label.setToolTip(
  2236. _("Gerber object for isolation routing.")
  2237. )
  2238. grid0.addWidget(self.obj_combo_label, 0, 0, 1, 2)
  2239. # ################################################
  2240. # ##### The object to be copper cleaned ##########
  2241. # ################################################
  2242. self.object_combo = FCComboBox()
  2243. self.object_combo.setModel(self.app.collection)
  2244. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2245. # self.object_combo.setCurrentIndex(1)
  2246. self.object_combo.is_last = True
  2247. grid0.addWidget(self.object_combo, 1, 0, 1, 2)
  2248. separator_line = QtWidgets.QFrame()
  2249. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2250. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2251. grid0.addWidget(separator_line, 2, 0, 1, 2)
  2252. # ### Tools ## ##
  2253. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  2254. self.tools_table_label.setToolTip(
  2255. _("Tools pool from which the algorithm\n"
  2256. "will pick the ones used for copper clearing.")
  2257. )
  2258. grid0.addWidget(self.tools_table_label, 3, 0, 1, 2)
  2259. self.tools_table = FCTable(drag_drop=True)
  2260. grid0.addWidget(self.tools_table, 4, 0, 1, 2)
  2261. self.tools_table.setColumnCount(4)
  2262. # 3rd column is reserved (and hidden) for the tool ID
  2263. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  2264. self.tools_table.setColumnHidden(3, True)
  2265. self.tools_table.setSortingEnabled(False)
  2266. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2267. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2268. _("This is the Tool Number.\n"
  2269. "Isolation routing will start with the tool with the biggest \n"
  2270. "diameter, continuing until there are no more tools.\n"
  2271. "Only tools that create Isolation geometry will still be present\n"
  2272. "in the resulting geometry. This is because with some tools\n"
  2273. "this function will not be able to create routing geometry.")
  2274. )
  2275. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2276. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  2277. "is the cut width into the material."))
  2278. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2279. _("The Tool Type (TT) can be:\n"
  2280. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  2281. "the cut width in material is exactly the tool diameter.\n"
  2282. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  2283. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  2284. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  2285. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  2286. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  2287. "column of this table.\n"
  2288. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  2289. "in the resulting geometry as Isolation."))
  2290. grid1 = QtWidgets.QGridLayout()
  2291. grid1.setColumnStretch(0, 0)
  2292. grid1.setColumnStretch(1, 1)
  2293. self.tools_box.addLayout(grid1)
  2294. # Tool order
  2295. self.order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  2296. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2297. "'No' --> means that the used order is the one in the tool table\n"
  2298. "'Forward' --> means that the tools will be ordered from small to big\n"
  2299. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2300. "WARNING: using rest machining will automatically set the order\n"
  2301. "in reverse and disable this control."))
  2302. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2303. {'label': _('Forward'), 'value': 'fwd'},
  2304. {'label': _('Reverse'), 'value': 'rev'}])
  2305. grid1.addWidget(self.order_label, 1, 0)
  2306. grid1.addWidget(self.order_radio, 1, 1)
  2307. separator_line = QtWidgets.QFrame()
  2308. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2309. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2310. grid1.addWidget(separator_line, 2, 0, 1, 2)
  2311. # #############################################################
  2312. # ############### Tool selection ##############################
  2313. # #############################################################
  2314. self.grid3 = QtWidgets.QGridLayout()
  2315. self.grid3.setColumnStretch(0, 0)
  2316. self.grid3.setColumnStretch(1, 1)
  2317. self.tools_box.addLayout(self.grid3)
  2318. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  2319. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  2320. # Tool Type Radio Button
  2321. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  2322. self.tool_type_label.setToolTip(
  2323. _("Default tool type:\n"
  2324. "- 'V-shape'\n"
  2325. "- Circular")
  2326. )
  2327. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  2328. {'label': _('Circular'), 'value': 'C1'}])
  2329. self.tool_type_radio.setToolTip(
  2330. _("Default tool type:\n"
  2331. "- 'V-shape'\n"
  2332. "- Circular")
  2333. )
  2334. self.tool_type_radio.setObjectName("i_tool_type")
  2335. self.grid3.addWidget(self.tool_type_label, 2, 0)
  2336. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  2337. # Tip Dia
  2338. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  2339. self.tipdialabel.setToolTip(
  2340. _("The tip diameter for V-Shape Tool"))
  2341. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2342. self.tipdia_entry.set_precision(self.decimals)
  2343. self.tipdia_entry.set_range(0.0000, 9999.9999)
  2344. self.tipdia_entry.setSingleStep(0.1)
  2345. self.tipdia_entry.setObjectName("i_vtipdia")
  2346. self.grid3.addWidget(self.tipdialabel, 3, 0)
  2347. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  2348. # Tip Angle
  2349. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  2350. self.tipanglelabel.setToolTip(
  2351. _("The tip angle for V-Shape Tool.\n"
  2352. "In degree."))
  2353. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2354. self.tipangle_entry.set_precision(self.decimals)
  2355. self.tipangle_entry.set_range(0.0000, 180.0000)
  2356. self.tipangle_entry.setSingleStep(5)
  2357. self.tipangle_entry.setObjectName("i_vtipangle")
  2358. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  2359. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  2360. # Cut Z entry
  2361. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  2362. cutzlabel.setToolTip(
  2363. _("Depth of cut into material. Negative value.\n"
  2364. "In FlatCAM units.")
  2365. )
  2366. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2367. self.cutz_entry.set_precision(self.decimals)
  2368. self.cutz_entry.set_range(-99999.9999, 0.0000)
  2369. self.cutz_entry.setObjectName("i_vcutz")
  2370. self.grid3.addWidget(cutzlabel, 5, 0)
  2371. self.grid3.addWidget(self.cutz_entry, 5, 1)
  2372. # ### Tool Diameter ####
  2373. self.addtool_entry_lbl = QtWidgets.QLabel('%s:' % _('Tool Dia'))
  2374. self.addtool_entry_lbl.setToolTip(
  2375. _("Diameter for the new tool to add in the Tool Table.\n"
  2376. "If the tool is V-shape type then this value is automatically\n"
  2377. "calculated from the other parameters.")
  2378. )
  2379. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2380. self.addtool_entry.set_precision(self.decimals)
  2381. self.addtool_entry.set_range(0.000, 9999.9999)
  2382. self.addtool_entry.setObjectName("i_new_tooldia")
  2383. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  2384. self.grid3.addWidget(self.addtool_entry, 6, 1)
  2385. bhlay = QtWidgets.QHBoxLayout()
  2386. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  2387. self.addtool_btn.setToolTip(
  2388. _("Add a new tool to the Tool Table\n"
  2389. "with the diameter specified above.")
  2390. )
  2391. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  2392. self.addtool_from_db_btn.setToolTip(
  2393. _("Add a new tool to the Tool Table\n"
  2394. "from the Tool Database.\n"
  2395. "Tool database administration in Menu: Options -> Tools Database")
  2396. )
  2397. bhlay.addWidget(self.addtool_btn)
  2398. bhlay.addWidget(self.addtool_from_db_btn)
  2399. self.grid3.addLayout(bhlay, 7, 0, 1, 2)
  2400. separator_line = QtWidgets.QFrame()
  2401. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2402. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2403. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  2404. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  2405. self.deltool_btn.setToolTip(
  2406. _("Delete a selection of tools in the Tool Table\n"
  2407. "by first selecting a row(s) in the Tool Table.")
  2408. )
  2409. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  2410. # self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  2411. separator_line = QtWidgets.QFrame()
  2412. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2413. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2414. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  2415. self.tool_data_label = QtWidgets.QLabel(
  2416. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2417. self.tool_data_label.setToolTip(
  2418. _(
  2419. "The data used for creating GCode.\n"
  2420. "Each tool store it's own set of such data."
  2421. )
  2422. )
  2423. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  2424. # Passes
  2425. passlabel = QtWidgets.QLabel('%s:' % _('Passes'))
  2426. passlabel.setToolTip(
  2427. _("Width of the isolation gap in\n"
  2428. "number (integer) of tool widths.")
  2429. )
  2430. self.passes_entry = FCSpinner(callback=self.confirmation_message_int)
  2431. self.passes_entry.set_range(1, 999)
  2432. self.passes_entry.setObjectName("i_passes")
  2433. self.grid3.addWidget(passlabel, 13, 0)
  2434. self.grid3.addWidget(self.passes_entry, 13, 1)
  2435. # Overlap Entry
  2436. overlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  2437. overlabel.setToolTip(
  2438. _("How much (percentage) of the tool width to overlap each tool pass.")
  2439. )
  2440. self.iso_overlap_entry = FCDoubleSpinner(suffix='%', callback=self.confirmation_message)
  2441. self.iso_overlap_entry.set_precision(self.decimals)
  2442. self.iso_overlap_entry.setWrapping(True)
  2443. self.iso_overlap_entry.set_range(0.0000, 99.9999)
  2444. self.iso_overlap_entry.setSingleStep(0.1)
  2445. self.iso_overlap_entry.setObjectName("i_overlap")
  2446. self.grid3.addWidget(overlabel, 14, 0)
  2447. self.grid3.addWidget(self.iso_overlap_entry, 14, 1)
  2448. # Milling Type Radio Button
  2449. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  2450. self.milling_type_label.setToolTip(
  2451. _("Milling type when the selected tool is of type: 'iso_op':\n"
  2452. "- climb / best for precision milling and to reduce tool usage\n"
  2453. "- conventional / useful when there is no backlash compensation")
  2454. )
  2455. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  2456. {'label': _('Conventional'), 'value': 'cv'}])
  2457. self.milling_type_radio.setToolTip(
  2458. _("Milling type when the selected tool is of type: 'iso_op':\n"
  2459. "- climb / best for precision milling and to reduce tool usage\n"
  2460. "- conventional / useful when there is no backlash compensation")
  2461. )
  2462. self.milling_type_radio.setObjectName("i_milling_type")
  2463. self.grid3.addWidget(self.milling_type_label, 15, 0)
  2464. self.grid3.addWidget(self.milling_type_radio, 15, 1)
  2465. # Follow
  2466. self.follow_label = QtWidgets.QLabel('%s:' % _('Follow'))
  2467. self.follow_label.setToolTip(
  2468. _("Generate a 'Follow' geometry.\n"
  2469. "This means that it will cut through\n"
  2470. "the middle of the trace.")
  2471. )
  2472. self.follow_cb = FCCheckBox()
  2473. self.follow_cb.setToolTip(_("Generate a 'Follow' geometry.\n"
  2474. "This means that it will cut through\n"
  2475. "the middle of the trace."))
  2476. self.follow_cb.setObjectName("i_follow")
  2477. self.grid3.addWidget(self.follow_label, 16, 0)
  2478. self.grid3.addWidget(self.follow_cb, 16, 1)
  2479. # Isolation Type
  2480. self.iso_type_label = QtWidgets.QLabel('%s:' % _('Isolation Type'))
  2481. self.iso_type_label.setToolTip(
  2482. _("Choose how the isolation will be executed:\n"
  2483. "- 'Full' -> complete isolation of polygons\n"
  2484. "- 'Ext' -> will isolate only on the outside\n"
  2485. "- 'Int' -> will isolate only on the inside\n"
  2486. "'Exterior' isolation is almost always possible\n"
  2487. "(with the right tool) but 'Interior'\n"
  2488. "isolation can be done only when there is an opening\n"
  2489. "inside of the polygon (e.g polygon is a 'doughnut' shape).")
  2490. )
  2491. self.iso_type_radio = RadioSet([{'label': _('Full'), 'value': 'full'},
  2492. {'label': _('Ext'), 'value': 'ext'},
  2493. {'label': _('Int'), 'value': 'int'}])
  2494. self.iso_type_radio.setObjectName("i_iso_type")
  2495. self.grid3.addWidget(self.iso_type_label, 17, 0)
  2496. self.grid3.addWidget(self.iso_type_radio, 17, 1)
  2497. separator_line = QtWidgets.QFrame()
  2498. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2499. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2500. self.grid3.addWidget(separator_line, 18, 0, 1, 2)
  2501. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  2502. self.apply_param_to_all.setToolTip(
  2503. _("The parameters in the current form will be applied\n"
  2504. "on all the tools from the Tool Table.")
  2505. )
  2506. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  2507. separator_line = QtWidgets.QFrame()
  2508. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2509. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2510. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  2511. # General Parameters
  2512. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  2513. self.gen_param_label.setToolTip(
  2514. _("Parameters that are common for all tools.")
  2515. )
  2516. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  2517. # Rest Machining
  2518. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  2519. self.rest_cb.setObjectName("i_rest")
  2520. self.rest_cb.setToolTip(
  2521. _("If checked, use 'rest machining'.\n"
  2522. "Basically it will isolate outside PCB features,\n"
  2523. "using the biggest tool and continue with the next tools,\n"
  2524. "from bigger to smaller, to isolate the copper features that\n"
  2525. "could not be cleared by previous tool, until there is\n"
  2526. "no more copper features to isolate or there are no more tools.\n"
  2527. "If not checked, use the standard algorithm.")
  2528. )
  2529. self.grid3.addWidget(self.rest_cb, 25, 0)
  2530. # Force isolation even if the interiors are not isolated
  2531. self.forced_rest_iso_cb = FCCheckBox(_("Forced Rest"))
  2532. self.forced_rest_iso_cb.setToolTip(
  2533. _("When checked the isolation will be done with the current tool even if\n"
  2534. "interiors of a polygon (holes in the polygon) could not be isolated.\n"
  2535. "Works when 'rest machining' is used.")
  2536. )
  2537. self.grid3.addWidget(self.forced_rest_iso_cb, 25, 1)
  2538. # Combine All Passes
  2539. self.combine_passes_cb = FCCheckBox(label=_('Combine'))
  2540. self.combine_passes_cb.setToolTip(
  2541. _("Combine all passes into one object")
  2542. )
  2543. self.combine_passes_cb.setObjectName("i_combine")
  2544. self.grid3.addWidget(self.combine_passes_cb, 26, 0, 1, 2)
  2545. # Exception Areas
  2546. self.except_cb = FCCheckBox(label=_('Except'))
  2547. self.except_cb.setToolTip(_("When the isolation geometry is generated,\n"
  2548. "by checking this, the area of the object below\n"
  2549. "will be subtracted from the isolation geometry."))
  2550. self.except_cb.setObjectName("i_except")
  2551. self.grid3.addWidget(self.except_cb, 27, 0)
  2552. # Type of object to be excepted
  2553. self.type_excobj_radio = RadioSet([{'label': _("Geometry"), 'value': 'geometry'},
  2554. {'label': _("Gerber"), 'value': 'gerber'}])
  2555. self.type_excobj_radio.setToolTip(
  2556. _("Specify the type of object to be excepted from isolation.\n"
  2557. "It can be of type: Gerber or Geometry.\n"
  2558. "What is selected here will dictate the kind\n"
  2559. "of objects that will populate the 'Object' combobox.")
  2560. )
  2561. self.grid3.addWidget(self.type_excobj_radio, 27, 1)
  2562. # The object to be excepted
  2563. self.exc_obj_combo = FCComboBox()
  2564. self.exc_obj_combo.setToolTip(_("Object whose area will be removed from isolation geometry."))
  2565. # set the model for the Area Exception comboboxes
  2566. self.exc_obj_combo.setModel(self.app.collection)
  2567. self.exc_obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2568. self.exc_obj_combo.is_last = True
  2569. self.exc_obj_combo.obj_type = self.type_excobj_radio.get_value()
  2570. self.grid3.addWidget(self.exc_obj_combo, 29, 0, 1, 2)
  2571. self.e_ois = OptionalInputSection(self.except_cb,
  2572. [
  2573. self.type_excobj_radio,
  2574. self.exc_obj_combo
  2575. ])
  2576. # Isolation Scope
  2577. self.select_label = QtWidgets.QLabel('%s:' % _("Selection"))
  2578. self.select_label.setToolTip(
  2579. _("Isolation scope. Choose what to isolate:\n"
  2580. "- 'All' -> Isolate all the polygons in the object\n"
  2581. "- 'Area Selection' -> Isolate polygons within a selection area.\n"
  2582. "- 'Polygon Selection' -> Isolate a selection of polygons.\n"
  2583. "- 'Reference Object' - will process the area specified by another object.")
  2584. )
  2585. self.select_combo = FCComboBox()
  2586. self.select_combo.addItems(
  2587. [_("All"), _("Area Selection"), _("Polygon Selection"), _("Reference Object")]
  2588. )
  2589. self.select_combo.setObjectName("i_selection")
  2590. self.grid3.addWidget(self.select_label, 30, 0)
  2591. self.grid3.addWidget(self.select_combo, 30, 1)
  2592. self.reference_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  2593. self.reference_combo_type_label.setToolTip(
  2594. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  2595. "It can be Gerber, Excellon or Geometry.")
  2596. )
  2597. self.reference_combo_type = FCComboBox()
  2598. self.reference_combo_type.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  2599. self.grid3.addWidget(self.reference_combo_type_label, 31, 0)
  2600. self.grid3.addWidget(self.reference_combo_type, 31, 1)
  2601. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  2602. self.reference_combo_label.setToolTip(
  2603. _("The FlatCAM object to be used as non copper clearing reference.")
  2604. )
  2605. self.reference_combo = FCComboBox()
  2606. self.reference_combo.setModel(self.app.collection)
  2607. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2608. self.reference_combo.is_last = True
  2609. self.grid3.addWidget(self.reference_combo_label, 32, 0)
  2610. self.grid3.addWidget(self.reference_combo, 32, 1)
  2611. self.reference_combo.hide()
  2612. self.reference_combo_label.hide()
  2613. self.reference_combo_type.hide()
  2614. self.reference_combo_type_label.hide()
  2615. # Polygon interiors selection
  2616. self.poly_int_cb = FCCheckBox(_("Interiors"))
  2617. self.poly_int_cb.setToolTip(
  2618. _("When checked the user can select interiors of a polygon.\n"
  2619. "(holes in the polygon).")
  2620. )
  2621. self.grid3.addWidget(self.poly_int_cb, 33, 0)
  2622. self.poly_int_cb.hide()
  2623. # Area Selection shape
  2624. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  2625. self.area_shape_label.setToolTip(
  2626. _("The kind of selection shape used for area selection.")
  2627. )
  2628. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  2629. {'label': _("Polygon"), 'value': 'polygon'}])
  2630. self.grid3.addWidget(self.area_shape_label, 35, 0)
  2631. self.grid3.addWidget(self.area_shape_radio, 35, 1)
  2632. self.area_shape_label.hide()
  2633. self.area_shape_radio.hide()
  2634. separator_line = QtWidgets.QFrame()
  2635. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2636. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2637. self.grid3.addWidget(separator_line, 36, 0, 1, 2)
  2638. self.generate_iso_button = QtWidgets.QPushButton("%s" % _("Generate Isolation Geometry"))
  2639. self.generate_iso_button.setStyleSheet("""
  2640. QPushButton
  2641. {
  2642. font-weight: bold;
  2643. }
  2644. """)
  2645. self.generate_iso_button.setToolTip(
  2646. _("Create a Geometry object with toolpaths to cut \n"
  2647. "isolation outside, inside or on both sides of the\n"
  2648. "object. For a Gerber object outside means outside\n"
  2649. "of the Gerber feature and inside means inside of\n"
  2650. "the Gerber feature, if possible at all. This means\n"
  2651. "that only if the Gerber feature has openings inside, they\n"
  2652. "will be isolated. If what is wanted is to cut isolation\n"
  2653. "inside the actual Gerber feature, use a negative tool\n"
  2654. "diameter above.")
  2655. )
  2656. self.tools_box.addWidget(self.generate_iso_button)
  2657. self.create_buffer_button = QtWidgets.QPushButton(_('Buffer Solid Geometry'))
  2658. self.create_buffer_button.setToolTip(
  2659. _("This button is shown only when the Gerber file\n"
  2660. "is loaded without buffering.\n"
  2661. "Clicking this will create the buffered geometry\n"
  2662. "required for isolation.")
  2663. )
  2664. self.tools_box.addWidget(self.create_buffer_button)
  2665. self.tools_box.addStretch()
  2666. # ## Reset Tool
  2667. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  2668. self.reset_button.setToolTip(
  2669. _("Will reset the tool parameters.")
  2670. )
  2671. self.reset_button.setStyleSheet("""
  2672. QPushButton
  2673. {
  2674. font-weight: bold;
  2675. }
  2676. """)
  2677. self.tools_box.addWidget(self.reset_button)
  2678. # ############################ FINSIHED GUI ###################################
  2679. # #############################################################################
  2680. def confirmation_message(self, accepted, minval, maxval):
  2681. if accepted is False:
  2682. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2683. self.decimals,
  2684. minval,
  2685. self.decimals,
  2686. maxval), False)
  2687. else:
  2688. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2689. def confirmation_message_int(self, accepted, minval, maxval):
  2690. if accepted is False:
  2691. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2692. (_("Edited value is out of range"), minval, maxval), False)
  2693. else:
  2694. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)