ToolIsolation.py 152 KB

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