ToolNCC.py 199 KB

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