ToolNCC.py 198 KB

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