ToolNCC.py 200 KB

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