ToolIsolation.py 148 KB

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