ToolNCC.py 206 KB

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