ToolNCC.py 200 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified by: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # 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
  11. from appParsers.ParseGerber import Gerber
  12. from camlib import grace
  13. from copy import deepcopy
  14. import numpy as np
  15. import math
  16. from shapely.geometry import base
  17. from shapely.ops import cascaded_union
  18. from shapely.geometry import MultiPolygon, Polygon, MultiLineString, LineString, LinearRing
  19. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  20. import logging
  21. import traceback
  22. import gettext
  23. import appTranslation as fcTranslate
  24. import builtins
  25. fcTranslate.apply_language('strings')
  26. if '_' not in builtins.__dict__:
  27. _ = gettext.gettext
  28. log = logging.getLogger('base')
  29. class NonCopperClear(AppTool, Gerber):
  30. def __init__(self, app):
  31. self.app = app
  32. self.decimals = self.app.decimals
  33. AppTool.__init__(self, app)
  34. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  35. # #############################################################################
  36. # ######################### Tool GUI ##########################################
  37. # #############################################################################
  38. self.ui = NccUI(layout=self.layout, app=self.app)
  39. self.toolName = self.ui.toolName
  40. # #############################################################################
  41. # ###################### Setup CONTEXT MENU ###################################
  42. # #############################################################################
  43. self.ui.tools_table.setupContextMenu()
  44. self.ui.tools_table.addContextMenu(
  45. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  46. )
  47. self.ui.tools_table.addContextMenu(
  48. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  49. )
  50. self.ui.tools_table.addContextMenu(
  51. _("Delete"), lambda:
  52. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  53. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  54. )
  55. # #############################################################################
  56. # ########################## VARIABLES ########################################
  57. # #############################################################################
  58. self.units = ''
  59. self.ncc_tools = {}
  60. self.tooluid = 0
  61. # store here the default data for Geometry Data
  62. self.default_data = {}
  63. self.obj_name = ""
  64. self.ncc_obj = None
  65. self.sel_rect = []
  66. self.bound_obj_name = ""
  67. self.bound_obj = None
  68. self.ncc_dia_list = []
  69. self.iso_dia_list = []
  70. self.has_offset = None
  71. self.o_name = None
  72. self.overlap = None
  73. self.connect = None
  74. self.contour = None
  75. self.rest = None
  76. self.first_click = False
  77. self.cursor_pos = None
  78. self.mouse_is_dragging = False
  79. # store here the points for the "Polygon" area selection shape
  80. self.points = []
  81. # set this as True when in middle of drawing a "Polygon" area selection shape
  82. # it is made False by first click to signify that the shape is complete
  83. self.poly_drawn = False
  84. self.mm = None
  85. self.mr = None
  86. self.kp = None
  87. # disconnect flags
  88. self.area_sel_disconnect_flag = False
  89. # store here solid_geometry when there are tool with isolation job
  90. self.solid_geometry = []
  91. self.select_method = None
  92. self.tool_type_item_options = []
  93. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  94. self.tooldia = None
  95. self.form_fields = {
  96. "tools_nccoperation": self.ui.op_radio,
  97. "tools_nccoverlap": self.ui.ncc_overlap_entry,
  98. "tools_nccmargin": self.ui.ncc_margin_entry,
  99. "tools_nccmethod": self.ui.ncc_method_combo,
  100. "tools_nccconnect": self.ui.ncc_connect_cb,
  101. "tools_ncccontour": self.ui.ncc_contour_cb,
  102. "tools_ncc_offset_choice": self.ui.ncc_choice_offset_cb,
  103. "tools_ncc_offset_value": self.ui.ncc_offset_spinner,
  104. "tools_nccmilling_type": self.ui.milling_type_radio
  105. }
  106. self.name2option = {
  107. "n_operation": "tools_nccoperation",
  108. "n_overlap": "tools_nccoverlap",
  109. "n_margin": "tools_nccmargin",
  110. "n_method": "tools_nccmethod",
  111. "n_connect": "tools_nccconnect",
  112. "n_contour": "tools_ncccontour",
  113. "n_offset": "tools_ncc_offset_choice",
  114. "n_offset_value": "tools_ncc_offset_value",
  115. "n_milling_type": "tools_nccmilling_type",
  116. }
  117. self.old_tool_dia = None
  118. self.connect_signals_at_init()
  119. def install(self, icon=None, separator=None, **kwargs):
  120. AppTool.install(self, icon, separator, shortcut='Alt+N', **kwargs)
  121. def run(self, toggle=True):
  122. self.app.defaults.report_usage("ToolNonCopperClear()")
  123. log.debug("ToolNCC().run() was launched ...")
  124. if toggle:
  125. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  126. if self.app.ui.splitter.sizes()[0] == 0:
  127. self.app.ui.splitter.setSizes([1, 1])
  128. else:
  129. try:
  130. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  131. # if tab is populated with the tool but it does not have the focus, focus on it
  132. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  133. # focus on Tool Tab
  134. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  135. else:
  136. self.app.ui.splitter.setSizes([0, 1])
  137. except AttributeError:
  138. pass
  139. else:
  140. if self.app.ui.splitter.sizes()[0] == 0:
  141. self.app.ui.splitter.setSizes([1, 1])
  142. AppTool.run(self)
  143. self.set_tool_ui()
  144. # reset those objects on a new run
  145. self.ncc_obj = None
  146. self.bound_obj = None
  147. self.obj_name = ''
  148. self.bound_obj_name = ''
  149. self.build_ui()
  150. # all the tools are selected by default
  151. # self.ui.tools_table.selectColumn(0)
  152. self.ui.tools_table.selectAll()
  153. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  154. def connect_signals_at_init(self):
  155. # #############################################################################
  156. # ############################ SIGNALS ########################################
  157. # #############################################################################
  158. self.ui.addtool_btn.clicked.connect(self.on_tool_add)
  159. self.ui.addtool_entry.returnPressed.connect(self.on_tooldia_updated)
  160. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  161. self.ui.generate_ncc_button.clicked.connect(self.on_ncc_click)
  162. self.ui.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  163. self.ui.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  164. self.ui.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  165. self.ui.op_radio.activated_custom.connect(self.on_operation_change)
  166. self.ui.reference_combo_type.currentIndexChanged.connect(self.on_reference_combo_changed)
  167. self.ui.select_combo.currentIndexChanged.connect(self.on_toggle_reference)
  168. self.ui.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  169. self.ui.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  170. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_index_changed)
  171. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  172. self.ui.addtool_from_db_btn.clicked.connect(self.on_ncc_tool_add_from_db_clicked)
  173. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  174. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  175. self.app.cleanup.connect(self.set_tool_ui)
  176. def on_type_obj_index_changed(self, val):
  177. obj_type = 0 if val == 'gerber' else 2
  178. self.ui.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  179. self.ui.object_combo.setCurrentIndex(0)
  180. self.ui.object_combo.obj_type = {
  181. "gerber": "Gerber", "geometry": "Geometry"
  182. }[self.ui.type_obj_radio.get_value()]
  183. def on_operation_change(self, val):
  184. if val == 'iso':
  185. self.ui.milling_type_label.setEnabled(True)
  186. self.ui.milling_type_radio.setEnabled(True)
  187. else:
  188. self.ui.milling_type_label.setEnabled(False)
  189. self.ui.milling_type_radio.setEnabled(False)
  190. current_row = self.ui.tools_table.currentRow()
  191. try:
  192. current_uid = int(self.ui.tools_table.item(current_row, 3).text())
  193. self.ncc_tools[current_uid]['data']['tools_nccoperation'] = val
  194. # TODO got a crash here, a KeyError exception; need to see it again and find out the why
  195. except AttributeError:
  196. return
  197. def on_toggle_all_rows(self):
  198. """
  199. will toggle the selection of all rows in Tools table
  200. :return:
  201. """
  202. sel_model = self.ui.tools_table.selectionModel()
  203. sel_indexes = sel_model.selectedIndexes()
  204. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  205. sel_rows = set()
  206. for idx in sel_indexes:
  207. sel_rows.add(idx.row())
  208. if len(sel_rows) == self.ui.tools_table.rowCount():
  209. self.ui.tools_table.clearSelection()
  210. else:
  211. self.ui.tools_table.selectAll()
  212. self.update_ui()
  213. def on_row_selection_change(self):
  214. self.update_ui()
  215. def update_ui(self):
  216. self.blockSignals(True)
  217. sel_rows = set()
  218. table_items = self.ui.tools_table.selectedItems()
  219. if table_items:
  220. for it in table_items:
  221. sel_rows.add(it.row())
  222. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  223. if not sel_rows or len(sel_rows) == 0:
  224. self.ui.generate_ncc_button.setDisabled(True)
  225. self.ui.tool_data_label.setText(
  226. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  227. )
  228. self.blockSignals(False)
  229. return
  230. else:
  231. self.ui.generate_ncc_button.setDisabled(False)
  232. for current_row in sel_rows:
  233. # populate the form with the data from the tool associated with the row parameter
  234. try:
  235. item = self.ui.tools_table.item(current_row, 3)
  236. if item is not None:
  237. tooluid = int(item.text())
  238. else:
  239. return
  240. except Exception as e:
  241. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  242. return
  243. # update the QLabel that shows for which Tool we have the parameters in the UI form
  244. if len(sel_rows) == 1:
  245. cr = current_row + 1
  246. self.ui.tool_data_label.setText(
  247. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), cr)
  248. )
  249. try:
  250. # set the form with data from the newly selected tool
  251. for tooluid_key, tooluid_value in list(self.ncc_tools.items()):
  252. if int(tooluid_key) == tooluid:
  253. for key, value in tooluid_value.items():
  254. if key == 'data':
  255. self.storage_to_form(tooluid_value['data'])
  256. except Exception as e:
  257. log.debug("NonCopperClear ---> update_ui() " + str(e))
  258. else:
  259. self.ui.tool_data_label.setText(
  260. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  261. )
  262. self.blockSignals(False)
  263. def storage_to_form(self, dict_storage):
  264. for form_key in self.form_fields:
  265. for storage_key in dict_storage:
  266. if form_key == storage_key:
  267. try:
  268. self.form_fields[form_key].set_value(dict_storage[form_key])
  269. except Exception as e:
  270. log.debug("NonCopperClear.storage_to_form() --> %s" % str(e))
  271. pass
  272. def form_to_storage(self):
  273. if self.ui.tools_table.rowCount() == 0:
  274. # there is no tool in tool table so we can't save the GUI elements values to storage
  275. return
  276. self.blockSignals(True)
  277. widget_changed = self.sender()
  278. wdg_objname = widget_changed.objectName()
  279. option_changed = self.name2option[wdg_objname]
  280. # row = self.ui.tools_table.currentRow()
  281. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  282. for row in rows:
  283. if row < 0:
  284. row = 0
  285. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  286. for tooluid_key, tooluid_val in self.ncc_tools.items():
  287. if int(tooluid_key) == tooluid_item:
  288. new_option_value = self.form_fields[option_changed].get_value()
  289. if option_changed in tooluid_val:
  290. tooluid_val[option_changed] = new_option_value
  291. if option_changed in tooluid_val['data']:
  292. tooluid_val['data'][option_changed] = new_option_value
  293. self.blockSignals(False)
  294. def on_apply_param_to_all_clicked(self):
  295. if self.ui.tools_table.rowCount() == 0:
  296. # there is no tool in tool table so we can't save the GUI elements values to storage
  297. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  298. return
  299. self.blockSignals(True)
  300. row = self.ui.tools_table.currentRow()
  301. if row < 0:
  302. row = 0
  303. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  304. temp_tool_data = {}
  305. for tooluid_key, tooluid_val in self.ncc_tools.items():
  306. if int(tooluid_key) == tooluid_item:
  307. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  308. # the current row in the tool table
  309. temp_tool_data = tooluid_val['data']
  310. break
  311. for tooluid_key, tooluid_val in self.ncc_tools.items():
  312. tooluid_val['data'] = deepcopy(temp_tool_data)
  313. # store all the data associated with the row parameter to the self.tools storage
  314. # tooldia_item = float(self.ui.tools_table.item(row, 1).text())
  315. # type_item = self.ui.tools_table.cellWidget(row, 2).currentText()
  316. # operation_type_item = self.ui.tools_table.cellWidget(row, 4).currentText()
  317. #
  318. # nccoffset_item = self.ncc_choice_offset_cb.get_value()
  319. # nccoffset_value_item = float(self.ncc_offset_spinner.get_value())
  320. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  321. # temp_tools = {}
  322. # temp_dia = {}
  323. # temp_data = {}
  324. #
  325. # for tooluid_key, tooluid_value in self.ncc_tools.items():
  326. # for key, value in tooluid_value.items():
  327. # if key == 'data':
  328. # # update the 'data' section
  329. # for data_key in tooluid_value[key].keys():
  330. # for form_key, form_value in self.form_fields.items():
  331. # if form_key == data_key:
  332. # temp_data[data_key] = form_value.get_value()
  333. # # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  334. # # updated from self.app.defaults
  335. # if data_key not in self.form_fields:
  336. # temp_data[data_key] = value[data_key]
  337. # temp_dia[key] = deepcopy(temp_data)
  338. # temp_data.clear()
  339. #
  340. # elif key == 'solid_geometry':
  341. # temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  342. # else:
  343. # temp_dia[key] = deepcopy(value)
  344. #
  345. # temp_tools[tooluid_key] = deepcopy(temp_dia)
  346. #
  347. # self.ncc_tools.clear()
  348. # self.ncc_tools = deepcopy(temp_tools)
  349. # temp_tools.clear()
  350. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  351. self.blockSignals(False)
  352. def on_add_tool_by_key(self):
  353. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  354. text='%s:' % _('Enter a Tool Diameter'),
  355. min=0.0001, max=9999.9999, decimals=self.decimals)
  356. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  357. val, ok = tool_add_popup.get_value()
  358. if ok:
  359. if float(val) == 0:
  360. self.app.inform.emit('[WARNING_NOTCL] %s' %
  361. _("Please enter a tool diameter with non-zero value, in Float format."))
  362. return
  363. self.on_tool_add(dia=float(val))
  364. else:
  365. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  366. def set_tool_ui(self):
  367. self.units = self.app.defaults['units'].upper()
  368. self.old_tool_dia = self.app.defaults["tools_nccnewdia"]
  369. self.ui.tools_frame.show()
  370. # use the current selected object and make it visible in the NCC object combobox
  371. sel_list = self.app.collection.get_selected()
  372. if len(sel_list) == 1:
  373. active = self.app.collection.get_active()
  374. kind = active.kind
  375. if kind == 'gerber':
  376. self.ui.type_obj_radio.set_value('gerber')
  377. else:
  378. self.ui.type_obj_radio.set_value('geometry')
  379. # run those once so the obj_type attribute is updated for the FCComboboxes
  380. # so the last loaded object is displayed
  381. self.on_type_obj_index_changed(val=kind)
  382. self.on_reference_combo_changed()
  383. self.ui.object_combo.set_value(active.options['name'])
  384. else:
  385. kind = 'gerber'
  386. self.ui.type_obj_radio.set_value('gerber')
  387. # run those once so the obj_type attribute is updated for the FCComboboxes
  388. # so the last loaded object is displayed
  389. self.on_type_obj_index_changed(val=kind)
  390. self.on_reference_combo_changed()
  391. self.ui.op_radio.set_value(self.app.defaults["tools_nccoperation"])
  392. self.ui.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  393. self.ui.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  394. self.ui.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  395. self.ui.ncc_method_combo.set_value(self.app.defaults["tools_nccmethod"])
  396. self.ui.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  397. self.ui.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  398. self.ui.ncc_choice_offset_cb.set_value(self.app.defaults["tools_ncc_offset_choice"])
  399. self.ui.ncc_offset_spinner.set_value(self.app.defaults["tools_ncc_offset_value"])
  400. self.ui.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  401. self.ui.rest_ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  402. self.ui.rest_ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  403. self.ui.rest_ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  404. self.ui.rest_ncc_choice_offset_cb.set_value(self.app.defaults["tools_ncc_offset_choice"])
  405. self.ui.rest_ncc_offset_spinner.set_value(self.app.defaults["tools_ncc_offset_value"])
  406. self.ui.select_combo.set_value(self.app.defaults["tools_nccref"])
  407. self.ui.area_shape_radio.set_value(self.app.defaults["tools_ncc_area_shape"])
  408. self.ui.milling_type_radio.set_value(self.app.defaults["tools_nccmilling_type"])
  409. self.ui.cutz_entry.set_value(self.app.defaults["tools_ncccutz"])
  410. self.ui.tool_type_radio.set_value(self.app.defaults["tools_ncctool_type"])
  411. self.ui.tipdia_entry.set_value(self.app.defaults["tools_ncctipdia"])
  412. self.ui.tipangle_entry.set_value(self.app.defaults["tools_ncctipangle"])
  413. self.ui.addtool_entry.set_value(self.app.defaults["tools_nccnewdia"])
  414. self.old_tool_dia = self.app.defaults["tools_nccnewdia"]
  415. self.on_tool_type(val=self.ui.tool_type_radio.get_value())
  416. # init the working variables
  417. self.default_data.clear()
  418. self.default_data = {
  419. "name": '_ncc',
  420. "plot": self.app.defaults["geometry_plot"],
  421. "cutz": float(self.app.defaults["geometry_cutz"]),
  422. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  423. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  424. "travelz": self.app.defaults["geometry_travelz"],
  425. "feedrate": self.app.defaults["geometry_feedrate"],
  426. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  427. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  428. "dwell": self.app.defaults["geometry_dwell"],
  429. "dwelltime": self.app.defaults["geometry_dwelltime"],
  430. "multidepth": self.app.defaults["geometry_multidepth"],
  431. "ppname_g": self.app.defaults["geometry_ppname_g"],
  432. "depthperpass": self.app.defaults["geometry_depthperpass"],
  433. "extracut": self.app.defaults["geometry_extracut"],
  434. "extracut_length": self.app.defaults["geometry_extracut_length"],
  435. "toolchange": self.app.defaults["geometry_toolchange"],
  436. "toolchangez": self.app.defaults["geometry_toolchangez"],
  437. "endz": self.app.defaults["geometry_endz"],
  438. "endxy": self.app.defaults["geometry_endxy"],
  439. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  440. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  441. "startz": self.app.defaults["geometry_startz"],
  442. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  443. "area_shape": self.app.defaults["geometry_area_shape"],
  444. "area_strategy": self.app.defaults["geometry_area_strategy"],
  445. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  446. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  447. "tools_nccmargin": self.app.defaults["tools_nccmargin"],
  448. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  449. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  450. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  451. "tools_nccoverlap": self.app.defaults["tools_nccoverlap"],
  452. "tools_nccrest": self.app.defaults["tools_nccrest"],
  453. "tools_nccref": self.app.defaults["tools_nccref"],
  454. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  455. "tools_ncc_offset_value": self.app.defaults["tools_ncc_offset_value"],
  456. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"]
  457. }
  458. try:
  459. dias = [float(self.app.defaults["tools_ncctools"])]
  460. except (ValueError, TypeError):
  461. try:
  462. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  463. except AttributeError:
  464. dias = self.app.defaults["tools_ncctools"]
  465. except Exception:
  466. dias = []
  467. self.tooluid = 0
  468. self.ncc_tools.clear()
  469. for tool_dia in dias:
  470. self.tooluid += 1
  471. self.ncc_tools.update({
  472. int(self.tooluid): {
  473. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  474. 'offset': 'Path',
  475. 'offset_value': 0.0,
  476. 'type': 'Iso',
  477. 'tool_type': self.app.defaults["tools_ncctool_type"],
  478. 'data': deepcopy(self.default_data),
  479. 'solid_geometry': []
  480. }
  481. })
  482. self.obj_name = ""
  483. self.ncc_obj = None
  484. self.bound_obj_name = ""
  485. self.bound_obj = None
  486. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  487. self.units = self.app.defaults['units'].upper()
  488. self.first_click = False
  489. self.cursor_pos = None
  490. self.mouse_is_dragging = False
  491. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  492. if prog_plot:
  493. self.temp_shapes.clear(update=True)
  494. self.sel_rect = []
  495. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  496. def rebuild_ui(self):
  497. # read the table tools uid
  498. current_uid_list = []
  499. for row in range(self.ui.tools_table.rowCount()):
  500. uid = int(self.ui.tools_table.item(row,3).text())
  501. current_uid_list.append(uid)
  502. new_tools = {}
  503. new_uid = 1
  504. for current_uid in current_uid_list:
  505. new_tools[new_uid] = deepcopy(self.ncc_tools[current_uid])
  506. new_uid += 1
  507. self.ncc_tools = new_tools
  508. # the tools table changed therefore we need to rebuild it
  509. QtCore.QTimer.singleShot(20, self.build_ui)
  510. def build_ui(self):
  511. self.ui_disconnect()
  512. # updated units
  513. self.units = self.app.defaults['units'].upper()
  514. sorted_tools = []
  515. for k, v in self.ncc_tools.items():
  516. if self.units == "IN":
  517. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  518. else:
  519. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  520. order = self.ui.ncc_order_radio.get_value()
  521. if order == 'fwd':
  522. sorted_tools.sort(reverse=False)
  523. elif order == 'rev':
  524. sorted_tools.sort(reverse=True)
  525. else:
  526. pass
  527. n = len(sorted_tools)
  528. self.ui.tools_table.setRowCount(n)
  529. tool_id = 0
  530. for tool_sorted in sorted_tools:
  531. for tooluid_key, tooluid_value in self.ncc_tools.items():
  532. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  533. tool_id += 1
  534. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  535. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  536. row_no = tool_id - 1
  537. self.ui.tools_table.setItem(row_no, 0, id_) # Tool name/id
  538. # Make sure that the drill diameter when in MM is with no more than self.decimals decimals
  539. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  540. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  541. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  542. tool_type_item = FCComboBox()
  543. tool_type_item.addItems(self.tool_type_item_options)
  544. idx = tool_type_item.findText(tooluid_value['tool_type'])
  545. tool_type_item.setCurrentIndex(idx)
  546. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  547. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  548. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  549. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  550. # make the diameter column editable
  551. for row in range(tool_id):
  552. self.ui.tools_table.item(row, 1).setFlags(
  553. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  554. self.ui.tools_table.resizeColumnsToContents()
  555. self.ui.tools_table.resizeRowsToContents()
  556. vertical_header = self.ui.tools_table.verticalHeader()
  557. vertical_header.hide()
  558. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  559. horizontal_header = self.ui.tools_table.horizontalHeader()
  560. horizontal_header.setMinimumSectionSize(10)
  561. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  562. horizontal_header.resizeSection(0, 20)
  563. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  564. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  565. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  566. self.ui_connect()
  567. # set the text on tool_data_label after loading the object
  568. sel_rows = set()
  569. sel_items = self.ui.tools_table.selectedItems()
  570. for it in sel_items:
  571. sel_rows.add(it.row())
  572. if len(sel_rows) > 1:
  573. self.ui.tool_data_label.setText(
  574. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  575. )
  576. def ui_connect(self):
  577. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  578. # rows selected
  579. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  580. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  581. for row in range(self.ui.tools_table.rowCount()):
  582. try:
  583. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  584. except AttributeError:
  585. pass
  586. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type)
  587. for opt in self.form_fields:
  588. current_widget = self.form_fields[opt]
  589. if isinstance(current_widget, FCCheckBox):
  590. current_widget.stateChanged.connect(self.form_to_storage)
  591. if isinstance(current_widget, RadioSet):
  592. current_widget.activated_custom.connect(self.form_to_storage)
  593. elif isinstance(current_widget, FCDoubleSpinner):
  594. current_widget.returnPressed.connect(self.form_to_storage)
  595. elif isinstance(current_widget, FCComboBox):
  596. current_widget.currentIndexChanged.connect(self.form_to_storage)
  597. self.ui.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  598. self.ui.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  599. def ui_disconnect(self):
  600. try:
  601. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  602. self.ui.tools_table.itemChanged.disconnect()
  603. except (TypeError, AttributeError):
  604. pass
  605. try:
  606. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  607. self.ui.tool_type_radio.activated_custom.disconnect()
  608. except (TypeError, AttributeError):
  609. pass
  610. for row in range(self.ui.tools_table.rowCount()):
  611. try:
  612. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  613. except (TypeError, AttributeError):
  614. pass
  615. for opt in self.form_fields:
  616. current_widget = self.form_fields[opt]
  617. if isinstance(current_widget, FCCheckBox):
  618. try:
  619. current_widget.stateChanged.disconnect(self.form_to_storage)
  620. except (TypeError, ValueError):
  621. pass
  622. if isinstance(current_widget, RadioSet):
  623. try:
  624. current_widget.activated_custom.disconnect(self.form_to_storage)
  625. except (TypeError, ValueError):
  626. pass
  627. elif isinstance(current_widget, FCDoubleSpinner):
  628. try:
  629. current_widget.returnPressed.disconnect(self.form_to_storage)
  630. except (TypeError, ValueError):
  631. pass
  632. elif isinstance(current_widget, FCComboBox):
  633. try:
  634. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  635. except (TypeError, ValueError):
  636. pass
  637. try:
  638. self.ui.ncc_rest_cb.stateChanged.disconnect()
  639. except (TypeError, ValueError):
  640. pass
  641. try:
  642. self.ui.ncc_order_radio.activated_custom[str].disconnect()
  643. except (TypeError, ValueError):
  644. pass
  645. # rows selected
  646. try:
  647. self.ui.tools_table.clicked.disconnect()
  648. except (TypeError, AttributeError):
  649. pass
  650. try:
  651. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  652. except (TypeError, AttributeError):
  653. pass
  654. def on_tooldia_updated(self):
  655. if self.ui.tool_type_radio.get_value() == 'C1':
  656. self.old_tool_dia = self.ui.addtool_entry.get_value()
  657. def on_reference_combo_changed(self):
  658. obj_type = self.ui.reference_combo_type.currentIndex()
  659. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  660. self.ui.reference_combo.setCurrentIndex(0)
  661. self.ui.reference_combo.obj_type = {
  662. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  663. }[self.ui.reference_combo_type.get_value()]
  664. def on_toggle_reference(self):
  665. sel_combo = self.ui.select_combo.get_value()
  666. if sel_combo == _("Itself"):
  667. self.ui.reference_combo.hide()
  668. self.ui.reference_combo_label.hide()
  669. self.ui.reference_combo_type.hide()
  670. self.ui.reference_combo_type_label.hide()
  671. self.ui.area_shape_label.hide()
  672. self.ui.area_shape_radio.hide()
  673. # disable rest-machining for area painting
  674. self.ui.ncc_rest_cb.setDisabled(False)
  675. elif sel_combo == _("Area Selection"):
  676. self.ui.reference_combo.hide()
  677. self.ui.reference_combo_label.hide()
  678. self.ui.reference_combo_type.hide()
  679. self.ui.reference_combo_type_label.hide()
  680. self.ui.area_shape_label.show()
  681. self.ui.area_shape_radio.show()
  682. # disable rest-machining for area painting
  683. # self.ui.ncc_rest_cb.set_value(False)
  684. # self.ui.ncc_rest_cb.setDisabled(True)
  685. else:
  686. self.ui.reference_combo.show()
  687. self.ui.reference_combo_label.show()
  688. self.ui.reference_combo_type.show()
  689. self.ui.reference_combo_type_label.show()
  690. self.ui.area_shape_label.hide()
  691. self.ui.area_shape_radio.hide()
  692. # disable rest-machining for area painting
  693. self.ui.ncc_rest_cb.setDisabled(False)
  694. def on_order_changed(self, order):
  695. if order != 'no':
  696. self.build_ui()
  697. def on_rest_machining_check(self, state):
  698. if state:
  699. self.ui.ncc_order_radio.set_value('rev')
  700. self.ui.ncc_order_label.setDisabled(True)
  701. self.ui.ncc_order_radio.setDisabled(True)
  702. self.ui.nccmarginlabel.hide()
  703. self.ui.ncc_margin_entry.hide()
  704. self.ui.ncc_connect_cb.hide()
  705. self.ui.ncc_contour_cb.hide()
  706. self.ui.ncc_choice_offset_cb.hide()
  707. self.ui.ncc_offset_spinner.hide()
  708. self.ui.rest_nccmarginlabel.show()
  709. self.ui.rest_ncc_margin_entry.show()
  710. self.ui.rest_ncc_connect_cb.show()
  711. self.ui.rest_ncc_contour_cb.show()
  712. self.ui.rest_ncc_choice_offset_cb.show()
  713. self.ui.rest_ncc_offset_spinner.show()
  714. else:
  715. self.ui.ncc_order_label.setDisabled(False)
  716. self.ui.ncc_order_radio.setDisabled(False)
  717. self.ui.nccmarginlabel.show()
  718. self.ui.ncc_margin_entry.show()
  719. self.ui.ncc_connect_cb.show()
  720. self.ui.ncc_contour_cb.show()
  721. self.ui.ncc_choice_offset_cb.show()
  722. self.ui.ncc_offset_spinner.show()
  723. self.ui.rest_nccmarginlabel.hide()
  724. self.ui.rest_ncc_margin_entry.hide()
  725. self.ui.rest_ncc_connect_cb.hide()
  726. self.ui.rest_ncc_contour_cb.hide()
  727. self.ui.rest_ncc_choice_offset_cb.hide()
  728. self.ui.rest_ncc_offset_spinner.hide()
  729. def on_tooltable_cellwidget_change(self):
  730. cw = self.sender()
  731. assert isinstance(cw, QtWidgets.QComboBox),\
  732. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  733. cw_index = self.ui.tools_table.indexAt(cw.pos())
  734. cw_row = cw_index.row()
  735. cw_col = cw_index.column()
  736. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  737. # if the sender is in the column with index 2 then we update the tool_type key
  738. if cw_col == 2:
  739. tt = cw.currentText()
  740. typ = 'Iso' if tt == 'V' else "Rough"
  741. self.ncc_tools[current_uid].update({
  742. 'type': typ,
  743. 'tool_type': tt,
  744. })
  745. def on_tool_type(self, val):
  746. if val == 'V':
  747. self.ui.addtool_entry_lbl.setDisabled(True)
  748. self.ui.addtool_entry.setDisabled(True)
  749. self.ui.tipdialabel.show()
  750. self.ui.tipdia_entry.show()
  751. self.ui.tipanglelabel.show()
  752. self.ui.tipangle_entry.show()
  753. self.on_calculate_tooldia()
  754. else:
  755. self.ui.addtool_entry_lbl.setDisabled(False)
  756. self.ui.addtool_entry.setDisabled(False)
  757. self.ui.tipdialabel.hide()
  758. self.ui.tipdia_entry.hide()
  759. self.ui.tipanglelabel.hide()
  760. self.ui.tipangle_entry.hide()
  761. self.ui.addtool_entry.set_value(self.old_tool_dia)
  762. def on_calculate_tooldia(self):
  763. if self.ui.tool_type_radio.get_value() == 'V':
  764. tip_dia = float(self.ui.tipdia_entry.get_value())
  765. tip_angle = float(self.ui.tipangle_entry.get_value()) / 2.0
  766. cut_z = float(self.ui.cutz_entry.get_value())
  767. cut_z = -cut_z if cut_z < 0 else cut_z
  768. # calculated tool diameter so the cut_z parameter is obeyed
  769. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  770. # update the default_data so it is used in the ncc_tools dict
  771. self.default_data.update({
  772. "vtipdia": tip_dia,
  773. "vtipangle": (tip_angle * 2),
  774. })
  775. self.ui.addtool_entry.set_value(tool_dia)
  776. return tool_dia
  777. else:
  778. return float(self.ui.addtool_entry.get_value())
  779. def on_tool_add(self, dia=None, muted=None):
  780. self.blockSignals(True)
  781. self.units = self.app.defaults['units'].upper()
  782. if dia:
  783. tool_dia = dia
  784. else:
  785. tool_dia = self.on_calculate_tooldia()
  786. if tool_dia is None:
  787. self.build_ui()
  788. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  789. return
  790. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  791. if tool_dia == 0:
  792. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  793. "in Float format."))
  794. return
  795. # construct a list of all 'tooluid' in the self.tools
  796. tool_uid_list = []
  797. for tooluid_key in self.ncc_tools:
  798. tool_uid_item = int(tooluid_key)
  799. tool_uid_list.append(tool_uid_item)
  800. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  801. if not tool_uid_list:
  802. max_uid = 0
  803. else:
  804. max_uid = max(tool_uid_list)
  805. self.tooluid = int(max_uid + 1)
  806. tool_dias = []
  807. for k, v in self.ncc_tools.items():
  808. for tool_v in v.keys():
  809. if tool_v == 'tooldia':
  810. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  811. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  812. if muted is None:
  813. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  814. # self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  815. self.blockSignals(False)
  816. return
  817. else:
  818. if muted is None:
  819. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  820. self.ncc_tools.update({
  821. int(self.tooluid): {
  822. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  823. 'offset': 'Path',
  824. 'offset_value': 0.0,
  825. 'type': 'Iso',
  826. 'tool_type': self.app.defaults["tools_ncctool_type"],
  827. 'data': deepcopy(self.default_data),
  828. 'solid_geometry': []
  829. }
  830. })
  831. self.blockSignals(False)
  832. self.build_ui()
  833. # select the tool just added
  834. for row in range(self.ui.tools_table.rowCount()):
  835. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  836. self.ui.tools_table.selectRow(row)
  837. break
  838. def on_tool_edit(self, item):
  839. self.blockSignals(True)
  840. edited_row = item.row()
  841. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  842. tool_dias = []
  843. try:
  844. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  845. except ValueError:
  846. # try to convert comma to decimal point. if it's still not working error message and return
  847. try:
  848. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  849. except ValueError:
  850. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  851. self.blockSignals(False)
  852. return
  853. for v in self.ncc_tools.values():
  854. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  855. # identify the tool that was edited and get it's tooluid
  856. if new_tool_dia not in tool_dias:
  857. self.ncc_tools[editeduid]['tooldia'] = deepcopy(float('%.*f' % (self.decimals, new_tool_dia)))
  858. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  859. self.blockSignals(False)
  860. self.build_ui()
  861. return
  862. # identify the old tool_dia and restore the text in tool table
  863. for k, v in self.ncc_tools.items():
  864. if k == editeduid:
  865. old_tool_dia = v['tooldia']
  866. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  867. restore_dia_item.setText(str(old_tool_dia))
  868. break
  869. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  870. self.blockSignals(False)
  871. self.build_ui()
  872. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  873. """
  874. Will delete a tool in the tool table
  875. :param rows_to_delete: which rows to delete; can be a list
  876. :param all_tools: delete all tools in the tool table
  877. :return:
  878. """
  879. self.blockSignals(True)
  880. deleted_tools_list = []
  881. if all_tools:
  882. self.ncc_tools.clear()
  883. self.blockSignals(False)
  884. self.build_ui()
  885. return
  886. if rows_to_delete:
  887. try:
  888. for row in rows_to_delete:
  889. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  890. deleted_tools_list.append(tooluid_del)
  891. except TypeError:
  892. tooluid_del = int(self.ui.tools_table.item(rows_to_delete, 3).text())
  893. deleted_tools_list.append(tooluid_del)
  894. for t in deleted_tools_list:
  895. self.ncc_tools.pop(t, None)
  896. self.blockSignals(False)
  897. self.build_ui()
  898. return
  899. try:
  900. if self.ui.tools_table.selectedItems():
  901. for row_sel in self.ui.tools_table.selectedItems():
  902. row = row_sel.row()
  903. if row < 0:
  904. continue
  905. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  906. deleted_tools_list.append(tooluid_del)
  907. for t in deleted_tools_list:
  908. self.ncc_tools.pop(t, None)
  909. except AttributeError:
  910. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  911. self.blockSignals(False)
  912. return
  913. except Exception as e:
  914. log.debug(str(e))
  915. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  916. self.blockSignals(False)
  917. self.build_ui()
  918. def on_ncc_click(self):
  919. """
  920. Slot for clicking signal
  921. :return: None
  922. """
  923. self.app.defaults.report_usage("on_ncc_click")
  924. self.first_click = False
  925. self.cursor_pos = None
  926. self.mouse_is_dragging = False
  927. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  928. if prog_plot:
  929. self.temp_shapes.clear(update=True)
  930. self.sel_rect = []
  931. obj_type = self.ui.type_obj_radio.get_value
  932. self.circle_steps = int(self.app.defaults["gerber_circle_steps"]) if obj_type == 'gerber' else \
  933. int(self.app.defaults["geometry_circle_steps"])
  934. self.obj_name = self.ui.object_combo.currentText()
  935. # Get source object.
  936. try:
  937. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  938. except Exception as e:
  939. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  940. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  941. if self.ncc_obj is None:
  942. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  943. return
  944. # use the selected tools in the tool table; get diameters for isolation
  945. self.iso_dia_list = []
  946. # use the selected tools in the tool table; get diameters for non-copper clear
  947. self.ncc_dia_list = []
  948. table_items = self.ui.tools_table.selectedItems()
  949. sel_rows = {t.row() for t in table_items}
  950. if len(sel_rows) > 0:
  951. for row in sel_rows:
  952. try:
  953. self.tooldia = float(self.ui.tools_table.item(row, 1).text())
  954. except ValueError:
  955. # try to convert comma to decimal point. if it's still not working error message and return
  956. try:
  957. self.tooldia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  958. except ValueError:
  959. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  960. continue
  961. # find out which tools is for isolation and which are for copper clearing
  962. for uid_k, uid_v in self.ncc_tools.items():
  963. if round(uid_v['tooldia'], self.decimals) == round(self.tooldia, self.decimals):
  964. if uid_v['data']['tools_nccoperation'] == "iso":
  965. self.iso_dia_list.append(self.tooldia)
  966. else:
  967. self.ncc_dia_list.append(self.tooldia)
  968. else:
  969. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  970. return
  971. self.o_name = '%s_ncc' % self.obj_name
  972. self.select_method = self.ui.select_combo.get_value()
  973. if self.select_method == _('Itself'):
  974. self.bound_obj_name = self.ui.object_combo.currentText()
  975. # Get source object.
  976. try:
  977. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  978. except Exception as e:
  979. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  980. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  981. self.clear_copper(ncc_obj=self.ncc_obj,
  982. ncctooldia=self.ncc_dia_list,
  983. isotooldia=self.iso_dia_list,
  984. outname=self.o_name,
  985. tools_storage=self.ncc_tools)
  986. elif self.select_method == _("Area Selection"):
  987. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  988. if self.app.is_legacy is False:
  989. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  990. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  991. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  992. else:
  993. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  994. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  995. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  996. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  997. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  998. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  999. # disconnect flags
  1000. self.area_sel_disconnect_flag = True
  1001. elif self.select_method == _("Reference Object"):
  1002. self.bound_obj_name = self.ui.reference_combo.currentText()
  1003. # Get source object.
  1004. try:
  1005. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1006. except Exception as e:
  1007. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1008. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1009. self.clear_copper(ncc_obj=self.ncc_obj,
  1010. sel_obj=self.bound_obj,
  1011. ncctooldia=self.ncc_dia_list,
  1012. isotooldia=self.iso_dia_list,
  1013. outname=self.o_name)
  1014. # To be called after clicking on the plot.
  1015. def on_mouse_release(self, event):
  1016. if self.app.is_legacy is False:
  1017. event_pos = event.pos
  1018. # event_is_dragging = event.is_dragging
  1019. right_button = 2
  1020. else:
  1021. event_pos = (event.xdata, event.ydata)
  1022. # event_is_dragging = self.app.plotcanvas.is_dragging
  1023. right_button = 3
  1024. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1025. if self.app.grid_status():
  1026. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1027. else:
  1028. curr_pos = (event_pos[0], event_pos[1])
  1029. x1, y1 = curr_pos[0], curr_pos[1]
  1030. shape_type = self.ui.area_shape_radio.get_value()
  1031. # do clear area only for left mouse clicks
  1032. if event.button == 1:
  1033. if shape_type == "square":
  1034. if self.first_click is False:
  1035. self.first_click = True
  1036. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  1037. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1038. if self.app.grid_status():
  1039. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1040. else:
  1041. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1042. self.app.delete_selection_shape()
  1043. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1044. pt1 = (x0, y0)
  1045. pt2 = (x1, y0)
  1046. pt3 = (x1, y1)
  1047. pt4 = (x0, y1)
  1048. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1049. self.sel_rect.append(new_rectangle)
  1050. # add a temporary shape on canvas
  1051. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1052. self.first_click = False
  1053. return
  1054. else:
  1055. self.points.append((x1, y1))
  1056. if len(self.points) > 1:
  1057. self.poly_drawn = True
  1058. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1059. return ""
  1060. elif event.button == right_button and self.mouse_is_dragging is False:
  1061. shape_type = self.ui.area_shape_radio.get_value()
  1062. if shape_type == "square":
  1063. self.first_click = False
  1064. else:
  1065. # if we finish to add a polygon
  1066. if self.poly_drawn is True:
  1067. try:
  1068. # try to add the point where we last clicked if it is not already in the self.points
  1069. last_pt = (x1, y1)
  1070. if last_pt != self.points[-1]:
  1071. self.points.append(last_pt)
  1072. except IndexError:
  1073. pass
  1074. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1075. if len(self.points) > 2:
  1076. self.delete_moving_selection_shape()
  1077. pol = Polygon(self.points)
  1078. # do not add invalid polygons even if they are drawn by utility geometry
  1079. if pol.is_valid:
  1080. self.sel_rect.append(pol)
  1081. self.draw_selection_shape_polygon(points=self.points)
  1082. self.app.inform.emit(
  1083. _("Zone added. Click to start adding next zone or right click to finish."))
  1084. self.points = []
  1085. self.poly_drawn = False
  1086. return
  1087. self.delete_tool_selection_shape()
  1088. if self.app.is_legacy is False:
  1089. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1090. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1091. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1092. else:
  1093. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1094. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1095. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1096. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1097. self.app.on_mouse_click_over_plot)
  1098. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1099. self.app.on_mouse_move_over_plot)
  1100. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1101. self.app.on_mouse_click_release_over_plot)
  1102. # disconnect flags
  1103. self.area_sel_disconnect_flag = False
  1104. if len(self.sel_rect) == 0:
  1105. return
  1106. self.sel_rect = cascaded_union(self.sel_rect)
  1107. self.clear_copper(ncc_obj=self.ncc_obj, sel_obj=self.bound_obj, ncctooldia=self.ncc_dia_list,
  1108. isotooldia=self.iso_dia_list, outname=self.o_name)
  1109. # called on mouse move
  1110. def on_mouse_move(self, event):
  1111. shape_type = self.ui.area_shape_radio.get_value()
  1112. if self.app.is_legacy is False:
  1113. event_pos = event.pos
  1114. event_is_dragging = event.is_dragging
  1115. # right_button = 2
  1116. else:
  1117. event_pos = (event.xdata, event.ydata)
  1118. event_is_dragging = self.app.plotcanvas.is_dragging
  1119. # right_button = 3
  1120. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1121. # detect mouse dragging motion
  1122. if event_is_dragging is True:
  1123. self.mouse_is_dragging = True
  1124. else:
  1125. self.mouse_is_dragging = False
  1126. # update the cursor position
  1127. if self.app.grid_status():
  1128. # Update cursor
  1129. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1130. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1131. symbol='++', edge_color=self.app.cursor_color_3D,
  1132. edge_width=self.app.defaults["global_cursor_width"],
  1133. size=self.app.defaults["global_cursor_size"])
  1134. if self.cursor_pos is None:
  1135. self.cursor_pos = (0, 0)
  1136. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1137. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1138. # # update the positions on status bar
  1139. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1140. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1141. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1142. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1143. units = self.app.defaults["units"].lower()
  1144. self.app.plotcanvas.text_hud.text = \
  1145. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1146. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1147. # draw the utility geometry
  1148. if shape_type == "square":
  1149. if self.first_click:
  1150. self.app.delete_selection_shape()
  1151. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1152. coords=(curr_pos[0], curr_pos[1]))
  1153. else:
  1154. self.delete_moving_selection_shape()
  1155. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1156. def on_key_press(self, event):
  1157. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1158. # matplotlib_key_flag = False
  1159. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1160. if type(event) is int:
  1161. key = event
  1162. # events from the GUI are of type QKeyEvent
  1163. elif type(event) == QtGui.QKeyEvent:
  1164. key = event.key()
  1165. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1166. # matplotlib_key_flag = True
  1167. key = event.key
  1168. key = QtGui.QKeySequence(key)
  1169. # check for modifiers
  1170. key_string = key.toString().lower()
  1171. if '+' in key_string:
  1172. mod, __, key_text = key_string.rpartition('+')
  1173. if mod.lower() == 'ctrl':
  1174. # modifiers = QtCore.Qt.ControlModifier
  1175. pass
  1176. elif mod.lower() == 'alt':
  1177. # modifiers = QtCore.Qt.AltModifier
  1178. pass
  1179. elif mod.lower() == 'shift':
  1180. # modifiers = QtCore.Qt.ShiftModifier
  1181. pass
  1182. else:
  1183. # modifiers = QtCore.Qt.NoModifier
  1184. pass
  1185. key = QtGui.QKeySequence(key_text)
  1186. # events from Vispy are of type KeyEvent
  1187. else:
  1188. key = event.key
  1189. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1190. if self.area_sel_disconnect_flag is True:
  1191. if self.app.is_legacy is False:
  1192. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1193. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1194. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1195. else:
  1196. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1197. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1198. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1199. try:
  1200. # restore the Grid snapping if it was active before
  1201. if self.grid_status_memory is True:
  1202. self.app.ui.grid_snap_btn.trigger()
  1203. if self.app.is_legacy is False:
  1204. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1205. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1206. else:
  1207. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1208. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1209. self.app.tool_shapes.clear(update=True)
  1210. except Exception as e:
  1211. log.debug("ToolPaint.on_key_press() _2 --> %s" % str(e))
  1212. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1213. self.app.on_mouse_click_over_plot)
  1214. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1215. self.app.on_mouse_move_over_plot)
  1216. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1217. self.app.on_mouse_click_release_over_plot)
  1218. self.points = []
  1219. self.poly_drawn = False
  1220. self.delete_moving_selection_shape()
  1221. self.delete_tool_selection_shape()
  1222. def calculate_bounding_box(self, ncc_obj, ncc_select, box_obj=None):
  1223. """
  1224. Will return a geometry that dictate the total extent of the area to be copper cleared
  1225. :param ncc_obj: The object to be copper cleared
  1226. :param box_obj: The object whose geometry will be used as delimitation for copper clearing - if selected
  1227. :param ncc_select: String that choose what kind of reference to be used for copper clearing extent
  1228. :return: The geometry that surrounds the area to be cleared and the kind of object from which the
  1229. geometry originated (string: "gerber", "geometry" or None)
  1230. """
  1231. box_kind = box_obj.kind if box_obj is not None else None
  1232. env_obj = None
  1233. if ncc_select == _('Itself'):
  1234. geo_n = ncc_obj.solid_geometry
  1235. try:
  1236. if isinstance(geo_n, MultiPolygon):
  1237. env_obj = geo_n.convex_hull
  1238. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1239. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1240. env_obj = cascaded_union(geo_n)
  1241. else:
  1242. env_obj = cascaded_union(geo_n)
  1243. env_obj = env_obj.convex_hull
  1244. except Exception as e:
  1245. log.debug("NonCopperClear.calculate_bounding_box() 'itself' --> %s" % str(e))
  1246. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1247. return None
  1248. elif ncc_select == _("Area Selection"):
  1249. env_obj = cascaded_union(self.sel_rect)
  1250. try:
  1251. __ = iter(env_obj)
  1252. except Exception:
  1253. env_obj = [env_obj]
  1254. elif ncc_select == _("Reference Object"):
  1255. if box_obj is None:
  1256. return None, None
  1257. box_geo = box_obj.solid_geometry
  1258. if box_kind == 'geometry':
  1259. try:
  1260. __ = iter(box_geo)
  1261. env_obj = box_geo
  1262. except Exception:
  1263. env_obj = [box_geo]
  1264. elif box_kind == 'gerber':
  1265. box_geo = cascaded_union(box_obj.solid_geometry).convex_hull
  1266. ncc_geo = cascaded_union(ncc_obj.solid_geometry).convex_hull
  1267. env_obj = ncc_geo.intersection(box_geo)
  1268. else:
  1269. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1270. return 'fail'
  1271. return env_obj, box_kind
  1272. def apply_margin_to_bounding_box(self, bbox, box_kind, ncc_select, ncc_margin):
  1273. """
  1274. Prepare non-copper polygons.
  1275. Apply a margin to the bounding box area from which the copper features will be subtracted
  1276. :param bbox: the Geometry to be used as bounding box after applying the ncc_margin
  1277. :param box_kind: "geometry" or "gerber"
  1278. :param ncc_select: the kind of area to be copper cleared
  1279. :param ncc_margin: the margin around the area to be copper cleared
  1280. :return: an geometric element (Polygon or MultiPolygon) that specify the area to be copper cleared
  1281. """
  1282. log.debug("NCC Tool. Preparing non-copper polygons.")
  1283. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1284. if bbox is None:
  1285. log.debug("NonCopperClear.apply_margin_to_bounding_box() --> The object is None")
  1286. return 'fail'
  1287. new_bounding_box = None
  1288. if ncc_select == _('Itself'):
  1289. try:
  1290. new_bounding_box = bbox.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1291. except Exception as e:
  1292. log.debug("NonCopperClear.apply_margin_to_bounding_box() 'itself' --> %s" % str(e))
  1293. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1294. return 'fail'
  1295. elif ncc_select == _("Area Selection"):
  1296. geo_buff_list = []
  1297. for poly in bbox:
  1298. if self.app.abort_flag:
  1299. # graceful abort requested by the user
  1300. raise grace
  1301. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1302. new_bounding_box = cascaded_union(geo_buff_list)
  1303. elif ncc_select == _("Reference Object"):
  1304. if box_kind == 'geometry':
  1305. geo_buff_list = []
  1306. for poly in bbox:
  1307. if self.app.abort_flag:
  1308. # graceful abort requested by the user
  1309. raise grace
  1310. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1311. new_bounding_box = cascaded_union(geo_buff_list)
  1312. elif box_kind == 'gerber':
  1313. new_bounding_box = bbox.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1314. else:
  1315. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1316. return 'fail'
  1317. log.debug("NCC Tool. Finished non-copper polygons.")
  1318. return new_bounding_box
  1319. def get_tool_empty_area(self, name, ncc_obj, geo_obj, isotooldia, has_offset, ncc_offset, ncc_margin,
  1320. bounding_box, tools_storage, work_geo=None):
  1321. """
  1322. Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry.
  1323. :param name:
  1324. :param ncc_obj:
  1325. :param geo_obj:
  1326. :param isotooldia:
  1327. :param has_offset:
  1328. :param ncc_offset:
  1329. :param ncc_margin:
  1330. :param bounding_box: only this area is kept
  1331. :param tools_storage:
  1332. :param work_geo: if provided use this geometry to generate the empty area
  1333. :return:
  1334. """
  1335. log.debug("NCC Tool. Calculate 'empty' area.")
  1336. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1337. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1338. # will store the number of tools for which the isolation is broken
  1339. warning_flag = 0
  1340. if work_geo:
  1341. sol_geo = work_geo
  1342. if has_offset is True:
  1343. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1344. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1345. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1346. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1347. if empty == 'fail' or empty.is_empty:
  1348. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1349. self.app.inform.emit(msg)
  1350. return 'fail'
  1351. if type(empty) is Polygon:
  1352. empty = MultiPolygon([empty])
  1353. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1354. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1355. return empty, warning_flag
  1356. if ncc_obj.kind == 'gerber' and not isotooldia:
  1357. # unfortunately for this function to work time efficient,
  1358. # if the Gerber was loaded without buffering then it require the buffering now.
  1359. if self.app.defaults['gerber_buffering'] == 'no':
  1360. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1361. else:
  1362. sol_geo = ncc_obj.solid_geometry
  1363. if has_offset is True:
  1364. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1365. if isinstance(sol_geo, list):
  1366. sol_geo = MultiPolygon(sol_geo)
  1367. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1368. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1369. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1370. if empty == 'fail' or empty.is_empty:
  1371. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1372. self.app.inform.emit(msg)
  1373. return 'fail'
  1374. elif ncc_obj.kind == 'gerber' and isotooldia:
  1375. isolated_geo = []
  1376. # unfortunately for this function to work time efficient,
  1377. # if the Gerber was loaded without buffering then it require the buffering now.
  1378. # TODO 'buffering status' should be a property of the object not the project property
  1379. if self.app.defaults['gerber_buffering'] == 'no':
  1380. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1381. else:
  1382. self.solid_geometry = ncc_obj.solid_geometry
  1383. # if milling type is climb then the move is counter-clockwise around features
  1384. milling_type = self.ui.milling_type_radio.get_value()
  1385. for tool_iso in isotooldia:
  1386. new_geometry = []
  1387. if milling_type == 'cl':
  1388. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1389. else:
  1390. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1391. if isolated_geo == 'fail' or isolated_geo.is_empty:
  1392. self.app.inform.emit('[ERROR_NOTCL] %s %s' %
  1393. (_("Isolation geometry could not be generated."), str(tool_iso)))
  1394. continue
  1395. if ncc_margin < tool_iso:
  1396. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1397. "than isolation tool diameter."))
  1398. try:
  1399. for geo_elem in isolated_geo:
  1400. # provide the app with a way to process the GUI events when in a blocking loop
  1401. QtWidgets.QApplication.processEvents()
  1402. if self.app.abort_flag:
  1403. # graceful abort requested by the user
  1404. raise grace
  1405. if isinstance(geo_elem, Polygon):
  1406. for ring in self.poly2rings(geo_elem):
  1407. new_geo = ring.intersection(bounding_box)
  1408. if new_geo and not new_geo.is_empty:
  1409. new_geometry.append(new_geo)
  1410. elif isinstance(geo_elem, MultiPolygon):
  1411. for poly in geo_elem:
  1412. for ring in self.poly2rings(poly):
  1413. new_geo = ring.intersection(bounding_box)
  1414. if new_geo and not new_geo.is_empty:
  1415. new_geometry.append(new_geo)
  1416. elif isinstance(geo_elem, LineString):
  1417. new_geo = geo_elem.intersection(bounding_box)
  1418. if new_geo:
  1419. if not new_geo.is_empty:
  1420. new_geometry.append(new_geo)
  1421. elif isinstance(geo_elem, MultiLineString):
  1422. for line_elem in geo_elem:
  1423. new_geo = line_elem.intersection(bounding_box)
  1424. if new_geo and not new_geo.is_empty:
  1425. new_geometry.append(new_geo)
  1426. except TypeError:
  1427. if isinstance(isolated_geo, Polygon):
  1428. for ring in self.poly2rings(isolated_geo):
  1429. new_geo = ring.intersection(bounding_box)
  1430. if new_geo:
  1431. if not new_geo.is_empty:
  1432. new_geometry.append(new_geo)
  1433. elif isinstance(isolated_geo, LineString):
  1434. new_geo = isolated_geo.intersection(bounding_box)
  1435. if new_geo and not new_geo.is_empty:
  1436. new_geometry.append(new_geo)
  1437. elif isinstance(isolated_geo, MultiLineString):
  1438. for line_elem in isolated_geo:
  1439. new_geo = line_elem.intersection(bounding_box)
  1440. if new_geo and not new_geo.is_empty:
  1441. new_geometry.append(new_geo)
  1442. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1443. for geo_e in new_geometry:
  1444. if type(geo_e) == MultiLineString:
  1445. warning_flag += 1
  1446. break
  1447. for k, v in tools_storage.items():
  1448. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1449. tool_iso)):
  1450. current_uid = int(k)
  1451. # add the solid_geometry to the current too in self.paint_tools dictionary
  1452. # and then reset the temporary list that stored that solid_geometry
  1453. v['solid_geometry'] = deepcopy(new_geometry)
  1454. v['data']['name'] = name
  1455. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1456. break
  1457. sol_geo = cascaded_union(isolated_geo)
  1458. if has_offset is True:
  1459. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1460. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1461. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1462. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1463. if empty == 'fail' or empty.is_empty:
  1464. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1465. self.app.inform.emit(msg)
  1466. return 'fail'
  1467. elif ncc_obj.kind == 'geometry':
  1468. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1469. if has_offset is True:
  1470. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1471. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1472. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1473. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1474. if empty == 'fail' or empty.is_empty:
  1475. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1476. self.app.inform.emit(msg)
  1477. return 'fail'
  1478. else:
  1479. self.app.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1480. return 'fail'
  1481. if type(empty) is Polygon:
  1482. empty = MultiPolygon([empty])
  1483. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1484. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1485. return empty, warning_flag
  1486. def clear_polygon_worker(self, pol, tooldia, ncc_method, ncc_overlap, ncc_connect, ncc_contour, prog_plot):
  1487. cp = None
  1488. if ncc_method == _("Standard"):
  1489. try:
  1490. cp = self.clear_polygon(pol, tooldia,
  1491. steps_per_circle=self.circle_steps,
  1492. overlap=ncc_overlap, contour=ncc_contour,
  1493. connect=ncc_connect,
  1494. prog_plot=prog_plot)
  1495. except grace:
  1496. return "fail"
  1497. except Exception as ee:
  1498. log.debug("NonCopperClear.clear_polygon_worker() Standard --> %s" % str(ee))
  1499. elif ncc_method == _("Seed"):
  1500. try:
  1501. cp = self.clear_polygon2(pol, tooldia,
  1502. steps_per_circle=self.circle_steps,
  1503. overlap=ncc_overlap, contour=ncc_contour,
  1504. connect=ncc_connect,
  1505. prog_plot=prog_plot)
  1506. except grace:
  1507. return "fail"
  1508. except Exception as ee:
  1509. log.debug("NonCopperClear.clear_polygon_worker() Seed --> %s" % str(ee))
  1510. elif ncc_method == _("Lines"):
  1511. try:
  1512. cp = self.clear_polygon3(pol, tooldia,
  1513. steps_per_circle=self.circle_steps,
  1514. overlap=ncc_overlap, contour=ncc_contour,
  1515. connect=ncc_connect,
  1516. prog_plot=prog_plot)
  1517. except grace:
  1518. return "fail"
  1519. except Exception as ee:
  1520. log.debug("NonCopperClear.clear_polygon_worker() Lines --> %s" % str(ee))
  1521. elif ncc_method == _("Combo"):
  1522. try:
  1523. self.app.inform.emit(_("Clearing the polygon with the method: lines."))
  1524. cp = self.clear_polygon3(pol, tooldia,
  1525. steps_per_circle=self.circle_steps,
  1526. overlap=ncc_overlap, contour=ncc_contour,
  1527. connect=ncc_connect,
  1528. prog_plot=prog_plot)
  1529. if cp and cp.objects:
  1530. pass
  1531. else:
  1532. self.app.inform.emit(_("Failed. Clearing the polygon with the method: seed."))
  1533. cp = self.clear_polygon2(pol, tooldia,
  1534. steps_per_circle=self.circle_steps,
  1535. overlap=ncc_overlap, contour=ncc_contour,
  1536. connect=ncc_connect,
  1537. prog_plot=prog_plot)
  1538. if cp and cp.objects:
  1539. pass
  1540. else:
  1541. self.app.inform.emit(_("Failed. Clearing the polygon with the method: standard."))
  1542. cp = self.clear_polygon(pol, tooldia,
  1543. steps_per_circle=self.circle_steps,
  1544. overlap=ncc_overlap, contour=ncc_contour,
  1545. connect=ncc_connect,
  1546. prog_plot=prog_plot)
  1547. except grace:
  1548. return "fail"
  1549. except Exception as ee:
  1550. log.debug("NonCopperClear.clear_polygon_worker() Combo --> %s" % str(ee))
  1551. if cp and cp.objects:
  1552. return list(cp.get_objects())
  1553. else:
  1554. pt = pol.representative_point()
  1555. coords = (pt.x, pt.y)
  1556. self.app.inform_shell.emit('%s %s' % (_('Polygon could not be cleared. Location:'), str(coords)))
  1557. return None
  1558. def clear_copper(self, ncc_obj, ncctooldia, isotooldia, sel_obj=None, outname=None, order=None,
  1559. tools_storage=None, run_threaded=True):
  1560. """
  1561. Clear the excess copper from the entire object.
  1562. :param ncc_obj: ncc cleared object
  1563. :type ncc_obj: appObjects.FlatCAMGerber.GerberObject
  1564. :param ncctooldia: a list of diameters of the tools to be used to ncc clear
  1565. :type ncctooldia: list
  1566. :param isotooldia: a list of diameters of the tools to be used for isolation
  1567. :type isotooldia: list
  1568. :param sel_obj:
  1569. :type sel_obj:
  1570. :param outname: name of the resulting object
  1571. :type outname: str
  1572. :param order: Tools order
  1573. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1574. Usage of the different one is related to when this function is called
  1575. from a TcL command.
  1576. :type tools_storage: dict
  1577. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False
  1578. it will run non-threaded for TclShell usage
  1579. :type run_threaded: bool
  1580. :return:
  1581. """
  1582. log.debug("Executing the handler ...")
  1583. if run_threaded:
  1584. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1585. else:
  1586. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1587. QtWidgets.QApplication.processEvents()
  1588. # ######################################################################################################
  1589. # ######################### Read the parameters ########################################################
  1590. # ######################################################################################################
  1591. units = self.app.defaults['units']
  1592. order = order if order else self.ui.ncc_order_radio.get_value()
  1593. ncc_select = self.ui.select_combo.get_value()
  1594. rest_machining_choice = self.ui.ncc_rest_cb.get_value()
  1595. # determine if to use the progressive plotting
  1596. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  1597. tools_storage = tools_storage if tools_storage is not None else self.ncc_tools
  1598. sorted_clear_tools = ncctooldia
  1599. if not sorted_clear_tools:
  1600. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There is no copper clearing tool in the selection "
  1601. "and at least one is needed."))
  1602. return 'fail'
  1603. # ########################################################################################################
  1604. # set the name for the future Geometry object
  1605. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1606. # ########################################################################################################
  1607. name = outname if outname is not None else self.obj_name + "_ncc"
  1608. # ########################################################################################################
  1609. # ######### #####Initializes the new geometry object #####################################################
  1610. # ########################################################################################################
  1611. def gen_clear_area(geo_obj, app_obj):
  1612. log.debug("NCC Tool. Normal copper clearing task started.")
  1613. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1614. # provide the app with a way to process the GUI events when in a blocking loop
  1615. if not run_threaded:
  1616. QtWidgets.QApplication.processEvents()
  1617. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1618. # will store the number of tools for which the isolation is broken
  1619. warning_flag = 0
  1620. tool = None
  1621. if order == 'fwd':
  1622. sorted_clear_tools.sort(reverse=False)
  1623. elif order == 'rev':
  1624. sorted_clear_tools.sort(reverse=True)
  1625. else:
  1626. pass
  1627. app_obj.poly_not_cleared = False # flag for polygons not cleared
  1628. if ncc_select == _("Reference Object"):
  1629. bbox_geo, bbox_kind = self.calculate_bounding_box(
  1630. ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1631. else:
  1632. bbox_geo, bbox_kind = self.calculate_bounding_box(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1633. if bbox_geo is None and bbox_kind is None:
  1634. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1635. return "fail"
  1636. # Bounding box for current tool
  1637. ncc_margin = self.ui.ncc_margin_entry.get_value()
  1638. bbox = self.apply_margin_to_bounding_box(bbox=bbox_geo, box_kind=bbox_kind,
  1639. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1640. # COPPER CLEARING with tools marked for CLEAR#
  1641. for tool in sorted_clear_tools:
  1642. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1643. if self.app.abort_flag:
  1644. # graceful abort requested by the user
  1645. raise grace
  1646. # provide the app with a way to process the GUI events when in a blocking loop
  1647. if not run_threaded:
  1648. QtWidgets.QApplication.processEvents()
  1649. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1650. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1651. )
  1652. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1653. # store here the geometry generated by clear operation
  1654. cleared_geo = []
  1655. tool_uid = 0 # find the current tool_uid
  1656. for k, v in self.ncc_tools.items():
  1657. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1658. tool_uid = int(k)
  1659. break
  1660. # parameters that are particular to the current tool
  1661. ncc_overlap = float(self.ncc_tools[tool_uid]["data"]["tools_nccoverlap"]) / 100.0
  1662. ncc_method = self.ncc_tools[tool_uid]["data"]["tools_nccmethod"]
  1663. ncc_connect = self.ncc_tools[tool_uid]["data"]["tools_nccconnect"]
  1664. ncc_contour = self.ncc_tools[tool_uid]["data"]["tools_ncccontour"]
  1665. has_offset = self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_choice"]
  1666. ncc_offset = float(self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_value"])
  1667. # Area to clear
  1668. area, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1669. isotooldia=isotooldia, ncc_margin=ncc_margin,
  1670. has_offset=has_offset, ncc_offset=ncc_offset,
  1671. tools_storage=tools_storage, bounding_box=bbox)
  1672. # Transform area to MultiPolygon
  1673. if isinstance(area, Polygon):
  1674. area = MultiPolygon([area])
  1675. # variables to display the percentage of work done
  1676. geo_len = len(area.geoms)
  1677. old_disp_number = 0
  1678. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1679. if area.geoms:
  1680. if len(area.geoms) > 0:
  1681. pol_nr = 0
  1682. for p in area.geoms:
  1683. # provide the app with a way to process the GUI events when in a blocking loop
  1684. if not run_threaded:
  1685. QtWidgets.QApplication.processEvents()
  1686. if self.app.abort_flag:
  1687. # graceful abort requested by the user
  1688. raise grace
  1689. # clean the polygon
  1690. p = p.buffer(0)
  1691. if p is not None and p.is_valid:
  1692. poly_failed = 0
  1693. try:
  1694. for pol in p:
  1695. # provide the app with a way to process the GUI events when in a blocking loop
  1696. QtWidgets.QApplication.processEvents()
  1697. if pol is not None and isinstance(pol, Polygon):
  1698. res = self.clear_polygon_worker(pol=pol, tooldia=tool,
  1699. ncc_method=ncc_method,
  1700. ncc_overlap=ncc_overlap,
  1701. ncc_connect=ncc_connect,
  1702. ncc_contour=ncc_contour,
  1703. prog_plot=prog_plot)
  1704. if res is not None:
  1705. cleared_geo += res
  1706. else:
  1707. poly_failed += 1
  1708. else:
  1709. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(pol)))
  1710. except TypeError:
  1711. if isinstance(p, Polygon):
  1712. res = self.clear_polygon_worker(pol=p, tooldia=tool,
  1713. ncc_method=ncc_method,
  1714. ncc_overlap=ncc_overlap,
  1715. ncc_connect=ncc_connect,
  1716. ncc_contour=ncc_contour,
  1717. prog_plot=prog_plot)
  1718. if res is not None:
  1719. cleared_geo += res
  1720. else:
  1721. poly_failed += 1
  1722. else:
  1723. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(p)))
  1724. if poly_failed > 0:
  1725. app_obj.poly_not_cleared = True
  1726. pol_nr += 1
  1727. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1728. # log.debug("Polygons cleared: %d" % pol_nr)
  1729. if old_disp_number < disp_number <= 100:
  1730. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1731. old_disp_number = disp_number
  1732. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1733. # check if there is a geometry at all in the cleared geometry
  1734. if cleared_geo:
  1735. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1736. # solid_geometry
  1737. for k, v in tools_storage.items():
  1738. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1739. tool)):
  1740. current_uid = int(k)
  1741. # add the solid_geometry to the current too in self.paint_tools dictionary
  1742. # and then reset the temporary list that stored that solid_geometry
  1743. v['solid_geometry'] = deepcopy(cleared_geo)
  1744. v['data']['name'] = name
  1745. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1746. break
  1747. else:
  1748. log.debug("There are no geometries in the cleared polygon.")
  1749. # clean the progressive plotted shapes if it was used
  1750. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1751. self.temp_shapes.clear(update=True)
  1752. # delete tools with empty geometry
  1753. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1754. for uid, uid_val in list(tools_storage.items()):
  1755. try:
  1756. # if the solid_geometry (type=list) is empty
  1757. if not uid_val['solid_geometry']:
  1758. msg = '%s %s: %s %s: %s' % (
  1759. _("Could not use the tool for copper clear."),
  1760. _("Tool"),
  1761. str(uid),
  1762. _("with diameter"),
  1763. str(uid_val['tooldia']))
  1764. self.app.inform.emit(msg)
  1765. log.debug("Empty geometry for tool: %s with diameter: %s" % (str(uid), str(uid_val['tooldia'])))
  1766. tools_storage.pop(uid, None)
  1767. except KeyError:
  1768. tools_storage.pop(uid, None)
  1769. geo_obj.options["cnctooldia"] = str(tool)
  1770. geo_obj.multigeo = True
  1771. geo_obj.tools = dict(tools_storage)
  1772. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1773. has_solid_geo = 0
  1774. for tid in geo_obj.tools:
  1775. if geo_obj.tools[tid]['solid_geometry']:
  1776. has_solid_geo += 1
  1777. if has_solid_geo == 0:
  1778. msg = '[ERROR] %s' % _("There is no NCC Geometry in the file.\n"
  1779. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1780. "Change the painting parameters and try again.")
  1781. app_obj.inform.emit(msg)
  1782. return 'fail'
  1783. # check to see if geo_obj.tools is empty
  1784. # it will be updated only if there is a solid_geometry for tools
  1785. if geo_obj.tools:
  1786. if warning_flag == 0:
  1787. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1788. else:
  1789. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1790. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1791. str(warning_flag),
  1792. _("tools")))
  1793. return
  1794. # create the solid_geometry
  1795. geo_obj.solid_geometry = []
  1796. for tool_id in geo_obj.tools:
  1797. if geo_obj.tools[tool_id]['solid_geometry']:
  1798. try:
  1799. for geo in geo_obj.tools[tool_id]['solid_geometry']:
  1800. geo_obj.solid_geometry.append(geo)
  1801. except TypeError:
  1802. geo_obj.solid_geometry.append(geo_obj.tools[tool_id]['solid_geometry'])
  1803. else:
  1804. # I will use this variable for this purpose although it was meant for something else
  1805. # signal that we have no geo in the object therefore don't create it
  1806. app_obj.poly_not_cleared = False
  1807. return "fail"
  1808. # # Experimental...
  1809. # # print("Indexing...", end=' ')
  1810. # # geo_obj.make_index()
  1811. # ###########################################################################################
  1812. # Initializes the new geometry object for the case of the rest-machining ####################
  1813. # ###########################################################################################
  1814. def gen_clear_area_rest(geo_obj, app_obj):
  1815. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1816. app_obj.inform.emit(_("NCC Tool. Rest machining copper clearing task started."))
  1817. # provide the app with a way to process the GUI events when in a blocking loop
  1818. if not run_threaded:
  1819. QtWidgets.QApplication.processEvents()
  1820. sorted_clear_tools.sort(reverse=True)
  1821. cleared_by_last_tool = []
  1822. rest_geo = []
  1823. current_uid = 1
  1824. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1825. app_obj.poly_not_cleared = True
  1826. if ncc_select == _("Reference Object"):
  1827. env_obj, box_obj_kind = self.calculate_bounding_box(
  1828. ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1829. else:
  1830. env_obj, box_obj_kind = self.calculate_bounding_box(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1831. if env_obj is None and box_obj_kind is None:
  1832. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1833. return "fail"
  1834. # log.debug("NCC Tool. Calculate 'empty' area.")
  1835. # app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1836. # Bounding box for current tool
  1837. ncc_margin = self.ui.ncc_margin_entry.get_value()
  1838. bbox = self.apply_margin_to_bounding_box(bbox=env_obj, box_kind=box_obj_kind,
  1839. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1840. ncc_connect = self.ui.rest_ncc_connect_cb.get_value()
  1841. ncc_contour = self.ui.rest_ncc_contour_cb.get_value()
  1842. has_offset = self.ui.rest_ncc_choice_offset_cb.get_value()
  1843. ncc_offset = self.ui.rest_ncc_offset_spinner.get_value()
  1844. # Area to clear
  1845. area, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1846. isotooldia=isotooldia,
  1847. has_offset=has_offset, ncc_offset=ncc_offset,
  1848. ncc_margin=ncc_margin, tools_storage=tools_storage,
  1849. bounding_box=bbox)
  1850. # Generate area for each tool
  1851. while sorted_clear_tools:
  1852. tool = sorted_clear_tools.pop(0)
  1853. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1854. if self.app.abort_flag:
  1855. # graceful abort requested by the user
  1856. raise grace
  1857. # provide the app with a way to process the GUI events when in a blocking loop
  1858. QtWidgets.QApplication.processEvents()
  1859. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1860. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1861. )
  1862. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1863. tool_uid = 0 # find the current tool_uid
  1864. for k, v in self.ncc_tools.items():
  1865. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1866. tool_uid = int(k)
  1867. break
  1868. # parameters that are particular to the current tool
  1869. ncc_overlap = float(self.ncc_tools[tool_uid]["data"]["tools_nccoverlap"]) / 100.0
  1870. ncc_method = self.ncc_tools[tool_uid]["data"]["tools_nccmethod"]
  1871. # variables to display the percentage of work done
  1872. geo_len = len(area.geoms)
  1873. old_disp_number = 0
  1874. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1875. # store here the geometry generated by clear operation
  1876. cleared_geo = []
  1877. if area.geoms:
  1878. if len(area.geoms) > 0:
  1879. pol_nr = 0
  1880. for p in area.geoms:
  1881. if self.app.abort_flag:
  1882. # graceful abort requested by the user
  1883. raise grace
  1884. if p is not None and p.is_valid:
  1885. # provide the app with a way to process the GUI events when in a blocking loop
  1886. QtWidgets.QApplication.processEvents()
  1887. poly_failed = 0
  1888. # speedup the clearing by not trying to clear polygons that is clear they can't be
  1889. # cleared with the current tool. this tremendously reduce the clearing time
  1890. check_dist = -tool / 2.0
  1891. check_buff = p.buffer(check_dist)
  1892. if not check_buff or check_buff.is_empty:
  1893. continue
  1894. # actual copper claring is done here
  1895. if isinstance(p, Polygon):
  1896. res = self.clear_polygon_worker(pol=p, tooldia=tool,
  1897. ncc_method=ncc_method,
  1898. ncc_overlap=ncc_overlap,
  1899. ncc_connect=ncc_connect,
  1900. ncc_contour=ncc_contour,
  1901. prog_plot=prog_plot)
  1902. if res is not None:
  1903. cleared_geo += res
  1904. else:
  1905. poly_failed += 1
  1906. else:
  1907. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(p)))
  1908. if poly_failed > 0:
  1909. app_obj.poly_not_cleared = True
  1910. pol_nr += 1
  1911. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1912. # log.debug("Polygons cleared: %d" % pol_nr)
  1913. if old_disp_number < disp_number <= 100:
  1914. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1915. old_disp_number = disp_number
  1916. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1917. if self.app.abort_flag:
  1918. raise grace # graceful abort requested by the user
  1919. # check if there is a geometry at all in the cleared geometry
  1920. if cleared_geo:
  1921. tools_storage[tool_uid]["solid_geometry"] = deepcopy(cleared_geo)
  1922. tools_storage[tool_uid]["data"]["name"] = name + '_' + str(tool)
  1923. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1924. else:
  1925. log.debug("There are no geometries in the cleared polygon.")
  1926. # Area to clear next
  1927. buffered_cleared = cascaded_union(cleared_geo).buffer(tool / 2.0)
  1928. area = area.difference(buffered_cleared)
  1929. if not area or area.is_empty:
  1930. break
  1931. # # try to clear the polygons
  1932. # buff_distance = 0.0
  1933. # try:
  1934. # new_area = [p.buffer(buff_distance) for p in area if not p.is_empty]
  1935. # except TypeError:
  1936. # new_area = [area.buffer(tool * ncc_overlap)]
  1937. # area = cascaded_union(area)
  1938. geo_obj.multigeo = True
  1939. geo_obj.options["cnctooldia"] = '0.0'
  1940. # clean the progressive plotted shapes if it was used
  1941. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1942. self.temp_shapes.clear(update=True)
  1943. # check to see if geo_obj.tools is empty
  1944. # it will be updated only if there is a solid_geometry for tools
  1945. if geo_obj.tools:
  1946. if warning_flag == 0:
  1947. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  1948. else:
  1949. self.app.inform.emit(
  1950. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  1951. "isolation is broken for"), str(warning_flag), _("tools")))
  1952. return
  1953. # create the solid_geometry
  1954. geo_obj.solid_geometry = []
  1955. for tool_uid in geo_obj.tools:
  1956. if geo_obj.tools[tool_uid]['solid_geometry']:
  1957. try:
  1958. for geo in geo_obj.tools[tool_uid]['solid_geometry']:
  1959. geo_obj.solid_geometry.append(geo)
  1960. except TypeError:
  1961. geo_obj.solid_geometry.append(geo_obj.tools[tool_uid]['solid_geometry'])
  1962. else:
  1963. # I will use this variable for this purpose although it was meant for something else
  1964. # signal that we have no geo in the object therefore don't create it
  1965. app_obj.poly_not_cleared = False
  1966. return "fail"
  1967. # ###########################################################################################
  1968. # Create the Job function and send it to the worker to be processed in another thread #######
  1969. # ###########################################################################################
  1970. def job_thread(a_obj):
  1971. try:
  1972. if rest_machining_choice is True:
  1973. a_obj.app_obj.new_object("geometry", name, gen_clear_area_rest)
  1974. else:
  1975. a_obj.app_obj.new_object("geometry", name, gen_clear_area)
  1976. except grace:
  1977. if run_threaded:
  1978. proc.done()
  1979. return
  1980. except Exception:
  1981. if run_threaded:
  1982. proc.done()
  1983. traceback.print_stack()
  1984. return
  1985. if run_threaded:
  1986. proc.done()
  1987. else:
  1988. a_obj.proc_container.view.set_idle()
  1989. # focus on Selected Tab
  1990. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1991. if run_threaded:
  1992. # Promise object with the new name
  1993. self.app.collection.promise(name)
  1994. # Background
  1995. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1996. else:
  1997. job_thread(app_obj=self.app)
  1998. def clear_copper_tcl(self, ncc_obj, sel_obj=None, ncctooldia=None, isotooldia=None, margin=None, has_offset=None,
  1999. offset=None, select_method=None, outname=None, overlap=None, connect=None, contour=None,
  2000. order=None, method=None, rest=None, tools_storage=None, plot=True, run_threaded=False):
  2001. """
  2002. Clear the excess copper from the entire object. To be used only in a TCL command.
  2003. :param ncc_obj: ncc cleared object
  2004. :param sel_obj:
  2005. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  2006. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  2007. :param overlap: value by which the paths will overlap
  2008. :param order: if the tools are ordered and how
  2009. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  2010. another object
  2011. :param has_offset: True if an offset is needed
  2012. :param offset: distance from the copper features where the copper clearing is stopping
  2013. :param margin: a border around cleared area
  2014. :param outname: name of the resulting object
  2015. :param connect: Connect lines to avoid tool lifts.
  2016. :param contour: Clear around the edges.
  2017. :param method: choice out of 'seed', 'normal', 'lines'
  2018. :param rest: True if to use rest-machining
  2019. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  2020. Usage of the different one is related to when this function is called from a
  2021. TcL command.
  2022. :param plot: if True after the job is finished the result will be plotted, else it will not.
  2023. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage;
  2024. if False it will run non-threaded for TclShell usage
  2025. :return:
  2026. """
  2027. if run_threaded:
  2028. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  2029. else:
  2030. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  2031. QtWidgets.QApplication.processEvents()
  2032. # #####################################################################
  2033. # ####### Read the parameters #########################################
  2034. # #####################################################################
  2035. units = self.app.defaults['units']
  2036. log.debug("NCC Tool started. Reading parameters.")
  2037. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2038. ncc_method = method
  2039. ncc_margin = margin
  2040. ncc_select = select_method
  2041. overlap = overlap
  2042. connect = connect
  2043. contour = contour
  2044. order = order
  2045. if tools_storage is not None:
  2046. tools_storage = tools_storage
  2047. else:
  2048. tools_storage = self.ncc_tools
  2049. ncc_offset = 0.0
  2050. if has_offset is True:
  2051. ncc_offset = offset
  2052. # ######################################################################################################
  2053. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2054. # ######################################################################################################
  2055. sorted_tools = []
  2056. try:
  2057. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2058. except AttributeError:
  2059. if not isinstance(ncctooldia, list):
  2060. sorted_tools = [float(ncctooldia)]
  2061. else:
  2062. sorted_tools = ncctooldia
  2063. if not sorted_tools:
  2064. return 'fail'
  2065. # ##############################################################################################################
  2066. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2067. # ##############################################################################################################
  2068. log.debug("NCC Tool. Preparing non-copper polygons.")
  2069. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2070. try:
  2071. if sel_obj is None or sel_obj == _('Itself'):
  2072. ncc_sel_obj = ncc_obj
  2073. else:
  2074. ncc_sel_obj = sel_obj
  2075. except Exception as e:
  2076. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2077. return 'fail'
  2078. bounding_box = None
  2079. if ncc_select == _('Itself'):
  2080. geo_n = ncc_sel_obj.solid_geometry
  2081. try:
  2082. if isinstance(geo_n, MultiPolygon):
  2083. env_obj = geo_n.convex_hull
  2084. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2085. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2086. env_obj = cascaded_union(geo_n)
  2087. else:
  2088. env_obj = cascaded_union(geo_n)
  2089. env_obj = env_obj.convex_hull
  2090. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2091. except Exception as e:
  2092. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2093. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2094. return 'fail'
  2095. elif ncc_select == 'area':
  2096. geo_n = cascaded_union(self.sel_rect)
  2097. try:
  2098. __ = iter(geo_n)
  2099. except Exception as e:
  2100. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2101. geo_n = [geo_n]
  2102. geo_buff_list = []
  2103. for poly in geo_n:
  2104. if self.app.abort_flag:
  2105. # graceful abort requested by the user
  2106. raise grace
  2107. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2108. bounding_box = cascaded_union(geo_buff_list)
  2109. elif ncc_select == _("Reference Object"):
  2110. geo_n = ncc_sel_obj.solid_geometry
  2111. if ncc_sel_obj.kind == 'geometry':
  2112. try:
  2113. __ = iter(geo_n)
  2114. except Exception as e:
  2115. log.debug("NonCopperClear.clear_copper() 'Reference Object' --> %s" % str(e))
  2116. geo_n = [geo_n]
  2117. geo_buff_list = []
  2118. for poly in geo_n:
  2119. if self.app.abort_flag:
  2120. # graceful abort requested by the user
  2121. raise grace
  2122. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2123. bounding_box = cascaded_union(geo_buff_list)
  2124. elif ncc_sel_obj.kind == 'gerber':
  2125. geo_n = cascaded_union(geo_n).convex_hull
  2126. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2127. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2128. else:
  2129. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2130. return 'fail'
  2131. log.debug("NCC Tool. Finished non-copper polygons.")
  2132. # ########################################################################################################
  2133. # set the name for the future Geometry object
  2134. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2135. # ########################################################################################################
  2136. rest_machining_choice = rest
  2137. if rest_machining_choice is True:
  2138. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2139. else:
  2140. name = outname if outname is not None else self.obj_name + "_ncc"
  2141. # ##########################################################################################
  2142. # Initializes the new geometry object ######################################################
  2143. # ##########################################################################################
  2144. def gen_clear_area(geo_obj, app_obj):
  2145. assert geo_obj.kind == 'geometry', \
  2146. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  2147. # provide the app with a way to process the GUI events when in a blocking loop
  2148. if not run_threaded:
  2149. QtWidgets.QApplication.processEvents()
  2150. log.debug("NCC Tool. Normal copper clearing task started.")
  2151. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2152. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2153. # will store the number of tools for which the isolation is broken
  2154. warning_flag = 0
  2155. if order == 'fwd':
  2156. sorted_tools.sort(reverse=False)
  2157. elif order == 'rev':
  2158. sorted_tools.sort(reverse=True)
  2159. else:
  2160. pass
  2161. cleared_geo = []
  2162. # Already cleared area
  2163. cleared = MultiPolygon()
  2164. # flag for polygons not cleared
  2165. app_obj.poly_not_cleared = False
  2166. # Generate area for each tool
  2167. offset_a = sum(sorted_tools)
  2168. current_uid = int(1)
  2169. try:
  2170. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2171. except TypeError:
  2172. tool = eval(self.app.defaults["tools_ncctools"])
  2173. # ###################################################################################################
  2174. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2175. # ###################################################################################################
  2176. log.debug("NCC Tool. Calculate 'empty' area.")
  2177. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2178. if ncc_obj.kind == 'gerber' and not isotooldia:
  2179. # unfortunately for this function to work time efficient,
  2180. # if the Gerber was loaded without buffering then it require the buffering now.
  2181. if self.app.defaults['gerber_buffering'] == 'no':
  2182. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2183. else:
  2184. sol_geo = ncc_obj.solid_geometry
  2185. if has_offset is True:
  2186. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2187. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2188. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2189. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2190. if empty == 'fail':
  2191. return 'fail'
  2192. if empty.is_empty:
  2193. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2194. _("Could not get the extent of the area to be non copper cleared."))
  2195. return 'fail'
  2196. elif ncc_obj.kind == 'gerber' and isotooldia:
  2197. isolated_geo = []
  2198. # unfortunately for this function to work time efficient,
  2199. # if the Gerber was loaded without buffering then it require the buffering now.
  2200. if self.app.defaults['gerber_buffering'] == 'no':
  2201. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2202. else:
  2203. self.solid_geometry = ncc_obj.solid_geometry
  2204. # if milling type is climb then the move is counter-clockwise around features
  2205. milling_type = self.app.defaults["tools_nccmilling_type"]
  2206. for tool_iso in isotooldia:
  2207. new_geometry = []
  2208. if milling_type == 'cl':
  2209. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2210. else:
  2211. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2212. if isolated_geo == 'fail':
  2213. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2214. else:
  2215. if ncc_margin < tool_iso:
  2216. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2217. "than isolation tool diameter."))
  2218. try:
  2219. for geo_elem in isolated_geo:
  2220. # provide the app with a way to process the GUI events when in a blocking loop
  2221. QtWidgets.QApplication.processEvents()
  2222. if self.app.abort_flag:
  2223. # graceful abort requested by the user
  2224. raise grace
  2225. if isinstance(geo_elem, Polygon):
  2226. for ring in self.poly2rings(geo_elem):
  2227. new_geo = ring.intersection(bounding_box)
  2228. if new_geo and not new_geo.is_empty:
  2229. new_geometry.append(new_geo)
  2230. elif isinstance(geo_elem, MultiPolygon):
  2231. for a_poly in geo_elem:
  2232. for ring in self.poly2rings(a_poly):
  2233. new_geo = ring.intersection(bounding_box)
  2234. if new_geo and not new_geo.is_empty:
  2235. new_geometry.append(new_geo)
  2236. elif isinstance(geo_elem, LineString):
  2237. new_geo = geo_elem.intersection(bounding_box)
  2238. if new_geo:
  2239. if not new_geo.is_empty:
  2240. new_geometry.append(new_geo)
  2241. elif isinstance(geo_elem, MultiLineString):
  2242. for line_elem in geo_elem:
  2243. new_geo = line_elem.intersection(bounding_box)
  2244. if new_geo and not new_geo.is_empty:
  2245. new_geometry.append(new_geo)
  2246. except TypeError:
  2247. if isinstance(isolated_geo, Polygon):
  2248. for ring in self.poly2rings(isolated_geo):
  2249. new_geo = ring.intersection(bounding_box)
  2250. if new_geo:
  2251. if not new_geo.is_empty:
  2252. new_geometry.append(new_geo)
  2253. elif isinstance(isolated_geo, LineString):
  2254. new_geo = isolated_geo.intersection(bounding_box)
  2255. if new_geo and not new_geo.is_empty:
  2256. new_geometry.append(new_geo)
  2257. elif isinstance(isolated_geo, MultiLineString):
  2258. for line_elem in isolated_geo:
  2259. new_geo = line_elem.intersection(bounding_box)
  2260. if new_geo and not new_geo.is_empty:
  2261. new_geometry.append(new_geo)
  2262. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2263. for geo_e in new_geometry:
  2264. if type(geo_e) == MultiLineString:
  2265. warning_flag += 1
  2266. break
  2267. for k, v in tools_storage.items():
  2268. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2269. tool_iso)):
  2270. current_uid = int(k)
  2271. # add the solid_geometry to the current too in self.paint_tools dictionary
  2272. # and then reset the temporary list that stored that solid_geometry
  2273. v['solid_geometry'] = deepcopy(new_geometry)
  2274. v['data']['name'] = name
  2275. break
  2276. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2277. sol_geo = cascaded_union(isolated_geo)
  2278. if has_offset is True:
  2279. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2280. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2281. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2282. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2283. if empty == 'fail':
  2284. return 'fail'
  2285. if empty.is_empty:
  2286. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2287. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2288. return 'fail'
  2289. elif ncc_obj.kind == 'geometry':
  2290. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2291. if has_offset is True:
  2292. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2293. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2294. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2295. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2296. if empty == 'fail':
  2297. return 'fail'
  2298. if empty.is_empty:
  2299. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2300. _("Could not get the extent of the area to be non copper cleared."))
  2301. return 'fail'
  2302. else:
  2303. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2304. return 'fail'
  2305. if type(empty) is Polygon:
  2306. empty = MultiPolygon([empty])
  2307. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2308. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2309. # COPPER CLEARING #
  2310. for tool in sorted_tools:
  2311. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2312. if self.app.abort_flag:
  2313. # graceful abort requested by the user
  2314. raise grace
  2315. # provide the app with a way to process the GUI events when in a blocking loop
  2316. QtWidgets.QApplication.processEvents()
  2317. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2318. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2319. )
  2320. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2321. cleared_geo[:] = []
  2322. # Get remaining tools offset
  2323. offset_a -= (tool - 1e-12)
  2324. # Area to clear
  2325. area = empty.buffer(-offset_a)
  2326. try:
  2327. area = area.difference(cleared)
  2328. except Exception:
  2329. continue
  2330. # Transform area to MultiPolygon
  2331. if type(area) is Polygon:
  2332. area = MultiPolygon([area])
  2333. # variables to display the percentage of work done
  2334. geo_len = len(area.geoms)
  2335. old_disp_number = 0
  2336. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2337. if area.geoms:
  2338. if len(area.geoms) > 0:
  2339. pol_nr = 0
  2340. for p in area.geoms:
  2341. # provide the app with a way to process the GUI events when in a blocking loop
  2342. QtWidgets.QApplication.processEvents()
  2343. if self.app.abort_flag:
  2344. # graceful abort requested by the user
  2345. raise grace
  2346. # clean the polygon
  2347. p = p.buffer(0)
  2348. if p is not None and p.is_valid:
  2349. poly_processed = []
  2350. try:
  2351. for pol in p:
  2352. if pol is not None and isinstance(pol, Polygon):
  2353. if ncc_method == 'standard':
  2354. cp = self.clear_polygon(pol, tool,
  2355. self.circle_steps,
  2356. overlap=overlap, contour=contour,
  2357. connect=connect,
  2358. prog_plot=False)
  2359. elif ncc_method == 'seed':
  2360. cp = self.clear_polygon2(pol, tool,
  2361. self.circle_steps,
  2362. overlap=overlap, contour=contour,
  2363. connect=connect,
  2364. prog_plot=False)
  2365. else:
  2366. cp = self.clear_polygon3(pol, tool,
  2367. self.circle_steps,
  2368. overlap=overlap, contour=contour,
  2369. connect=connect,
  2370. prog_plot=False)
  2371. if cp:
  2372. cleared_geo += list(cp.get_objects())
  2373. poly_processed.append(True)
  2374. else:
  2375. poly_processed.append(False)
  2376. log.warning("Polygon in MultiPolygon can not be cleared.")
  2377. else:
  2378. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2379. "It is: %s" % str(type(pol)))
  2380. except TypeError:
  2381. if isinstance(p, Polygon):
  2382. if ncc_method == 'standard':
  2383. cp = self.clear_polygon(p, tool, self.circle_steps,
  2384. overlap=overlap, contour=contour, connect=connect,
  2385. prog_plot=False)
  2386. elif ncc_method == 'seed':
  2387. cp = self.clear_polygon2(p, tool, self.circle_steps,
  2388. overlap=overlap, contour=contour, connect=connect,
  2389. prog_plot=False)
  2390. else:
  2391. cp = self.clear_polygon3(p, tool, self.circle_steps,
  2392. overlap=overlap, contour=contour, connect=connect,
  2393. prog_plot=False)
  2394. if cp:
  2395. cleared_geo += list(cp.get_objects())
  2396. poly_processed.append(True)
  2397. else:
  2398. poly_processed.append(False)
  2399. log.warning("Polygon can not be cleared.")
  2400. else:
  2401. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2402. p_cleared = poly_processed.count(True)
  2403. p_not_cleared = poly_processed.count(False)
  2404. if p_not_cleared:
  2405. app_obj.poly_not_cleared = True
  2406. if p_cleared == 0:
  2407. continue
  2408. pol_nr += 1
  2409. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2410. # log.debug("Polygons cleared: %d" % pol_nr)
  2411. if old_disp_number < disp_number <= 100:
  2412. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2413. old_disp_number = disp_number
  2414. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2415. # check if there is a geometry at all in the cleared geometry
  2416. if cleared_geo:
  2417. # Overall cleared area
  2418. cleared = empty.buffer(-offset_a * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2419. tool / 1.999999)
  2420. # clean-up cleared geo
  2421. cleared = cleared.buffer(0)
  2422. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2423. # solid_geometry
  2424. for k, v in tools_storage.items():
  2425. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2426. tool)):
  2427. current_uid = int(k)
  2428. # add the solid_geometry to the current too in self.paint_tools dictionary
  2429. # and then reset the temporary list that stored that solid_geometry
  2430. v['solid_geometry'] = deepcopy(cleared_geo)
  2431. v['data']['name'] = name
  2432. break
  2433. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2434. else:
  2435. log.debug("There are no geometries in the cleared polygon.")
  2436. # delete tools with empty geometry
  2437. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2438. for uid, uid_val in list(tools_storage.items()):
  2439. try:
  2440. # if the solid_geometry (type=list) is empty
  2441. if not uid_val['solid_geometry']:
  2442. tools_storage.pop(uid, None)
  2443. except KeyError:
  2444. tools_storage.pop(uid, None)
  2445. geo_obj.options["cnctooldia"] = str(tool)
  2446. geo_obj.multigeo = True
  2447. geo_obj.tools.clear()
  2448. geo_obj.tools = dict(tools_storage)
  2449. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2450. has_solid_geo = 0
  2451. for tooluid in geo_obj.tools:
  2452. if geo_obj.tools[tooluid]['solid_geometry']:
  2453. has_solid_geo += 1
  2454. if has_solid_geo == 0:
  2455. app_obj.inform.emit('[ERROR] %s' %
  2456. _("There is no NCC Geometry in the file.\n"
  2457. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2458. "Change the painting parameters and try again."))
  2459. return 'fail'
  2460. # check to see if geo_obj.tools is empty
  2461. # it will be updated only if there is a solid_geometry for tools
  2462. if geo_obj.tools:
  2463. if warning_flag == 0:
  2464. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2465. else:
  2466. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2467. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2468. str(warning_flag),
  2469. _("tools")))
  2470. return
  2471. # create the solid_geometry
  2472. geo_obj.solid_geometry = []
  2473. for tooluid in geo_obj.tools:
  2474. if geo_obj.tools[tooluid]['solid_geometry']:
  2475. try:
  2476. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2477. geo_obj.solid_geometry.append(geo)
  2478. except TypeError:
  2479. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2480. else:
  2481. # I will use this variable for this purpose although it was meant for something else
  2482. # signal that we have no geo in the object therefore don't create it
  2483. app_obj.poly_not_cleared = False
  2484. return "fail"
  2485. # ###########################################################################################
  2486. # Initializes the new geometry object for the case of the rest-machining ####################
  2487. # ###########################################################################################
  2488. def gen_clear_area_rest(geo_obj, app_obj):
  2489. assert geo_obj.kind == 'geometry', \
  2490. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  2491. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2492. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2493. # provide the app with a way to process the GUI events when in a blocking loop
  2494. if not run_threaded:
  2495. QtWidgets.QApplication.processEvents()
  2496. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2497. # will store the number of tools for which the isolation is broken
  2498. warning_flag = 0
  2499. sorted_tools.sort(reverse=True)
  2500. cleared_geo = []
  2501. cleared_by_last_tool = []
  2502. rest_geo = []
  2503. current_uid = 1
  2504. try:
  2505. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2506. except TypeError:
  2507. tool = eval(self.app.defaults["tools_ncctools"])
  2508. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2509. app_obj.poly_not_cleared = True
  2510. log.debug("NCC Tool. Calculate 'empty' area.")
  2511. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2512. # ###################################################################################################
  2513. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2514. # ###################################################################################################
  2515. if ncc_obj.kind == 'gerber' and not isotooldia:
  2516. sol_geo = ncc_obj.solid_geometry
  2517. if has_offset is True:
  2518. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2519. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2520. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2521. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2522. if empty == 'fail':
  2523. return 'fail'
  2524. if empty.is_empty:
  2525. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2526. _("Could not get the extent of the area to be non copper cleared."))
  2527. return 'fail'
  2528. elif ncc_obj.kind == 'gerber' and isotooldia:
  2529. isolated_geo = []
  2530. self.solid_geometry = ncc_obj.solid_geometry
  2531. # if milling type is climb then the move is counter-clockwise around features
  2532. milling_type = self.app.defaults["tools_nccmilling_type"]
  2533. for tool_iso in isotooldia:
  2534. new_geometry = []
  2535. if milling_type == 'cl':
  2536. isolated_geo = self.generate_envelope(tool_iso, 1)
  2537. else:
  2538. isolated_geo = self.generate_envelope(tool_iso, 0)
  2539. if isolated_geo == 'fail':
  2540. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2541. else:
  2542. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2543. "than isolation tool diameter."))
  2544. try:
  2545. for geo_elem in isolated_geo:
  2546. # provide the app with a way to process the GUI events when in a blocking loop
  2547. QtWidgets.QApplication.processEvents()
  2548. if self.app.abort_flag:
  2549. # graceful abort requested by the user
  2550. raise grace
  2551. if isinstance(geo_elem, Polygon):
  2552. for ring in self.poly2rings(geo_elem):
  2553. new_geo = ring.intersection(bounding_box)
  2554. if new_geo and not new_geo.is_empty:
  2555. new_geometry.append(new_geo)
  2556. elif isinstance(geo_elem, MultiPolygon):
  2557. for poly_g in geo_elem:
  2558. for ring in self.poly2rings(poly_g):
  2559. new_geo = ring.intersection(bounding_box)
  2560. if new_geo and not new_geo.is_empty:
  2561. new_geometry.append(new_geo)
  2562. elif isinstance(geo_elem, LineString):
  2563. new_geo = geo_elem.intersection(bounding_box)
  2564. if new_geo:
  2565. if not new_geo.is_empty:
  2566. new_geometry.append(new_geo)
  2567. elif isinstance(geo_elem, MultiLineString):
  2568. for line_elem in geo_elem:
  2569. new_geo = line_elem.intersection(bounding_box)
  2570. if new_geo and not new_geo.is_empty:
  2571. new_geometry.append(new_geo)
  2572. except TypeError:
  2573. try:
  2574. if isinstance(isolated_geo, Polygon):
  2575. for ring in self.poly2rings(isolated_geo):
  2576. new_geo = ring.intersection(bounding_box)
  2577. if new_geo:
  2578. if not new_geo.is_empty:
  2579. new_geometry.append(new_geo)
  2580. elif isinstance(isolated_geo, LineString):
  2581. new_geo = isolated_geo.intersection(bounding_box)
  2582. if new_geo and not new_geo.is_empty:
  2583. new_geometry.append(new_geo)
  2584. elif isinstance(isolated_geo, MultiLineString):
  2585. for line_elem in isolated_geo:
  2586. new_geo = line_elem.intersection(bounding_box)
  2587. if new_geo and not new_geo.is_empty:
  2588. new_geometry.append(new_geo)
  2589. except Exception:
  2590. pass
  2591. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2592. for geo_e in new_geometry:
  2593. if type(geo_e) == MultiLineString:
  2594. warning_flag += 1
  2595. break
  2596. for k, v in tools_storage.items():
  2597. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2598. tool_iso)):
  2599. current_uid = int(k)
  2600. # add the solid_geometry to the current too in self.paint_tools dictionary
  2601. # and then reset the temporary list that stored that solid_geometry
  2602. v['solid_geometry'] = deepcopy(new_geometry)
  2603. v['data']['name'] = name
  2604. break
  2605. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2606. sol_geo = cascaded_union(isolated_geo)
  2607. if has_offset is True:
  2608. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2609. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2610. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2611. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2612. if empty == 'fail':
  2613. return 'fail'
  2614. if empty.is_empty:
  2615. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2616. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2617. return 'fail'
  2618. elif ncc_obj.kind == 'geometry':
  2619. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2620. if has_offset is True:
  2621. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2622. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2623. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2624. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2625. if empty == 'fail':
  2626. return 'fail'
  2627. if empty.is_empty:
  2628. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2629. _("Could not get the extent of the area to be non copper cleared."))
  2630. return 'fail'
  2631. else:
  2632. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2633. return
  2634. if self.app.abort_flag:
  2635. # graceful abort requested by the user
  2636. raise grace
  2637. if type(empty) is Polygon:
  2638. empty = MultiPolygon([empty])
  2639. area = empty.buffer(0)
  2640. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2641. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2642. # Generate area for each tool
  2643. while sorted_tools:
  2644. if self.app.abort_flag:
  2645. # graceful abort requested by the user
  2646. raise grace
  2647. tool = sorted_tools.pop(0)
  2648. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2649. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2650. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2651. )
  2652. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2653. tool_used = tool - 1e-12
  2654. cleared_geo[:] = []
  2655. # Area to clear
  2656. for poly_r in cleared_by_last_tool:
  2657. # provide the app with a way to process the GUI events when in a blocking loop
  2658. QtWidgets.QApplication.processEvents()
  2659. if self.app.abort_flag:
  2660. # graceful abort requested by the user
  2661. raise grace
  2662. try:
  2663. area = area.difference(poly_r)
  2664. except Exception:
  2665. pass
  2666. cleared_by_last_tool[:] = []
  2667. # Transform area to MultiPolygon
  2668. if type(area) is Polygon:
  2669. area = MultiPolygon([area])
  2670. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2671. # and rest_geo it's a list
  2672. allparts = [p.buffer(0) for p in area.geoms]
  2673. allparts += deepcopy(rest_geo)
  2674. rest_geo[:] = []
  2675. area = MultiPolygon(deepcopy(allparts))
  2676. allparts[:] = []
  2677. # variables to display the percentage of work done
  2678. geo_len = len(area.geoms)
  2679. old_disp_number = 0
  2680. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2681. if area.geoms:
  2682. if len(area.geoms) > 0:
  2683. pol_nr = 0
  2684. for p in area.geoms:
  2685. if self.app.abort_flag:
  2686. # graceful abort requested by the user
  2687. raise grace
  2688. # clean the polygon
  2689. p = p.buffer(0)
  2690. if p is not None and p.is_valid:
  2691. # provide the app with a way to process the GUI events when in a blocking loop
  2692. QtWidgets.QApplication.processEvents()
  2693. if isinstance(p, Polygon):
  2694. try:
  2695. if ncc_method == 'standard':
  2696. cp = self.clear_polygon(p, tool_used,
  2697. self.circle_steps,
  2698. overlap=overlap, contour=contour, connect=connect,
  2699. prog_plot=False)
  2700. elif ncc_method == 'seed':
  2701. cp = self.clear_polygon2(p, tool_used,
  2702. self.circle_steps,
  2703. overlap=overlap, contour=contour, connect=connect,
  2704. prog_plot=False)
  2705. else:
  2706. cp = self.clear_polygon3(p, tool_used,
  2707. self.circle_steps,
  2708. overlap=overlap, contour=contour, connect=connect,
  2709. prog_plot=False)
  2710. cleared_geo.append(list(cp.get_objects()))
  2711. except Exception as ee:
  2712. log.warning("Polygon can't be cleared. %s" % str(ee))
  2713. # this polygon should be added to a list and then try clear it with
  2714. # a smaller tool
  2715. rest_geo.append(p)
  2716. elif isinstance(p, MultiPolygon):
  2717. for poly_p in p:
  2718. if poly_p is not None:
  2719. # provide the app with a way to process the GUI events when
  2720. # in a blocking loop
  2721. QtWidgets.QApplication.processEvents()
  2722. try:
  2723. if ncc_method == 'standard':
  2724. cp = self.clear_polygon(poly_p, tool_used,
  2725. self.circle_steps,
  2726. overlap=overlap, contour=contour,
  2727. connect=connect,
  2728. prog_plot=False)
  2729. elif ncc_method == 'seed':
  2730. cp = self.clear_polygon2(poly_p, tool_used,
  2731. self.circle_steps,
  2732. overlap=overlap, contour=contour,
  2733. connect=connect,
  2734. prog_plot=False)
  2735. else:
  2736. cp = self.clear_polygon3(poly_p, tool_used,
  2737. self.circle_steps,
  2738. overlap=overlap, contour=contour,
  2739. connect=connect,
  2740. prog_plot=False)
  2741. cleared_geo.append(list(cp.get_objects()))
  2742. except Exception as eee:
  2743. log.warning("Polygon can't be cleared. %s" % str(eee))
  2744. # this polygon should be added to a list and then try clear it with
  2745. # a smaller tool
  2746. rest_geo.append(poly_p)
  2747. pol_nr += 1
  2748. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2749. # log.debug("Polygons cleared: %d" % pol_nr)
  2750. if old_disp_number < disp_number <= 100:
  2751. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2752. old_disp_number = disp_number
  2753. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2754. if self.app.abort_flag:
  2755. # graceful abort requested by the user
  2756. raise grace
  2757. # check if there is a geometry at all in the cleared geometry
  2758. if cleared_geo:
  2759. # Overall cleared area
  2760. cleared_area = list(self.flatten_list(cleared_geo))
  2761. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2762. # for p in cleared_area])
  2763. # here we store the poly's already processed in the original geometry by the current tool
  2764. # into cleared_by_last_tool list
  2765. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2766. # the next tool
  2767. buffer_value = tool_used / 2
  2768. for p in cleared_area:
  2769. if self.app.abort_flag:
  2770. # graceful abort requested by the user
  2771. raise grace
  2772. r_poly = p.buffer(buffer_value)
  2773. cleared_by_last_tool.append(r_poly)
  2774. # find the tooluid associated with the current tool_dia so we know
  2775. # where to add the tool solid_geometry
  2776. for k, v in tools_storage.items():
  2777. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2778. tool)):
  2779. current_uid = int(k)
  2780. # add the solid_geometry to the current too in self.paint_tools dictionary
  2781. # and then reset the temporary list that stored that solid_geometry
  2782. v['solid_geometry'] = deepcopy(cleared_area)
  2783. v['data']['name'] = name
  2784. cleared_area[:] = []
  2785. break
  2786. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2787. else:
  2788. log.debug("There are no geometries in the cleared polygon.")
  2789. geo_obj.multigeo = True
  2790. geo_obj.options["cnctooldia"] = str(tool)
  2791. # check to see if geo_obj.tools is empty
  2792. # it will be updated only if there is a solid_geometry for tools
  2793. if geo_obj.tools:
  2794. if warning_flag == 0:
  2795. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2796. else:
  2797. self.app.inform.emit(
  2798. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2799. "isolation is broken for"), str(warning_flag), _("tools")))
  2800. return
  2801. # create the solid_geometry
  2802. geo_obj.solid_geometry = []
  2803. for tooluid in geo_obj.tools:
  2804. if geo_obj.tools[tooluid]['solid_geometry']:
  2805. try:
  2806. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2807. geo_obj.solid_geometry.append(geo)
  2808. except TypeError:
  2809. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2810. else:
  2811. # I will use this variable for this purpose although it was meant for something else
  2812. # signal that we have no geo in the object therefore don't create it
  2813. app_obj.poly_not_cleared = False
  2814. return "fail"
  2815. # ###########################################################################################
  2816. # Create the Job function and send it to the worker to be processed in another thread #######
  2817. # ###########################################################################################
  2818. def job_thread(app_obj):
  2819. try:
  2820. if rest_machining_choice is True:
  2821. app_obj.app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  2822. else:
  2823. app_obj.app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  2824. except grace:
  2825. if run_threaded:
  2826. proc.done()
  2827. return
  2828. except Exception:
  2829. if run_threaded:
  2830. proc.done()
  2831. traceback.print_stack()
  2832. return
  2833. if run_threaded:
  2834. proc.done()
  2835. else:
  2836. app_obj.proc_container.view.set_idle()
  2837. # focus on Selected Tab
  2838. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2839. if run_threaded:
  2840. # Promise object with the new name
  2841. self.app.collection.promise(name)
  2842. # Background
  2843. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2844. else:
  2845. job_thread(app_obj=self.app)
  2846. def get_ncc_empty_area(self, target, boundary=None):
  2847. """
  2848. Returns the complement of target geometry within
  2849. the given boundary polygon. If not specified, it defaults to
  2850. the rectangular bounding box of target geometry.
  2851. :param target: The geometry that is to be 'inverted'
  2852. :param boundary: A polygon that surrounds the entire solid geometry and from which we subtract in order to
  2853. create a "negative" geometry (geometry to be emptied of copper)
  2854. :return:
  2855. """
  2856. if isinstance(target, Polygon):
  2857. geo_len = 1
  2858. else:
  2859. geo_len = len(target)
  2860. pol_nr = 0
  2861. old_disp_number = 0
  2862. if boundary is None:
  2863. boundary = target.envelope
  2864. else:
  2865. boundary = boundary
  2866. try:
  2867. ret_val = boundary.difference(target)
  2868. except Exception:
  2869. try:
  2870. for el in target:
  2871. # provide the app with a way to process the GUI events when in a blocking loop
  2872. QtWidgets.QApplication.processEvents()
  2873. if self.app.abort_flag:
  2874. # graceful abort requested by the user
  2875. raise grace
  2876. boundary = boundary.difference(el)
  2877. pol_nr += 1
  2878. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2879. if old_disp_number < disp_number <= 100:
  2880. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2881. old_disp_number = disp_number
  2882. return boundary
  2883. except Exception:
  2884. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2885. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  2886. "Reload the Gerber file after this change."))
  2887. return 'fail'
  2888. return ret_val
  2889. @staticmethod
  2890. def poly2rings(poly):
  2891. return [poly.exterior] + [interior for interior in poly.interiors]
  2892. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2893. # isolation_geometry produces an envelope that is going on the left of the geometry
  2894. # (the copper features). To leave the least amount of burrs on the features
  2895. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2896. # the first pass is the one cutting all of the features, so it needs to be reversed
  2897. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2898. # to cut on the right side of the left over copper i.e on the left side of the features.
  2899. try:
  2900. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2901. except Exception as e:
  2902. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2903. return 'fail'
  2904. if invert:
  2905. try:
  2906. try:
  2907. pl = []
  2908. for p in geom:
  2909. if p is not None:
  2910. if isinstance(p, Polygon):
  2911. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2912. elif isinstance(p, LinearRing):
  2913. pl.append(Polygon(p.coords[::-1]))
  2914. geom = MultiPolygon(pl)
  2915. except TypeError:
  2916. if isinstance(geom, Polygon) and geom is not None:
  2917. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2918. elif isinstance(geom, LinearRing) and geom is not None:
  2919. geom = Polygon(geom.coords[::-1])
  2920. else:
  2921. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2922. type(geom))
  2923. except Exception as e:
  2924. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2925. return 'fail'
  2926. return geom
  2927. def on_ncc_tool_add_from_db_executed(self, tool):
  2928. """
  2929. Here add the tool from DB in the selected geometry object
  2930. :return:
  2931. """
  2932. tool_from_db = deepcopy(tool)
  2933. res = self.on_ncc_tool_from_db_inserted(tool=tool_from_db)
  2934. for idx in range(self.app.ui.plot_tab_area.count()):
  2935. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2936. wdg = self.app.ui.plot_tab_area.widget(idx)
  2937. wdg.deleteLater()
  2938. self.app.ui.plot_tab_area.removeTab(idx)
  2939. if res == 'fail':
  2940. return
  2941. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2942. # select last tool added
  2943. toolid = res
  2944. for row in range(self.ui.tools_table.rowCount()):
  2945. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2946. self.ui.tools_table.selectRow(row)
  2947. self.on_row_selection_change()
  2948. def on_ncc_tool_from_db_inserted(self, tool):
  2949. """
  2950. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2951. :param tool: a dict with the tool data
  2952. :return: None
  2953. """
  2954. self.ui_disconnect()
  2955. self.units = self.app.defaults['units'].upper()
  2956. tooldia = float(tool['tooldia'])
  2957. # construct a list of all 'tooluid' in the self.tools
  2958. tool_uid_list = []
  2959. for tooluid_key in self.ncc_tools:
  2960. tool_uid_item = int(tooluid_key)
  2961. tool_uid_list.append(tool_uid_item)
  2962. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2963. if not tool_uid_list:
  2964. max_uid = 0
  2965. else:
  2966. max_uid = max(tool_uid_list)
  2967. tooluid = max_uid + 1
  2968. tooldia = float('%.*f' % (self.decimals, tooldia))
  2969. tool_dias = []
  2970. for k, v in self.ncc_tools.items():
  2971. for tool_v in v.keys():
  2972. if tool_v == 'tooldia':
  2973. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2974. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2975. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2976. self.ui_connect()
  2977. return 'fail'
  2978. self.ncc_tools.update({
  2979. tooluid: {
  2980. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2981. 'offset': tool['offset'],
  2982. 'offset_value': tool['offset_value'],
  2983. 'type': tool['type'],
  2984. 'tool_type': tool['tool_type'],
  2985. 'data': deepcopy(tool['data']),
  2986. 'solid_geometry': []
  2987. }
  2988. })
  2989. self.ncc_tools[tooluid]['data']['name'] = '_ncc'
  2990. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2991. self.ui_connect()
  2992. self.build_ui()
  2993. # select the tool just added
  2994. for row in range(self.ui.tools_table.rowCount()):
  2995. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  2996. self.ui.tools_table.selectRow(row)
  2997. break
  2998. def on_ncc_tool_add_from_db_clicked(self):
  2999. """
  3000. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3001. and display the Tools Database tab in the form needed for the Tool adding
  3002. :return: None
  3003. """
  3004. # if the Tools Database is already opened focus on it
  3005. for idx in range(self.app.ui.plot_tab_area.count()):
  3006. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3007. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3008. break
  3009. self.app.on_tools_database(source='ncc')
  3010. self.app.tools_db_tab.ok_to_add = True
  3011. self.app.tools_db_tab.ui.buttons_frame.hide()
  3012. self.app.tools_db_tab.ui.add_tool_from_db.show()
  3013. self.app.tools_db_tab.ui.cancel_tool_from_db.show()
  3014. def reset_fields(self):
  3015. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3016. class NccUI:
  3017. toolName = _("Non-Copper Clearing")
  3018. def __init__(self, layout, app):
  3019. self.app = app
  3020. self.decimals = self.app.decimals
  3021. self.layout = layout
  3022. self.tools_frame = QtWidgets.QFrame()
  3023. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  3024. self.layout.addWidget(self.tools_frame)
  3025. self.tools_box = QtWidgets.QVBoxLayout()
  3026. self.tools_box.setContentsMargins(0, 0, 0, 0)
  3027. self.tools_frame.setLayout(self.tools_box)
  3028. # ## Title
  3029. title_label = QtWidgets.QLabel("%s" % self.toolName)
  3030. title_label.setStyleSheet("""
  3031. QLabel
  3032. {
  3033. font-size: 16px;
  3034. font-weight: bold;
  3035. }
  3036. """)
  3037. self.tools_box.addWidget(title_label)
  3038. # ## Form Layout
  3039. form_layout = QtWidgets.QFormLayout()
  3040. self.tools_box.addLayout(form_layout)
  3041. # ################################################
  3042. # ##### Type of object to be copper cleaned ######
  3043. # ################################################
  3044. # self.type_obj_radio = FCComboBox()
  3045. # self.type_obj_radio.addItem("Gerber")
  3046. # self.type_obj_radio.addItem("Excellon")
  3047. # self.type_obj_radio.addItem("Geometry")
  3048. #
  3049. # # we get rid of item1 ("Excellon") as it is not suitable
  3050. # self.type_obj_radio.view().setRowHidden(1, True)
  3051. # self.type_obj_radio.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  3052. # self.type_obj_radio.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  3053. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  3054. self.type_obj_combo_label.setToolTip(
  3055. _("Specify the type of object to be cleared of excess copper.\n"
  3056. "It can be of type: Gerber or Geometry.\n"
  3057. "What is selected here will dictate the kind\n"
  3058. "of objects that will populate the 'Object' combobox.")
  3059. )
  3060. self.type_obj_combo_label.setMinimumWidth(60)
  3061. self.type_obj_radio = RadioSet([{'label': _("Geometry"), 'value': 'geometry'},
  3062. {'label': _("Gerber"), 'value': 'gerber'}])
  3063. form_layout.addRow(self.type_obj_combo_label, self.type_obj_radio)
  3064. # ################################################
  3065. # ##### The object to be copper cleaned ##########
  3066. # ################################################
  3067. self.object_combo = FCComboBox()
  3068. self.object_combo.setModel(self.app.collection)
  3069. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3070. # self.object_combo.setCurrentIndex(1)
  3071. self.object_combo.is_last = True
  3072. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  3073. self.object_label.setToolTip(_("Object to be cleared of excess copper."))
  3074. form_layout.addRow(self.object_label, self.object_combo)
  3075. separator_line = QtWidgets.QFrame()
  3076. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3077. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3078. self.tools_box.addWidget(separator_line)
  3079. # ### Tools ## ##
  3080. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  3081. self.tools_table_label.setToolTip(
  3082. _("Tools pool from which the algorithm\n"
  3083. "will pick the ones used for copper clearing.")
  3084. )
  3085. self.tools_box.addWidget(self.tools_table_label)
  3086. self.tools_table = FCTable(drag_drop=True)
  3087. self.tools_box.addWidget(self.tools_table)
  3088. self.tools_table.setColumnCount(4)
  3089. # 3rd column is reserved (and hidden) for the tool ID
  3090. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  3091. self.tools_table.setColumnHidden(3, True)
  3092. self.tools_table.setSortingEnabled(False)
  3093. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3094. self.tools_table.horizontalHeaderItem(0).setToolTip(
  3095. _("This is the Tool Number.\n"
  3096. "Non copper clearing will start with the tool with the biggest \n"
  3097. "diameter, continuing until there are no more tools.\n"
  3098. "Only tools that create NCC clearing geometry will still be present\n"
  3099. "in the resulting geometry. This is because with some tools\n"
  3100. "this function will not be able to create painting geometry.")
  3101. )
  3102. self.tools_table.horizontalHeaderItem(1).setToolTip(
  3103. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  3104. "is the cut width into the material."))
  3105. self.tools_table.horizontalHeaderItem(2).setToolTip(
  3106. _("The Tool Type (TT) can be:\n"
  3107. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  3108. "the cut width in material is exactly the tool diameter.\n"
  3109. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  3110. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  3111. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  3112. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  3113. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  3114. "column of this table.\n"
  3115. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  3116. "in the resulting geometry as Isolation."))
  3117. # self.tools_table.horizontalHeaderItem(4).setToolTip(
  3118. # _("The 'Operation' can be:\n"
  3119. # "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  3120. # "If it's not successful then the non-copper clearing will fail, too.\n"
  3121. # "- Clear -> the regular non-copper clearing."))
  3122. grid1 = QtWidgets.QGridLayout()
  3123. self.tools_box.addLayout(grid1)
  3124. grid1.setColumnStretch(0, 0)
  3125. grid1.setColumnStretch(1, 1)
  3126. # Tool order
  3127. self.ncc_order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  3128. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  3129. "'No' --> means that the used order is the one in the tool table\n"
  3130. "'Forward' --> means that the tools will be ordered from small to big\n"
  3131. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  3132. "WARNING: using rest machining will automatically set the order\n"
  3133. "in reverse and disable this control."))
  3134. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  3135. {'label': _('Forward'), 'value': 'fwd'},
  3136. {'label': _('Reverse'), 'value': 'rev'}])
  3137. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  3138. "'No' --> means that the used order is the one in the tool table\n"
  3139. "'Forward' --> means that the tools will be ordered from small to big\n"
  3140. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  3141. "WARNING: using rest machining will automatically set the order\n"
  3142. "in reverse and disable this control."))
  3143. grid1.addWidget(self.ncc_order_label, 1, 0)
  3144. grid1.addWidget(self.ncc_order_radio, 1, 1)
  3145. separator_line = QtWidgets.QFrame()
  3146. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3147. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3148. grid1.addWidget(separator_line, 2, 0, 1, 2)
  3149. # #############################################################
  3150. # ############### Tool selection ##############################
  3151. # #############################################################
  3152. self.grid3 = QtWidgets.QGridLayout()
  3153. self.tools_box.addLayout(self.grid3)
  3154. self.grid3.setColumnStretch(0, 0)
  3155. self.grid3.setColumnStretch(1, 1)
  3156. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  3157. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  3158. # Tool Type Radio Button
  3159. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  3160. self.tool_type_label.setToolTip(
  3161. _("Default tool type:\n"
  3162. "- 'V-shape'\n"
  3163. "- Circular")
  3164. )
  3165. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  3166. {'label': _('Circular'), 'value': 'C1'}])
  3167. self.tool_type_radio.setToolTip(
  3168. _("Default tool type:\n"
  3169. "- 'V-shape'\n"
  3170. "- Circular")
  3171. )
  3172. self.tool_type_radio.setObjectName(_("Tool Type"))
  3173. self.grid3.addWidget(self.tool_type_label, 2, 0)
  3174. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  3175. # Tip Dia
  3176. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  3177. self.tipdialabel.setToolTip(
  3178. _("The tip diameter for V-Shape Tool"))
  3179. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3180. self.tipdia_entry.set_precision(self.decimals)
  3181. self.tipdia_entry.set_range(0.0000, 9999.9999)
  3182. self.tipdia_entry.setSingleStep(0.1)
  3183. self.tipdia_entry.setObjectName(_("V-Tip Dia"))
  3184. self.grid3.addWidget(self.tipdialabel, 3, 0)
  3185. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  3186. # Tip Angle
  3187. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  3188. self.tipanglelabel.setToolTip(
  3189. _("The tip angle for V-Shape Tool.\n"
  3190. "In degree."))
  3191. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3192. self.tipangle_entry.set_precision(self.decimals)
  3193. self.tipangle_entry.set_range(0.0000, 180.0000)
  3194. self.tipangle_entry.setSingleStep(5)
  3195. self.tipangle_entry.setObjectName(_("V-Tip Angle"))
  3196. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  3197. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  3198. # Cut Z entry
  3199. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  3200. cutzlabel.setToolTip(
  3201. _("Depth of cut into material. Negative value.\n"
  3202. "In FlatCAM units.")
  3203. )
  3204. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3205. self.cutz_entry.set_precision(self.decimals)
  3206. self.cutz_entry.set_range(-99999.9999, 0.0000)
  3207. self.cutz_entry.setObjectName(_("Cut Z"))
  3208. self.cutz_entry.setToolTip(
  3209. _("Depth of cut into material. Negative value.\n"
  3210. "In FlatCAM units.")
  3211. )
  3212. self.grid3.addWidget(cutzlabel, 5, 0)
  3213. self.grid3.addWidget(self.cutz_entry, 5, 1)
  3214. # ### Tool Diameter ####
  3215. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  3216. self.addtool_entry_lbl.setToolTip(
  3217. _("Diameter for the new tool to add in the Tool Table.\n"
  3218. "If the tool is V-shape type then this value is automatically\n"
  3219. "calculated from the other parameters.")
  3220. )
  3221. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3222. self.addtool_entry.set_precision(self.decimals)
  3223. self.addtool_entry.set_range(0.000, 9999.9999)
  3224. self.addtool_entry.setObjectName(_("Tool Dia"))
  3225. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  3226. self.grid3.addWidget(self.addtool_entry, 6, 1)
  3227. hlay = QtWidgets.QHBoxLayout()
  3228. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  3229. self.addtool_btn.setToolTip(
  3230. _("Add a new tool to the Tool Table\n"
  3231. "with the diameter specified above.")
  3232. )
  3233. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  3234. self.addtool_from_db_btn.setToolTip(
  3235. _("Add a new tool to the Tool Table\n"
  3236. "from the Tool Database.\n"
  3237. "Tool database administration in Menu: Options -> Tools Database")
  3238. )
  3239. hlay.addWidget(self.addtool_btn)
  3240. hlay.addWidget(self.addtool_from_db_btn)
  3241. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  3242. separator_line = QtWidgets.QFrame()
  3243. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3244. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3245. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  3246. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  3247. self.deltool_btn.setToolTip(
  3248. _("Delete a selection of tools in the Tool Table\n"
  3249. "by first selecting a row(s) in the Tool Table.")
  3250. )
  3251. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  3252. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  3253. separator_line = QtWidgets.QFrame()
  3254. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3255. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3256. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  3257. self.tool_data_label = QtWidgets.QLabel(
  3258. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  3259. self.tool_data_label.setToolTip(
  3260. _(
  3261. "The data used for creating GCode.\n"
  3262. "Each tool store it's own set of such data."
  3263. )
  3264. )
  3265. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  3266. # Operation
  3267. op_label = QtWidgets.QLabel('%s:' % _('Operation'))
  3268. op_label.setToolTip(
  3269. _("The 'Operation' can be:\n"
  3270. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  3271. "If it's not successful then the non-copper clearing will fail, too.\n"
  3272. "- Clear -> the regular non-copper clearing.")
  3273. )
  3274. self.op_radio = RadioSet([
  3275. {"label": _("Clear"), "value": "clear"},
  3276. {"label": _("Isolation"), "value": "iso"}
  3277. ], orientation='horizontal', stretch=False)
  3278. self.op_radio.setObjectName("n_operation")
  3279. self.grid3.addWidget(op_label, 13, 0)
  3280. self.grid3.addWidget(self.op_radio, 13, 1)
  3281. # Milling Type Radio Button
  3282. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  3283. self.milling_type_label.setToolTip(
  3284. _("Milling type when the selected tool is of type: 'iso_op':\n"
  3285. "- climb / best for precision milling and to reduce tool usage\n"
  3286. "- conventional / useful when there is no backlash compensation")
  3287. )
  3288. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  3289. {'label': _('Conventional'), 'value': 'cv'}])
  3290. self.milling_type_radio.setToolTip(
  3291. _("Milling type when the selected tool is of type: 'iso_op':\n"
  3292. "- climb / best for precision milling and to reduce tool usage\n"
  3293. "- conventional / useful when there is no backlash compensation")
  3294. )
  3295. self.milling_type_radio.setObjectName("n_milling_type")
  3296. self.milling_type_label.setEnabled(False)
  3297. self.milling_type_radio.setEnabled(False)
  3298. self.grid3.addWidget(self.milling_type_label, 14, 0)
  3299. self.grid3.addWidget(self.milling_type_radio, 14, 1)
  3300. # Overlap Entry
  3301. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  3302. nccoverlabel.setToolTip(
  3303. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  3304. "Adjust the value starting with lower values\n"
  3305. "and increasing it if areas that should be cleared are still \n"
  3306. "not cleared.\n"
  3307. "Lower values = faster processing, faster execution on CNC.\n"
  3308. "Higher values = slow processing and slow execution on CNC\n"
  3309. "due of too many paths.")
  3310. )
  3311. self.ncc_overlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  3312. self.ncc_overlap_entry.set_precision(self.decimals)
  3313. self.ncc_overlap_entry.setWrapping(True)
  3314. self.ncc_overlap_entry.setRange(0.000, 99.9999)
  3315. self.ncc_overlap_entry.setSingleStep(0.1)
  3316. self.ncc_overlap_entry.setObjectName("n_overlap")
  3317. self.grid3.addWidget(nccoverlabel, 15, 0)
  3318. self.grid3.addWidget(self.ncc_overlap_entry, 15, 1)
  3319. # Method
  3320. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  3321. methodlabel.setToolTip(
  3322. _("Algorithm for copper clearing:\n"
  3323. "- Standard: Fixed step inwards.\n"
  3324. "- Seed-based: Outwards from seed.\n"
  3325. "- Line-based: Parallel lines.")
  3326. )
  3327. # self.ncc_method_radio = RadioSet([
  3328. # {"label": _("Standard"), "value": "standard"},
  3329. # {"label": _("Seed-based"), "value": "seed"},
  3330. # {"label": _("Straight lines"), "value": "lines"}
  3331. # ], orientation='vertical', stretch=False)
  3332. self.ncc_method_combo = FCComboBox()
  3333. self.ncc_method_combo.addItems(
  3334. [_("Standard"), _("Seed"), _("Lines"), _("Combo")]
  3335. )
  3336. self.ncc_method_combo.setObjectName("n_method")
  3337. self.grid3.addWidget(methodlabel, 16, 0)
  3338. self.grid3.addWidget(self.ncc_method_combo, 16, 1)
  3339. # Margin
  3340. self.nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  3341. self.nccmarginlabel.setToolTip(
  3342. _("Bounding box margin.")
  3343. )
  3344. self.ncc_margin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3345. self.ncc_margin_entry.set_precision(self.decimals)
  3346. self.ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  3347. self.ncc_margin_entry.setObjectName("n_margin")
  3348. self.grid3.addWidget(self.nccmarginlabel, 17, 0)
  3349. self.grid3.addWidget(self.ncc_margin_entry, 17, 1)
  3350. # Connect lines
  3351. self.ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  3352. self.ncc_connect_cb.setObjectName("n_connect")
  3353. self.ncc_connect_cb.setToolTip(
  3354. _("Draw lines between resulting\n"
  3355. "segments to minimize tool lifts.")
  3356. )
  3357. self.grid3.addWidget(self.ncc_connect_cb, 18, 0)
  3358. # Contour
  3359. self.ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  3360. self.ncc_contour_cb.setObjectName("n_contour")
  3361. self.ncc_contour_cb.setToolTip(
  3362. _("Cut around the perimeter of the polygon\n"
  3363. "to trim rough edges.")
  3364. )
  3365. self.grid3.addWidget(self.ncc_contour_cb, 18, 1)
  3366. # ## NCC Offset choice
  3367. self.ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  3368. self.ncc_choice_offset_cb.setObjectName("n_offset")
  3369. self.ncc_choice_offset_cb.setToolTip(
  3370. _("If used, it will add an offset to the copper features.\n"
  3371. "The copper clearing will finish to a distance\n"
  3372. "from the copper features.\n"
  3373. "The value can be between 0 and 10 FlatCAM units.")
  3374. )
  3375. self.grid3.addWidget(self.ncc_choice_offset_cb, 19, 0)
  3376. # ## NCC Offset Entry
  3377. self.ncc_offset_spinner = FCDoubleSpinner(callback=self.confirmation_message)
  3378. self.ncc_offset_spinner.set_range(0.00, 10.00)
  3379. self.ncc_offset_spinner.set_precision(4)
  3380. self.ncc_offset_spinner.setWrapping(True)
  3381. self.ncc_offset_spinner.setObjectName("n_offset_value")
  3382. units = self.app.defaults['units'].upper()
  3383. if units == 'MM':
  3384. self.ncc_offset_spinner.setSingleStep(0.1)
  3385. else:
  3386. self.ncc_offset_spinner.setSingleStep(0.01)
  3387. self.grid3.addWidget(self.ncc_offset_spinner, 19, 1)
  3388. self.ois_ncc_offset = OptionalInputSection(self.ncc_choice_offset_cb, [self.ncc_offset_spinner])
  3389. separator_line = QtWidgets.QFrame()
  3390. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3391. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3392. self.grid3.addWidget(separator_line, 21, 0, 1, 2)
  3393. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  3394. self.apply_param_to_all.setToolTip(
  3395. _("The parameters in the current form will be applied\n"
  3396. "on all the tools from the Tool Table.")
  3397. )
  3398. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  3399. separator_line = QtWidgets.QFrame()
  3400. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3401. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3402. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  3403. # General Parameters
  3404. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  3405. self.gen_param_label.setToolTip(
  3406. _("Parameters that are common for all tools.")
  3407. )
  3408. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  3409. # Rest Machining
  3410. self.ncc_rest_cb = FCCheckBox('%s' % _("Rest"))
  3411. self.ncc_rest_cb.setObjectName("n_rest_machining")
  3412. self.ncc_rest_cb.setToolTip(
  3413. _("If checked, use 'rest machining'.\n"
  3414. "Basically it will clear copper outside PCB features,\n"
  3415. "using the biggest tool and continue with the next tools,\n"
  3416. "from bigger to smaller, to clear areas of copper that\n"
  3417. "could not be cleared by previous tool, until there is\n"
  3418. "no more copper to clear or there are no more tools.\n"
  3419. "If not checked, use the standard algorithm.")
  3420. )
  3421. self.grid3.addWidget(self.ncc_rest_cb, 25, 0, 1, 2)
  3422. # Rest Margin
  3423. self.rest_nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  3424. self.rest_nccmarginlabel.setToolTip(
  3425. _("Bounding box margin.")
  3426. )
  3427. self.rest_ncc_margin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3428. self.rest_ncc_margin_entry.set_precision(self.decimals)
  3429. self.rest_ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  3430. self.rest_ncc_margin_entry.setObjectName("n_margin")
  3431. self.grid3.addWidget(self.rest_nccmarginlabel, 26, 0)
  3432. self.grid3.addWidget(self.rest_ncc_margin_entry, 26, 1)
  3433. # Rest Connect lines
  3434. self.rest_ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  3435. self.rest_ncc_connect_cb.setToolTip(
  3436. _("Draw lines between resulting\n"
  3437. "segments to minimize tool lifts.")
  3438. )
  3439. self.grid3.addWidget(self.rest_ncc_connect_cb, 27, 0)
  3440. # Rest Contour
  3441. self.rest_ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  3442. self.rest_ncc_contour_cb.setToolTip(
  3443. _("Cut around the perimeter of the polygon\n"
  3444. "to trim rough edges.")
  3445. )
  3446. self.grid3.addWidget(self.rest_ncc_contour_cb, 27, 1)
  3447. # ## Rest NCC Offset choice
  3448. self.rest_ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  3449. self.rest_ncc_choice_offset_cb.setToolTip(
  3450. _("If used, it will add an offset to the copper features.\n"
  3451. "The copper clearing will finish to a distance\n"
  3452. "from the copper features.\n"
  3453. "The value can be between 0 and 10 FlatCAM units.")
  3454. )
  3455. self.grid3.addWidget(self.rest_ncc_choice_offset_cb, 28, 0)
  3456. # ## Rest NCC Offset Entry
  3457. self.rest_ncc_offset_spinner = FCDoubleSpinner(callback=self.confirmation_message)
  3458. self.rest_ncc_offset_spinner.set_range(0.00, 10.00)
  3459. self.rest_ncc_offset_spinner.set_precision(4)
  3460. self.rest_ncc_offset_spinner.setWrapping(True)
  3461. units = self.app.defaults['units'].upper()
  3462. if units == 'MM':
  3463. self.rest_ncc_offset_spinner.setSingleStep(0.1)
  3464. else:
  3465. self.rest_ncc_offset_spinner.setSingleStep(0.01)
  3466. self.grid3.addWidget(self.rest_ncc_offset_spinner, 28, 1)
  3467. self.rest_ois_ncc_offset = OptionalInputSection(self.rest_ncc_choice_offset_cb, [self.rest_ncc_offset_spinner])
  3468. # ## Reference
  3469. # self.select_radio = RadioSet([
  3470. # {'label': _('Itself'), 'value': 'itself'},
  3471. # {"label": _("Area Selection"), "value": "area"},
  3472. # {'label': _("Reference Object"), 'value': 'box'}
  3473. # ], orientation='vertical', stretch=False)
  3474. self.select_combo = FCComboBox()
  3475. self.select_combo.addItems(
  3476. [_("Itself"), _("Area Selection"), _("Reference Object")]
  3477. )
  3478. self.select_combo.setObjectName("n_selection")
  3479. self.select_label = QtWidgets.QLabel('%s:' % _("Selection"))
  3480. self.select_label.setToolTip(
  3481. _("Selection of area to be processed.\n"
  3482. "- 'Itself' - the processing extent is based on the object that is processed.\n "
  3483. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  3484. "- 'Reference Object' - will process the area specified by another object.")
  3485. )
  3486. self.grid3.addWidget(self.select_label, 29, 0, )
  3487. self.grid3.addWidget(self.select_combo, 29, 1)
  3488. form1 = QtWidgets.QFormLayout()
  3489. self.grid3.addLayout(form1, 30, 0, 1, 2)
  3490. self.reference_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  3491. self.reference_combo_type_label.setToolTip(
  3492. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  3493. "It can be Gerber, Excellon or Geometry.")
  3494. )
  3495. self.reference_combo_type = FCComboBox()
  3496. self.reference_combo_type.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  3497. form1.addRow(self.reference_combo_type_label, self.reference_combo_type)
  3498. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  3499. self.reference_combo_label.setToolTip(
  3500. _("The FlatCAM object to be used as non copper clearing reference.")
  3501. )
  3502. self.reference_combo = FCComboBox()
  3503. self.reference_combo.setModel(self.app.collection)
  3504. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3505. self.reference_combo.is_last = True
  3506. form1.addRow(self.reference_combo_label, self.reference_combo)
  3507. self.reference_combo.hide()
  3508. self.reference_combo_label.hide()
  3509. self.reference_combo_type.hide()
  3510. self.reference_combo_type_label.hide()
  3511. # Area Selection shape
  3512. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  3513. self.area_shape_label.setToolTip(
  3514. _("The kind of selection shape used for area selection.")
  3515. )
  3516. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  3517. {'label': _("Polygon"), 'value': 'polygon'}])
  3518. self.grid3.addWidget(self.area_shape_label, 31, 0)
  3519. self.grid3.addWidget(self.area_shape_radio, 31, 1)
  3520. self.area_shape_label.hide()
  3521. self.area_shape_radio.hide()
  3522. separator_line = QtWidgets.QFrame()
  3523. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3524. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3525. self.grid3.addWidget(separator_line, 32, 0, 1, 2)
  3526. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  3527. self.generate_ncc_button.setToolTip(
  3528. _("Create the Geometry Object\n"
  3529. "for non-copper routing.")
  3530. )
  3531. self.generate_ncc_button.setStyleSheet("""
  3532. QPushButton
  3533. {
  3534. font-weight: bold;
  3535. }
  3536. """)
  3537. self.tools_box.addWidget(self.generate_ncc_button)
  3538. self.tools_box.addStretch()
  3539. # ## Reset Tool
  3540. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  3541. self.reset_button.setToolTip(
  3542. _("Will reset the tool parameters.")
  3543. )
  3544. self.reset_button.setStyleSheet("""
  3545. QPushButton
  3546. {
  3547. font-weight: bold;
  3548. }
  3549. """)
  3550. self.tools_box.addWidget(self.reset_button)
  3551. # ############################ FINSIHED GUI ###################################
  3552. # #############################################################################
  3553. def confirmation_message(self, accepted, minval, maxval):
  3554. if accepted is False:
  3555. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  3556. self.decimals,
  3557. minval,
  3558. self.decimals,
  3559. maxval), False)
  3560. else:
  3561. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  3562. def confirmation_message_int(self, accepted, minval, maxval):
  3563. if accepted is False:
  3564. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  3565. (_("Edited value is out of range"), minval, maxval), False)
  3566. else:
  3567. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)