ToolNCC.py 199 KB

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