ToolIsolation.py 148 KB

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