ToolIsolation.py 156 KB

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