ToolNCC.py 200 KB

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