ToolIsolation.py 147 KB

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