ToolNCC.py 200 KB

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