ToolIsolation.py 146 KB

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