ToolIsolation.py 154 KB

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