FlatCAMObj.py 255 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. import copy
  9. import inspect # TODO: For debugging only.
  10. from datetime import datetime
  11. from flatcamGUI.ObjectUI import *
  12. from FlatCAMCommon import LoudDict
  13. from camlib import *
  14. import itertools
  15. import gettext
  16. import FlatCAMTranslation as fcTranslate
  17. import builtins
  18. fcTranslate.apply_language('strings')
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. class ObjectDeleted(Exception):
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. pass
  24. class ValidationError(Exception):
  25. def __init__(self, message, errors):
  26. super().__init__(message)
  27. self.errors = errors
  28. # #######################################
  29. # # FlatCAMObj ##
  30. # #######################################
  31. class FlatCAMObj(QtCore.QObject):
  32. """
  33. Base type of objects handled in FlatCAM. These become interactive
  34. in the GUI, can be plotted, and their options can be modified
  35. by the user in their respective forms.
  36. """
  37. # Instance of the application to which these are related.
  38. # The app should set this value.
  39. app = None
  40. def __init__(self, name):
  41. """
  42. Constructor.
  43. :param name: Name of the object given by the user.
  44. :return: FlatCAMObj
  45. """
  46. QtCore.QObject.__init__(self)
  47. # View
  48. self.ui = None
  49. self.options = LoudDict(name=name)
  50. self.options.set_change_callback(self.on_options_change)
  51. self.form_fields = {}
  52. # store here the default data for Geometry Data
  53. self.default_data = {}
  54. self.kind = None # Override with proper name
  55. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  56. self.shapes = self.app.plotcanvas.new_shape_group()
  57. # self.mark_shapes = self.app.plotcanvas.new_shape_collection(layers=2)
  58. self.mark_shapes = {}
  59. self.item = None # Link with project view item
  60. self.muted_ui = False
  61. self.deleted = False
  62. try:
  63. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  64. self.app.defaults["global_tolerance"] else 0.01
  65. except ValueError:
  66. self._drawing_tolerance = 0.01
  67. self.isHovering = False
  68. self.notHovering = True
  69. self.units = 'IN'
  70. # assert isinstance(self.ui, ObjectUI)
  71. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  72. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  73. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  74. def __del__(self):
  75. pass
  76. def __str__(self):
  77. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  78. def from_dict(self, d):
  79. """
  80. This supersedes ``from_dict`` in derived classes. Derived classes
  81. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  82. ``self.options`` is only updated, not overwritten. This ensures that
  83. options set by the app do not vanish when reading the objects
  84. from a project file.
  85. :param d: Dictionary with attributes to set.
  86. :return: None
  87. """
  88. for attr in self.ser_attrs:
  89. if attr == 'options':
  90. self.options.update(d[attr])
  91. else:
  92. try:
  93. setattr(self, attr, d[attr])
  94. except KeyError:
  95. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. "
  96. "Means that we are loading an old project that don't"
  97. "have all attributes in the latest FlatCAM." % str(attr))
  98. pass
  99. def on_options_change(self, key):
  100. # Update form on programmatically options change
  101. self.set_form_item(key)
  102. # Set object visibility
  103. if key == 'plot':
  104. self.visible = self.options['plot']
  105. self.optionChanged.emit(key)
  106. def set_ui(self, ui):
  107. self.ui = ui
  108. self.form_fields = {"name": self.ui.name_entry}
  109. assert isinstance(self.ui, ObjectUI)
  110. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  111. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  112. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  113. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  114. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  115. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  116. def build_ui(self):
  117. """
  118. Sets up the UI/form for this object. Show the UI
  119. in the App.
  120. :return: None
  121. :rtype: None
  122. """
  123. self.muted_ui = True
  124. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  125. # Remove anything else in the box
  126. # box_children = self.app.ui.notebook.selected_contents.get_children()
  127. # for child in box_children:
  128. # self.app.ui.notebook.selected_contents.remove(child)
  129. # while self.app.ui.selected_layout.count():
  130. # self.app.ui.selected_layout.takeAt(0)
  131. # Put in the UI
  132. # box_selected.pack_start(sw, True, True, 0)
  133. # self.app.ui.notebook.selected_contents.add(self.ui)
  134. # self.app.ui.selected_layout.addWidget(self.ui)
  135. try:
  136. self.app.ui.selected_scroll_area.takeWidget()
  137. except Exception as e:
  138. self.app.log.debug("Nothing to remove")
  139. self.app.ui.selected_scroll_area.setWidget(self.ui)
  140. self.muted_ui = False
  141. def on_name_activate(self):
  142. old_name = copy(self.options["name"])
  143. new_name = self.ui.name_entry.get_value()
  144. if new_name != old_name:
  145. # update the SHELL auto-completer model data
  146. try:
  147. self.app.myKeywords.remove(old_name)
  148. self.app.myKeywords.append(new_name)
  149. self.app.shell._edit.set_model_data(self.app.myKeywords)
  150. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  151. except Exception as e:
  152. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  153. self.options["name"] = self.ui.name_entry.get_value()
  154. self.default_data["name"] = self.ui.name_entry.get_value()
  155. self.app.collection.update_view()
  156. self.app.inform.emit(_("[success] Name changed from {old} to {new}").format(old=old_name, new=new_name))
  157. def on_offset_button_click(self):
  158. self.app.report_usage("obj_on_offset_button")
  159. self.read_form()
  160. vector_val = self.ui.offsetvector_entry.get_value()
  161. self.offset(vector_val)
  162. self.plot()
  163. self.app.object_changed.emit(self)
  164. def on_scale_button_click(self):
  165. self.app.report_usage("obj_on_scale_button")
  166. self.read_form()
  167. factor = self.ui.scale_entry.get_value()
  168. self.scale(factor)
  169. self.plot()
  170. self.app.object_changed.emit(self)
  171. def on_skew_button_click(self):
  172. self.app.report_usage("obj_on_skew_button")
  173. self.read_form()
  174. x_angle = self.ui.xangle_entry.get_value()
  175. y_angle = self.ui.yangle_entry.get_value()
  176. self.skew(x_angle, y_angle)
  177. self.plot()
  178. self.app.object_changed.emit(self)
  179. def to_form(self):
  180. """
  181. Copies options to the UI form.
  182. :return: None
  183. """
  184. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  185. for option in self.options:
  186. try:
  187. self.set_form_item(option)
  188. except Exception as e:
  189. self.app.log.warning("Unexpected error:", sys.exc_info())
  190. def read_form(self):
  191. """
  192. Reads form into ``self.options``.
  193. :return: None
  194. :rtype: None
  195. """
  196. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  197. for option in self.options:
  198. try:
  199. self.read_form_item(option)
  200. except Exception as e:
  201. self.app.log.warning("Unexpected error:", sys.exc_info())
  202. def set_form_item(self, option):
  203. """
  204. Copies the specified option to the UI form.
  205. :param option: Name of the option (Key in ``self.options``).
  206. :type option: str
  207. :return: None
  208. """
  209. try:
  210. self.form_fields[option].set_value(self.options[option])
  211. except KeyError:
  212. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  213. pass
  214. def read_form_item(self, option):
  215. """
  216. Reads the specified option from the UI form into ``self.options``.
  217. :param option: Name of the option.
  218. :type option: str
  219. :return: None
  220. """
  221. try:
  222. self.options[option] = self.form_fields[option].get_value()
  223. except KeyError:
  224. self.app.log.warning("Failed to read option from field: %s" % option)
  225. def plot(self):
  226. """
  227. Plot this object (Extend this method to implement the actual plotting).
  228. Call this in descendants before doing the plotting.
  229. :return: Whether to continue plotting or not depending on the "plot" option.
  230. :rtype: bool
  231. """
  232. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  233. if self.deleted:
  234. return False
  235. self.clear()
  236. return True
  237. def serialize(self):
  238. """
  239. Returns a representation of the object as a dictionary so
  240. it can be later exported as JSON. Override this method.
  241. :return: Dictionary representing the object
  242. :rtype: dict
  243. """
  244. return
  245. def deserialize(self, obj_dict):
  246. """
  247. Re-builds an object from its serialized version.
  248. :param obj_dict: Dictionary representing a FlatCAMObj
  249. :type obj_dict: dict
  250. :return: None
  251. """
  252. return
  253. def add_shape(self, **kwargs):
  254. if self.deleted:
  255. raise ObjectDeleted()
  256. else:
  257. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  258. return key
  259. def add_mark_shape(self, apid, **kwargs):
  260. if self.deleted:
  261. raise ObjectDeleted()
  262. else:
  263. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, **kwargs)
  264. return key
  265. @property
  266. def visible(self):
  267. return self.shapes.visible
  268. @visible.setter
  269. def visible(self, value, threaded=False):
  270. log.debug("FlatCAMObj.visible()")
  271. def worker_task(app_obj):
  272. app_obj.shapes.visible = value
  273. # Not all object types has annotations
  274. try:
  275. app_obj.annotation.visible = value
  276. except Exception as e:
  277. pass
  278. if threaded is False:
  279. worker_task(self)
  280. else:
  281. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  282. @property
  283. def drawing_tolerance(self):
  284. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  285. @drawing_tolerance.setter
  286. def drawing_tolerance(self, value):
  287. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  288. def clear(self, update=False):
  289. self.shapes.clear(update)
  290. # Not all object types has annotations
  291. try:
  292. self.annotation.clear(update)
  293. except AttributeError:
  294. pass
  295. def delete(self):
  296. # Free resources
  297. del self.ui
  298. del self.options
  299. # Set flag
  300. self.deleted = True
  301. class FlatCAMGerber(FlatCAMObj, Gerber):
  302. """
  303. Represents Gerber code.
  304. """
  305. optionChanged = QtCore.pyqtSignal(str)
  306. replotApertures = QtCore.pyqtSignal()
  307. ui_type = GerberObjectUI
  308. def merge(self, grb_list, grb_final):
  309. """
  310. Merges the geometry of objects in geo_list into
  311. the geometry of geo_final.
  312. :param grb_list: List of FlatCAMGerber Objects to join.
  313. :param grb_final: Destination FlatCAMGeometry object.
  314. :return: None
  315. """
  316. if grb_final.solid_geometry is None:
  317. grb_final.solid_geometry = []
  318. grb_final.follow_geometry = []
  319. if not grb_final.apertures:
  320. grb_final.apertures = {}
  321. if type(grb_final.solid_geometry) is not list:
  322. grb_final.solid_geometry = [grb_final.solid_geometry]
  323. grb_final.follow_geometry = [grb_final.follow_geometry]
  324. for grb in grb_list:
  325. # Expand lists
  326. if type(grb) is list:
  327. FlatCAMGerber.merge(grb, grb_final)
  328. else: # If not list, just append
  329. for option in grb.options:
  330. if option is not 'name':
  331. try:
  332. grb_final.options[option] = grb.options[option]
  333. except KeyError:
  334. log.warning("Failed to copy option.", option)
  335. try:
  336. for geos in grb.solid_geometry:
  337. grb_final.solid_geometry.append(geos)
  338. grb_final.follow_geometry.append(geos)
  339. except TypeError:
  340. grb_final.solid_geometry.append(grb.solid_geometry)
  341. grb_final.follow_geometry.append(grb.solid_geometry)
  342. for ap in grb.apertures:
  343. if ap not in grb_final.apertures:
  344. grb_final.apertures[ap] = grb.apertures[ap]
  345. else:
  346. # create a list of integers out of the grb.apertures keys and find the max of that value
  347. # then, the aperture duplicate is assigned an id value incremented with 1,
  348. # and finally made string because the apertures dict keys are strings
  349. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  350. grb_final.apertures[max_ap] = {}
  351. grb_final.apertures[max_ap]['geometry'] = []
  352. for k, v in grb.apertures[ap].items():
  353. grb_final.apertures[max_ap][k] = deepcopy(v)
  354. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  355. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  356. def __init__(self, name):
  357. Gerber.__init__(self, steps_per_circle=int(self.app.defaults["gerber_circle_steps"]))
  358. FlatCAMObj.__init__(self, name)
  359. self.kind = "gerber"
  360. # The 'name' is already in self.options from FlatCAMObj
  361. # Automatically updates the UI
  362. self.options.update({
  363. "plot": True,
  364. "multicolored": False,
  365. "solid": False,
  366. "isotooldia": 0.016,
  367. "isopasses": 1,
  368. "isooverlap": 0.15,
  369. "milling_type": "cl",
  370. "combine_passes": True,
  371. "noncoppermargin": 0.0,
  372. "noncopperrounded": False,
  373. "bboxmargin": 0.0,
  374. "bboxrounded": False,
  375. "aperture_display": False,
  376. "follow": False
  377. })
  378. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  379. self.iso_type = 2
  380. self.multigeo = False
  381. self.follow = False
  382. self.apertures_row = 0
  383. # store the source file here
  384. self.source_file = ""
  385. # list of rows with apertures plotted
  386. self.marked_rows = []
  387. # Attributes to be included in serialization
  388. # Always append to it because it carries contents
  389. # from predecessors.
  390. self.ser_attrs += ['options', 'kind']
  391. def set_ui(self, ui):
  392. """
  393. Maps options with GUI inputs.
  394. Connects GUI events to methods.
  395. :param ui: GUI object.
  396. :type ui: GerberObjectUI
  397. :return: None
  398. """
  399. FlatCAMObj.set_ui(self, ui)
  400. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  401. self.replotApertures.connect(self.on_mark_cb_click_table)
  402. self.form_fields.update({
  403. "plot": self.ui.plot_cb,
  404. "multicolored": self.ui.multicolored_cb,
  405. "solid": self.ui.solid_cb,
  406. "isotooldia": self.ui.iso_tool_dia_entry,
  407. "isopasses": self.ui.iso_width_entry,
  408. "isooverlap": self.ui.iso_overlap_entry,
  409. "milling_type": self.ui.milling_type_radio,
  410. "combine_passes": self.ui.combine_passes_cb,
  411. "noncoppermargin": self.ui.noncopper_margin_entry,
  412. "noncopperrounded": self.ui.noncopper_rounded_cb,
  413. "bboxmargin": self.ui.bbmargin_entry,
  414. "bboxrounded": self.ui.bbrounded_cb,
  415. "aperture_display": self.ui.aperture_table_visibility_cb,
  416. "follow": self.ui.follow_cb
  417. })
  418. # Fill form fields only on object create
  419. self.to_form()
  420. assert isinstance(self.ui, GerberObjectUI)
  421. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  422. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  423. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  424. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  425. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  426. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  427. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  428. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  429. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  430. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  431. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  432. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  433. # Show/Hide Advanced Options
  434. if self.app.defaults["global_app_level"] == 'b':
  435. self.ui.level.setText(_(
  436. '<span style="color:green;"><b>Basic</b></span>'
  437. ))
  438. self.ui.apertures_table_label.hide()
  439. self.ui.aperture_table_visibility_cb.hide()
  440. self.ui.milling_type_label.hide()
  441. self.ui.milling_type_radio.hide()
  442. self.ui.generate_ext_iso_button.hide()
  443. self.ui.generate_int_iso_button.hide()
  444. self.ui.follow_cb.hide()
  445. self.ui.padding_area_label.show()
  446. else:
  447. self.ui.level.setText(_(
  448. '<span style="color:red;"><b>Advanced</b></span>'
  449. ))
  450. self.ui.padding_area_label.hide()
  451. # add the shapes storage for marking apertures
  452. for ap_code in self.apertures:
  453. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=2)
  454. # set initial state of the aperture table and associated widgets
  455. self.on_aperture_table_visibility_change()
  456. self.build_ui()
  457. def build_ui(self):
  458. FlatCAMObj.build_ui(self)
  459. try:
  460. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  461. self.ui.apertures_table.itemChanged.disconnect()
  462. except TypeError:
  463. pass
  464. self.apertures_row = 0
  465. aper_no = self.apertures_row + 1
  466. sort = []
  467. for k, v in list(self.apertures.items()):
  468. sort.append(int(k))
  469. sorted_apertures = sorted(sort)
  470. # sort = []
  471. # for k, v in list(self.aperture_macros.items()):
  472. # sort.append(k)
  473. # sorted_macros = sorted(sort)
  474. # n = len(sorted_apertures) + len(sorted_macros)
  475. n = len(sorted_apertures)
  476. self.ui.apertures_table.setRowCount(n)
  477. for ap_code in sorted_apertures:
  478. ap_code = str(ap_code)
  479. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  480. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  481. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  482. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  483. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  484. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  485. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  486. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  487. ap_dim_item = QtWidgets.QTableWidgetItem(
  488. '%.4f, %.4f' % (self.apertures[ap_code]['width'] * self.file_units_factor,
  489. self.apertures[ap_code]['height'] * self.file_units_factor
  490. )
  491. )
  492. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  493. elif str(self.apertures[ap_code]['type']) == 'P':
  494. ap_dim_item = QtWidgets.QTableWidgetItem(
  495. '%.4f, %.4f' % (self.apertures[ap_code]['diam'] * self.file_units_factor,
  496. self.apertures[ap_code]['nVertices'] * self.file_units_factor)
  497. )
  498. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  499. else:
  500. ap_dim_item = QtWidgets.QTableWidgetItem('')
  501. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  502. try:
  503. if self.apertures[ap_code]['size'] is not None:
  504. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  505. float(self.apertures[ap_code]['size'] *
  506. self.file_units_factor))
  507. else:
  508. ap_size_item = QtWidgets.QTableWidgetItem('')
  509. except KeyError:
  510. ap_size_item = QtWidgets.QTableWidgetItem('')
  511. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  512. mark_item = FCCheckBox()
  513. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  514. # if self.ui.aperture_table_visibility_cb.isChecked():
  515. # mark_item.setChecked(True)
  516. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  517. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  518. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  519. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  520. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  521. self.apertures_row += 1
  522. # for ap_code in sorted_macros:
  523. # ap_code = str(ap_code)
  524. #
  525. # ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  526. # ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  527. # self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  528. #
  529. # ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  530. #
  531. # ap_type_item = QtWidgets.QTableWidgetItem('AM')
  532. # ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  533. #
  534. # mark_item = FCCheckBox()
  535. # mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  536. # # if self.ui.aperture_table_visibility_cb.isChecked():
  537. # # mark_item.setChecked(True)
  538. #
  539. # self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  540. # self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  541. # self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  542. #
  543. # self.apertures_row += 1
  544. self.ui.apertures_table.selectColumn(0)
  545. self.ui.apertures_table.resizeColumnsToContents()
  546. self.ui.apertures_table.resizeRowsToContents()
  547. vertical_header = self.ui.apertures_table.verticalHeader()
  548. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  549. vertical_header.hide()
  550. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  551. horizontal_header = self.ui.apertures_table.horizontalHeader()
  552. horizontal_header.setMinimumSectionSize(10)
  553. horizontal_header.setDefaultSectionSize(70)
  554. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  555. horizontal_header.resizeSection(0, 27)
  556. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  557. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  558. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  559. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  560. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  561. horizontal_header.resizeSection(5, 17)
  562. self.ui.apertures_table.setColumnWidth(5, 17)
  563. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  564. self.ui.apertures_table.setSortingEnabled(False)
  565. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  566. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  567. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  568. if self.marked_rows:
  569. for row in range(self.ui.apertures_table.rowCount()):
  570. try:
  571. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  572. except IndexError:
  573. pass
  574. self.ui_connect()
  575. def ui_connect(self):
  576. for row in range(self.ui.apertures_table.rowCount()):
  577. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  578. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  579. def ui_disconnect(self):
  580. for row in range(self.ui.apertures_table.rowCount()):
  581. try:
  582. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  583. except TypeError:
  584. pass
  585. try:
  586. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  587. except TypeError:
  588. pass
  589. def on_generatenoncopper_button_click(self, *args):
  590. self.app.report_usage("gerber_on_generatenoncopper_button")
  591. self.read_form()
  592. name = self.options["name"] + "_noncopper"
  593. def geo_init(geo_obj, app_obj):
  594. assert isinstance(geo_obj, FlatCAMGeometry)
  595. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  596. if not self.options["noncopperrounded"]:
  597. bounding_box = bounding_box.envelope
  598. non_copper = bounding_box.difference(self.solid_geometry)
  599. geo_obj.solid_geometry = non_copper
  600. # TODO: Check for None
  601. self.app.new_object("geometry", name, geo_init)
  602. def on_generatebb_button_click(self, *args):
  603. self.app.report_usage("gerber_on_generatebb_button")
  604. self.read_form()
  605. name = self.options["name"] + "_bbox"
  606. def geo_init(geo_obj, app_obj):
  607. assert isinstance(geo_obj, FlatCAMGeometry)
  608. # Bounding box with rounded corners
  609. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  610. if not self.options["bboxrounded"]: # Remove rounded corners
  611. bounding_box = bounding_box.envelope
  612. geo_obj.solid_geometry = bounding_box
  613. self.app.new_object("geometry", name, geo_init)
  614. def on_ext_iso_button_click(self, *args):
  615. if self.ui.follow_cb.get_value() is True:
  616. obj = self.app.collection.get_active()
  617. obj.follow()
  618. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  619. obj.ui.plot_cb.toggle()
  620. else:
  621. self.app.report_usage("gerber_on_iso_button")
  622. self.read_form()
  623. self.isolate(iso_type=0)
  624. def on_int_iso_button_click(self, *args):
  625. if self.ui.follow_cb.get_value() is True:
  626. obj = self.app.collection.get_active()
  627. obj.follow()
  628. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  629. obj.ui.plot_cb.toggle()
  630. else:
  631. self.app.report_usage("gerber_on_iso_button")
  632. self.read_form()
  633. self.isolate(iso_type=1)
  634. def on_iso_button_click(self, *args):
  635. if self.ui.follow_cb.get_value() is True:
  636. obj = self.app.collection.get_active()
  637. obj.follow_geo()
  638. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  639. obj.ui.plot_cb.toggle()
  640. else:
  641. self.app.report_usage("gerber_on_iso_button")
  642. self.read_form()
  643. self.isolate()
  644. def follow_geo(self, outname=None):
  645. """
  646. Creates a geometry object "following" the gerber paths.
  647. :return: None
  648. """
  649. # default_name = self.options["name"] + "_follow"
  650. # follow_name = outname or default_name
  651. if outname is None:
  652. follow_name = self.options["name"] + "_follow"
  653. else:
  654. follow_name = outname
  655. def follow_init(follow_obj, app):
  656. # Propagate options
  657. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  658. follow_obj.solid_geometry = self.follow_geometry
  659. # TODO: Do something if this is None. Offer changing name?
  660. try:
  661. self.app.new_object("geometry", follow_name, follow_init)
  662. except Exception as e:
  663. return "Operation failed: %s" % str(e)
  664. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  665. outname=None, combine=None, milling_type=None, follow=None):
  666. """
  667. Creates an isolation routing geometry object in the project.
  668. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  669. :param dia: Tool diameter
  670. :param passes: Number of tool widths to cut
  671. :param overlap: Overlap between passes in fraction of tool diameter
  672. :param outname: Base name of the output object
  673. :return: None
  674. """
  675. if dia is None:
  676. dia = float(self.options["isotooldia"])
  677. if passes is None:
  678. passes = int(self.options["isopasses"])
  679. if overlap is None:
  680. overlap = float(self.options["isooverlap"])
  681. if combine is None:
  682. combine = self.options["combine_passes"]
  683. else:
  684. combine = bool(combine)
  685. if milling_type is None:
  686. milling_type = self.options["milling_type"]
  687. if iso_type is None:
  688. self.iso_type = 2
  689. else:
  690. self.iso_type = iso_type
  691. base_name = self.options["name"] + "_iso"
  692. base_name = outname or base_name
  693. def generate_envelope(offset, invert, envelope_iso_type=2, follow=None):
  694. # isolation_geometry produces an envelope that is going on the left of the geometry
  695. # (the copper features). To leave the least amount of burrs on the features
  696. # the tool needs to travel on the right side of the features (this is called conventional milling)
  697. # the first pass is the one cutting all of the features, so it needs to be reversed
  698. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  699. # to cut on the right side of the left over copper i.e on the left side of the features.
  700. try:
  701. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  702. except Exception as e:
  703. log.debug(str(e))
  704. return 'fail'
  705. if invert:
  706. try:
  707. if type(geom) is MultiPolygon:
  708. pl = []
  709. for p in geom:
  710. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  711. geom = MultiPolygon(pl)
  712. elif type(geom) is Polygon:
  713. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  714. else:
  715. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  716. except Exception as e:
  717. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  718. return geom
  719. if combine:
  720. if self.iso_type == 0:
  721. iso_name = self.options["name"] + "_ext_iso"
  722. elif self.iso_type == 1:
  723. iso_name = self.options["name"] + "_int_iso"
  724. else:
  725. iso_name = base_name
  726. # TODO: This is ugly. Create way to pass data into init function.
  727. def iso_init(geo_obj, app_obj):
  728. # Propagate options
  729. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  730. geo_obj.solid_geometry = []
  731. for i in range(passes):
  732. iso_offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  733. # if milling type is climb then the move is counter-clockwise around features
  734. if milling_type == 'cl':
  735. # geom = generate_envelope (offset, i == 0)
  736. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type, follow=follow)
  737. else:
  738. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type, follow=follow)
  739. geo_obj.solid_geometry.append(geom)
  740. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  741. # or just looking in the lists (they are one level depth) and if any is not empty
  742. # proceed with object creation, if there are empty and the number of them is the length
  743. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  744. empty_cnt = 0
  745. if not isinstance(geo_obj.solid_geometry, list):
  746. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  747. for g in geo_obj.solid_geometry:
  748. if g:
  749. app_obj.inform.emit(_(
  750. "[success] Isolation geometry created: %s"
  751. ) % geo_obj.options["name"])
  752. break
  753. else:
  754. empty_cnt += 1
  755. if empty_cnt == len(geo_obj.solid_geometry):
  756. raise ValidationError("Empty Geometry", None)
  757. geo_obj.multigeo = False
  758. # TODO: Do something if this is None. Offer changing name?
  759. self.app.new_object("geometry", iso_name, iso_init)
  760. else:
  761. for i in range(passes):
  762. offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  763. if passes > 1:
  764. if self.iso_type == 0:
  765. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  766. elif self.iso_type == 1:
  767. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  768. else:
  769. iso_name = base_name + str(i + 1)
  770. else:
  771. if self.iso_type == 0:
  772. iso_name = self.options["name"] + "_ext_iso"
  773. elif self.iso_type == 1:
  774. iso_name = self.options["name"] + "_int_iso"
  775. else:
  776. iso_name = base_name
  777. # TODO: This is ugly. Create way to pass data into init function.
  778. def iso_init(geo_obj, app_obj):
  779. # Propagate options
  780. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  781. # if milling type is climb then the move is counter-clockwise around features
  782. if milling_type == 'cl':
  783. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  784. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type,
  785. follow=follow)
  786. else:
  787. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type,
  788. follow=follow)
  789. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  790. # or just looking in the lists (they are one level depth) and if any is not empty
  791. # proceed with object creation, if there are empty and the number of them is the length
  792. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  793. empty_cnt = 0
  794. if not isinstance(geo_obj.solid_geometry, list):
  795. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  796. for g in geo_obj.solid_geometry:
  797. if g:
  798. app_obj.inform.emit(_(
  799. "[success] Isolation geometry created: %s"
  800. ) % geo_obj.options["name"])
  801. break
  802. else:
  803. empty_cnt += 1
  804. if empty_cnt == len(geo_obj.solid_geometry):
  805. raise ValidationError("Empty Geometry", None)
  806. geo_obj.multigeo = False
  807. # TODO: Do something if this is None. Offer changing name?
  808. self.app.new_object("geometry", iso_name, iso_init)
  809. def on_plot_cb_click(self, *args):
  810. if self.muted_ui:
  811. return
  812. self.read_form_item('plot')
  813. self.plot()
  814. def on_solid_cb_click(self, *args):
  815. if self.muted_ui:
  816. return
  817. self.read_form_item('solid')
  818. self.plot()
  819. def on_multicolored_cb_click(self, *args):
  820. if self.muted_ui:
  821. return
  822. self.read_form_item('multicolored')
  823. self.plot()
  824. def on_follow_cb_click(self):
  825. if self.muted_ui:
  826. return
  827. self.plot()
  828. def on_aperture_table_visibility_change(self):
  829. if self.ui.aperture_table_visibility_cb.isChecked():
  830. self.ui.apertures_table.setVisible(True)
  831. for ap in self.mark_shapes:
  832. self.mark_shapes[ap].enabled = True
  833. self.ui.mark_all_cb.setVisible(True)
  834. self.ui.mark_all_cb.setChecked(False)
  835. else:
  836. self.ui.apertures_table.setVisible(False)
  837. self.ui.mark_all_cb.setVisible(False)
  838. # on hide disable all mark plots
  839. for row in range(self.ui.apertures_table.rowCount()):
  840. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  841. self.clear_plot_apertures()
  842. for ap in self.mark_shapes:
  843. self.mark_shapes[ap].enabled = False
  844. def convert_units(self, units):
  845. """
  846. Converts the units of the object by scaling dimensions in all geometry
  847. and options.
  848. :param units: Units to which to convert the object: "IN" or "MM".
  849. :type units: str
  850. :return: None
  851. :rtype: None
  852. """
  853. factor = Gerber.convert_units(self, units)
  854. self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  855. self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  856. def plot(self, **kwargs):
  857. """
  858. :param kwargs: color and face_color
  859. :return:
  860. """
  861. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  862. # Does all the required setup and returns False
  863. # if the 'ptint' option is set to False.
  864. if not FlatCAMObj.plot(self):
  865. return
  866. if 'color' in kwargs:
  867. color = kwargs['color']
  868. else:
  869. color = self.app.defaults['global_plot_line']
  870. if 'face_color' in kwargs:
  871. face_color = kwargs['face_color']
  872. else:
  873. face_color = self.app.defaults['global_plot_fill']
  874. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  875. if self.ui.follow_cb.get_value():
  876. geometry = self.follow_geometry
  877. else:
  878. geometry = self.solid_geometry
  879. # Make sure geometry is iterable.
  880. try:
  881. __ = iter(geometry)
  882. except TypeError:
  883. geometry = [geometry]
  884. def random_color():
  885. color = np.random.rand(4)
  886. color[3] = 1
  887. return color
  888. try:
  889. if self.options["solid"]:
  890. for g in geometry:
  891. if type(g) == Polygon or type(g) == LineString:
  892. self.add_shape(shape=g, color=color,
  893. face_color=random_color() if self.options['multicolored']
  894. else face_color, visible=self.options['plot'])
  895. elif type(g) == Point:
  896. pass
  897. else:
  898. try:
  899. for el in g:
  900. self.add_shape(shape=el, color=color,
  901. face_color=random_color() if self.options['multicolored']
  902. else face_color, visible=self.options['plot'])
  903. except TypeError:
  904. self.add_shape(shape=g, color=color,
  905. face_color=random_color() if self.options['multicolored']
  906. else face_color, visible=self.options['plot'])
  907. else:
  908. for g in geometry:
  909. if type(g) == Polygon or type(g) == LineString:
  910. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  911. visible=self.options['plot'])
  912. elif type(g) == Point:
  913. pass
  914. else:
  915. for el in g:
  916. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  917. visible=self.options['plot'])
  918. self.shapes.redraw()
  919. except (ObjectDeleted, AttributeError):
  920. self.shapes.clear(update=True)
  921. # experimental plot() when the solid_geometry is stored in the self.apertures
  922. def plot_aperture(self, **kwargs):
  923. """
  924. :param kwargs: color and face_color
  925. :return:
  926. """
  927. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  928. # Does all the required setup and returns False
  929. # if the 'ptint' option is set to False.
  930. if not FlatCAMObj.plot(self):
  931. return
  932. # for marking apertures, line color and fill color are the same
  933. if 'color' in kwargs:
  934. color = kwargs['color']
  935. else:
  936. color = self.app.defaults['global_plot_fill']
  937. if 'marked_aperture' not in kwargs:
  938. return
  939. else:
  940. aperture_to_plot_mark = kwargs['marked_aperture']
  941. if aperture_to_plot_mark is None:
  942. return
  943. if 'visible' not in kwargs:
  944. visibility = True
  945. else:
  946. visibility = kwargs['visible']
  947. with self.app.proc_container.new(_("Plotting Apertures")) as proc:
  948. self.app.progress.emit(30)
  949. def job_thread(app_obj):
  950. self.app.progress.emit(30)
  951. try:
  952. if aperture_to_plot_mark in self.apertures:
  953. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  954. if 'solid' in elem:
  955. geo = elem['solid']
  956. if type(geo) == Polygon or type(geo) == LineString:
  957. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  958. face_color=color, visible=visibility)
  959. else:
  960. for el in geo:
  961. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  962. face_color=color, visible=visibility)
  963. self.mark_shapes[aperture_to_plot_mark].redraw()
  964. self.app.progress.emit(100)
  965. except (ObjectDeleted, AttributeError):
  966. self.clear_plot_apertures()
  967. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  968. def clear_plot_apertures(self, aperture='all'):
  969. """
  970. :param aperture: string; aperture for which to clear the mark shapes
  971. :return:
  972. """
  973. if aperture == 'all':
  974. for apid in self.apertures:
  975. self.mark_shapes[apid].clear(update=True)
  976. else:
  977. self.mark_shapes[aperture].clear(update=True)
  978. def clear_mark_all(self):
  979. self.ui.mark_all_cb.set_value(False)
  980. self.marked_rows[:] = []
  981. def on_mark_cb_click_table(self):
  982. """
  983. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  984. :return:
  985. """
  986. self.ui_disconnect()
  987. cw = self.sender()
  988. try:
  989. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  990. cw_row = cw_index.row()
  991. except AttributeError:
  992. cw_row = 0
  993. self.marked_rows[:] = []
  994. try:
  995. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  996. except AttributeError:
  997. return
  998. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  999. self.marked_rows.append(True)
  1000. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1001. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'], marked_aperture=aperture, visible=True)
  1002. self.mark_shapes[aperture].redraw()
  1003. else:
  1004. self.marked_rows.append(False)
  1005. self.clear_plot_apertures(aperture=aperture)
  1006. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1007. # if all the row mark's are enabled also enable the Mark All checkbox
  1008. cb_cnt = 0
  1009. total_row = self.ui.apertures_table.rowCount()
  1010. for row in range(total_row):
  1011. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1012. cb_cnt += 1
  1013. else:
  1014. cb_cnt -= 1
  1015. if cb_cnt < total_row:
  1016. self.ui.mark_all_cb.setChecked(False)
  1017. else:
  1018. self.ui.mark_all_cb.setChecked(True)
  1019. self.ui_connect()
  1020. def on_mark_all_click(self, signal):
  1021. self.ui_disconnect()
  1022. mark_all = self.ui.mark_all_cb.isChecked()
  1023. for row in range(self.ui.apertures_table.rowCount()):
  1024. # update the mark_rows list
  1025. if mark_all:
  1026. self.marked_rows.append(True)
  1027. else:
  1028. self.marked_rows[:] = []
  1029. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1030. mark_cb.setChecked(mark_all)
  1031. if mark_all:
  1032. for aperture in self.apertures:
  1033. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1034. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'],
  1035. marked_aperture=aperture, visible=True)
  1036. # HACK: enable/disable the grid for a better look
  1037. self.app.ui.grid_snap_btn.trigger()
  1038. self.app.ui.grid_snap_btn.trigger()
  1039. else:
  1040. self.clear_plot_apertures()
  1041. self.ui_connect()
  1042. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1043. """
  1044. :return: Gerber_code
  1045. """
  1046. def tz_format(x, y, fac):
  1047. x_c = x * fac
  1048. y_c = y * fac
  1049. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1050. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1051. # extract whole part and decimal part
  1052. x_form = x_form.partition('.')
  1053. y_form = y_form.partition('.')
  1054. # left padd the 'whole' part with zeros
  1055. x_whole = x_form[0].rjust(whole, '0')
  1056. y_whole = y_form[0].rjust(whole, '0')
  1057. # restore the coordinate padded in the left with 0 and added the decimal part
  1058. # without the decinal dot
  1059. x_form = x_whole + x_form[2]
  1060. y_form = y_whole + y_form[2]
  1061. return x_form, y_form
  1062. def lz_format(x, y, fac):
  1063. x_c = x * fac
  1064. y_c = y * fac
  1065. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1066. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1067. # pad with rear zeros
  1068. x_form.ljust(length, '0')
  1069. y_form.ljust(length, '0')
  1070. return x_form, y_form
  1071. # Gerber code is stored here
  1072. gerber_code = ''
  1073. # apertures processing
  1074. try:
  1075. length = whole + fract
  1076. if '0' in self.apertures:
  1077. if 'geometry' in self.apertures['0']:
  1078. for geo_elem in self.apertures['0']['geometry']:
  1079. if 'solid' in geo_elem:
  1080. geo = geo_elem['solid']
  1081. if not geo.is_empty:
  1082. gerber_code += 'G36*\n'
  1083. geo_coords = list(geo.exterior.coords)
  1084. # first command is a move with pen-up D02 at the beginning of the geo
  1085. if g_zeros == 'T':
  1086. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1087. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1088. yform=y_formatted)
  1089. else:
  1090. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1091. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1092. yform=y_formatted)
  1093. for coord in geo_coords[1:]:
  1094. if g_zeros == 'T':
  1095. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1096. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1097. yform=y_formatted)
  1098. else:
  1099. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1100. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1101. yform=y_formatted)
  1102. gerber_code += 'D02*\n'
  1103. gerber_code += 'G37*\n'
  1104. clear_list = list(geo.interiors)
  1105. if clear_list:
  1106. gerber_code += '%LPC*%\n'
  1107. for clear_geo in clear_list:
  1108. gerber_code += 'G36*\n'
  1109. geo_coords = list(clear_geo.coords)
  1110. # first command is a move with pen-up D02 at the beginning of the geo
  1111. if g_zeros == 'T':
  1112. x_formatted, y_formatted = tz_format(
  1113. geo_coords[0][0], geo_coords[0][1], factor)
  1114. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1115. yform=y_formatted)
  1116. else:
  1117. x_formatted, y_formatted = lz_format(
  1118. geo_coords[0][0], geo_coords[0][1], factor)
  1119. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1120. yform=y_formatted)
  1121. prev_coord = geo_coords[0]
  1122. for coord in geo_coords[1:]:
  1123. if coord != prev_coord:
  1124. if g_zeros == 'T':
  1125. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1126. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1127. yform=y_formatted)
  1128. else:
  1129. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1130. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1131. yform=y_formatted)
  1132. prev_coord = coord
  1133. gerber_code += 'D02*\n'
  1134. gerber_code += 'G37*\n'
  1135. gerber_code += '%LPD*%\n'
  1136. if 'clear' in geo_elem:
  1137. geo = geo_elem['clear']
  1138. if not geo.is_empty:
  1139. gerber_code += '%LPC*%\n'
  1140. gerber_code += 'G36*\n'
  1141. geo_coords = list(geo.exterior.coords)
  1142. # first command is a move with pen-up D02 at the beginning of the geo
  1143. if g_zeros == 'T':
  1144. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1145. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1146. yform=y_formatted)
  1147. else:
  1148. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1149. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1150. yform=y_formatted)
  1151. prev_coord = geo_coords[0]
  1152. for coord in geo_coords[1:]:
  1153. if coord != prev_coord:
  1154. if g_zeros == 'T':
  1155. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1156. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1157. yform=y_formatted)
  1158. else:
  1159. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1160. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1161. yform=y_formatted)
  1162. prev_coord = coord
  1163. gerber_code += 'D02*\n'
  1164. gerber_code += 'G37*\n'
  1165. gerber_code += '%LPD*%\n'
  1166. for apid in self.apertures:
  1167. if apid == '0':
  1168. continue
  1169. else:
  1170. gerber_code += 'D%s*\n' % str(apid)
  1171. if 'geometry' in self.apertures[apid]:
  1172. for geo_elem in self.apertures[apid]['geometry']:
  1173. if 'follow' in geo_elem:
  1174. geo = geo_elem['follow']
  1175. if not geo.is_empty:
  1176. if isinstance(geo, Point):
  1177. if g_zeros == 'T':
  1178. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1179. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1180. yform=y_formatted)
  1181. else:
  1182. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1183. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1184. yform=y_formatted)
  1185. else:
  1186. geo_coords = list(geo.coords)
  1187. # first command is a move with pen-up D02 at the beginning of the geo
  1188. if g_zeros == 'T':
  1189. x_formatted, y_formatted = tz_format(
  1190. geo_coords[0][0], geo_coords[0][1], factor)
  1191. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1192. yform=y_formatted)
  1193. else:
  1194. x_formatted, y_formatted = lz_format(
  1195. geo_coords[0][0], geo_coords[0][1], factor)
  1196. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1197. yform=y_formatted)
  1198. prev_coord = geo_coords[0]
  1199. for coord in geo_coords[1:]:
  1200. if coord != prev_coord:
  1201. if g_zeros == 'T':
  1202. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1203. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1204. yform=y_formatted)
  1205. else:
  1206. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1207. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1208. yform=y_formatted)
  1209. prev_coord = coord
  1210. # gerber_code += "D02*\n"
  1211. if 'clear' in geo_elem:
  1212. gerber_code += '%LPC*%\n'
  1213. geo = geo_elem['clear']
  1214. if not geo.is_empty:
  1215. if isinstance(geo, Point):
  1216. if g_zeros == 'T':
  1217. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1218. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1219. yform=y_formatted)
  1220. else:
  1221. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1222. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1223. yform=y_formatted)
  1224. else:
  1225. geo_coords = list(geo.coords)
  1226. # first command is a move with pen-up D02 at the beginning of the geo
  1227. if g_zeros == 'T':
  1228. x_formatted, y_formatted = tz_format(
  1229. geo_coords[0][0], geo_coords[0][1], factor)
  1230. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1231. yform=y_formatted)
  1232. else:
  1233. x_formatted, y_formatted = lz_format(
  1234. geo_coords[0][0], geo_coords[0][1], factor)
  1235. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1236. yform=y_formatted)
  1237. prev_coord = geo_coords[0]
  1238. for coord in geo_coords[1:]:
  1239. if coord != prev_coord:
  1240. if g_zeros == 'T':
  1241. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1242. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1243. yform=y_formatted)
  1244. else:
  1245. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1246. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1247. yform=y_formatted)
  1248. prev_coord = coord
  1249. # gerber_code += "D02*\n"
  1250. gerber_code += '%LPD*%\n'
  1251. except Exception as e:
  1252. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> %s" % str(e))
  1253. if not self.apertures:
  1254. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> Gerber Object is empty: no apertures.")
  1255. return 'fail'
  1256. return gerber_code
  1257. def mirror(self, axis, point):
  1258. Gerber.mirror(self, axis=axis, point=point)
  1259. self.replotApertures.emit()
  1260. def offset(self, vect):
  1261. Gerber.offset(self, vect=vect)
  1262. self.replotApertures.emit()
  1263. def rotate(self, angle, point):
  1264. Gerber.rotate(self, angle=angle, point=point)
  1265. self.replotApertures.emit()
  1266. def scale(self, xfactor, yfactor=None, point=None):
  1267. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1268. self.replotApertures.emit()
  1269. def skew(self, angle_x, angle_y, point):
  1270. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1271. self.replotApertures.emit()
  1272. def serialize(self):
  1273. return {
  1274. "options": self.options,
  1275. "kind": self.kind
  1276. }
  1277. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1278. """
  1279. Represents Excellon/Drill code.
  1280. """
  1281. ui_type = ExcellonObjectUI
  1282. optionChanged = QtCore.pyqtSignal(str)
  1283. def __init__(self, name):
  1284. Excellon.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  1285. FlatCAMObj.__init__(self, name)
  1286. self.kind = "excellon"
  1287. self.options.update({
  1288. "plot": True,
  1289. "solid": False,
  1290. "drillz": -0.1,
  1291. "travelz": 0.1,
  1292. "feedrate": 5.0,
  1293. "feedrate_rapid": 5.0,
  1294. "tooldia": 0.1,
  1295. "slot_tooldia": 0.1,
  1296. "toolchange": False,
  1297. "toolchangez": 1.0,
  1298. "toolchangexy": "0.0, 0.0",
  1299. "endz": 2.0,
  1300. "startz": None,
  1301. "spindlespeed": None,
  1302. "dwell": True,
  1303. "dwelltime": 1000,
  1304. "ppname_e": 'defaults',
  1305. "z_pdepth": -0.02,
  1306. "feedrate_probe": 3.0,
  1307. "optimization_type": "R",
  1308. "gcode_type": "drills"
  1309. })
  1310. # TODO: Document this.
  1311. self.tool_cbs = {}
  1312. # dict to hold the tool number as key and tool offset as value
  1313. self.tool_offset = {}
  1314. # variable to store the total amount of drills per job
  1315. self.tot_drill_cnt = 0
  1316. self.tool_row = 0
  1317. # variable to store the total amount of slots per job
  1318. self.tot_slot_cnt = 0
  1319. self.tool_row_slots = 0
  1320. # variable to store the distance travelled
  1321. self.travel_distance = 0.0
  1322. # store the source file here
  1323. self.source_file = ""
  1324. self.multigeo = False
  1325. # Attributes to be included in serialization
  1326. # Always append to it because it carries contents
  1327. # from predecessors.
  1328. self.ser_attrs += ['options', 'kind']
  1329. def merge(self, exc_list, exc_final):
  1330. """
  1331. Merge Excellon objects found in exc_list parameter into exc_final object.
  1332. Options are always copied from source .
  1333. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1334. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1335. tool_name to be used in the final Excellon object, exc_final.
  1336. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1337. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1338. :param exc_final: Destination FlatCAMExcellon object.
  1339. :return: None
  1340. """
  1341. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1342. flag_order = False
  1343. try:
  1344. flattened_list = list(itertools.chain(*exc_list))
  1345. except TypeError:
  1346. flattened_list = exc_list
  1347. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1348. # values will be list of Shapely Points; for drills
  1349. custom_dict_drills = {}
  1350. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1351. # values will be list of Shapely Points; for slots
  1352. custom_dict_slots = {}
  1353. for exc in flattened_list:
  1354. # copy options of the current excellon obj to the final excellon obj
  1355. for option in exc.options:
  1356. if option is not 'name':
  1357. try:
  1358. exc_final.options[option] = exc.options[option]
  1359. except Exception as e:
  1360. exc.app.log.warning("Failed to copy option.", option)
  1361. for drill in exc.drills:
  1362. exc_tool_dia = float('%.4f' % exc.tools[drill['tool']]['C'])
  1363. if exc_tool_dia not in custom_dict_drills:
  1364. custom_dict_drills[exc_tool_dia] = [drill['point']]
  1365. else:
  1366. custom_dict_drills[exc_tool_dia].append(drill['point'])
  1367. for slot in exc.slots:
  1368. exc_tool_dia = float('%.4f' % exc.tools[slot['tool']]['C'])
  1369. if exc_tool_dia not in custom_dict_slots:
  1370. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  1371. else:
  1372. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  1373. # add the zeros and units to the exc_final object
  1374. exc_final.zeros = exc.zeros
  1375. exc_final.units = exc.units
  1376. # ##########################################
  1377. # Here we add data to the exc_final object #
  1378. # ##########################################
  1379. # variable to make tool_name for the tools
  1380. current_tool = 0
  1381. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  1382. # drills
  1383. for tool_dia in custom_dict_drills:
  1384. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  1385. current_tool += 1
  1386. tool_name = str(current_tool)
  1387. spec = {"C": float(tool_dia)}
  1388. exc_final.tools[tool_name] = spec
  1389. # rebuild the drills list of dict's that belong to the exc_final object
  1390. for point in custom_dict_drills[tool_dia]:
  1391. exc_final.drills.append(
  1392. {
  1393. "point": point,
  1394. "tool": str(current_tool)
  1395. }
  1396. )
  1397. # The tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  1398. # of two Shapely Points in case of slots
  1399. for tool_dia in custom_dict_slots:
  1400. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  1401. # but only if there are no drills
  1402. if not exc_final.tools:
  1403. current_tool += 1
  1404. tool_name = str(current_tool)
  1405. spec = {"C": float(tool_dia)}
  1406. exc_final.tools[tool_name] = spec
  1407. else:
  1408. dia_list = []
  1409. for v in exc_final.tools.values():
  1410. dia_list.append(float(v["C"]))
  1411. if tool_dia not in dia_list:
  1412. flag_order = True
  1413. current_tool = len(dia_list) + 1
  1414. tool_name = str(current_tool)
  1415. spec = {"C": float(tool_dia)}
  1416. exc_final.tools[tool_name] = spec
  1417. else:
  1418. for k, v in exc_final.tools.items():
  1419. if v["C"] == tool_dia:
  1420. current_tool = int(k)
  1421. break
  1422. # rebuild the slots list of dict's that belong to the exc_final object
  1423. for point in custom_dict_slots[tool_dia]:
  1424. exc_final.slots.append(
  1425. {
  1426. "start": point[0],
  1427. "stop": point[1],
  1428. "tool": str(current_tool)
  1429. }
  1430. )
  1431. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  1432. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  1433. current_tool = 0
  1434. if flag_order is True:
  1435. dia_list = []
  1436. temp_drills = []
  1437. temp_slots = []
  1438. temp_tools = {}
  1439. for v in exc_final.tools.values():
  1440. dia_list.append(float(v["C"]))
  1441. dia_list.sort()
  1442. for ordered_dia in dia_list:
  1443. current_tool += 1
  1444. tool_name_temp = str(current_tool)
  1445. spec_temp = {"C": float(ordered_dia)}
  1446. temp_tools[tool_name_temp] = spec_temp
  1447. for drill in exc_final.drills:
  1448. exc_tool_dia = float('%.4f' % exc_final.tools[drill['tool']]['C'])
  1449. if exc_tool_dia == ordered_dia:
  1450. temp_drills.append(
  1451. {
  1452. "point": drill["point"],
  1453. "tool": str(current_tool)
  1454. }
  1455. )
  1456. for slot in exc_final.slots:
  1457. slot_tool_dia = float('%.4f' % exc_final.tools[slot['tool']]['C'])
  1458. if slot_tool_dia == ordered_dia:
  1459. temp_slots.append(
  1460. {
  1461. "start": slot["start"],
  1462. "stop": slot["stop"],
  1463. "tool": str(current_tool)
  1464. }
  1465. )
  1466. # delete the exc_final tools, drills and slots
  1467. exc_final.tools = dict()
  1468. exc_final.drills[:] = []
  1469. exc_final.slots[:] = []
  1470. # update the exc_final tools, drills and slots with the ordered values
  1471. exc_final.tools = temp_tools
  1472. exc_final.drills[:] = temp_drills
  1473. exc_final.slots[:] = temp_slots
  1474. # create the geometry for the exc_final object
  1475. exc_final.create_geometry()
  1476. def build_ui(self):
  1477. FlatCAMObj.build_ui(self)
  1478. try:
  1479. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1480. self.ui.tools_table.itemChanged.disconnect()
  1481. except TypeError:
  1482. pass
  1483. n = len(self.tools)
  1484. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1485. self.ui.tools_table.setRowCount(n + 2)
  1486. self.tot_drill_cnt = 0
  1487. self.tot_slot_cnt = 0
  1488. self.tool_row = 0
  1489. sort = []
  1490. for k, v in list(self.tools.items()):
  1491. sort.append((k, v.get('C')))
  1492. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1493. tools = [i[0] for i in sorted_tools]
  1494. for tool_no in tools:
  1495. drill_cnt = 0 # variable to store the nr of drills per tool
  1496. slot_cnt = 0 # variable to store the nr of slots per tool
  1497. # Find no of drills for the current tool
  1498. for drill in self.drills:
  1499. if drill['tool'] == tool_no:
  1500. drill_cnt += 1
  1501. self.tot_drill_cnt += drill_cnt
  1502. # Find no of slots for the current tool
  1503. for slot in self.slots:
  1504. if slot['tool'] == tool_no:
  1505. slot_cnt += 1
  1506. self.tot_slot_cnt += slot_cnt
  1507. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  1508. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1509. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  1510. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1511. # There are no drill bits in MM with more than 3 decimals diameter
  1512. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1513. if self.units == 'MM':
  1514. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  1515. else:
  1516. dia = QtWidgets.QTableWidgetItem('%.4f' % (self.tools[tool_no]['C']))
  1517. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1518. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1519. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1520. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1521. if slot_cnt > 0:
  1522. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1523. else:
  1524. slot_count = QtWidgets.QTableWidgetItem('')
  1525. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1526. try:
  1527. if self.units == 'MM':
  1528. t_offset = self.tool_offset[float('%.2f' % float(self.tools[tool_no]['C']))]
  1529. else:
  1530. t_offset = self.tool_offset[float('%.4f' % float(self.tools[tool_no]['C']))]
  1531. except KeyError:
  1532. t_offset = self.app.defaults['excellon_offset']
  1533. tool_offset_item = QtWidgets.QTableWidgetItem('%s' % str(t_offset))
  1534. plot_item = FCCheckBox()
  1535. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1536. if self.ui.plot_cb.isChecked():
  1537. plot_item.setChecked(True)
  1538. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  1539. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1540. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1541. self.ui.tools_table.setItem(self.tool_row, 4, tool_offset_item) # Tool offset
  1542. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  1543. self.tool_row += 1
  1544. # add a last row with the Total number of drills
  1545. empty = QtWidgets.QTableWidgetItem('')
  1546. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1547. empty_1 = QtWidgets.QTableWidgetItem('')
  1548. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1549. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1550. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1551. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1552. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1553. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  1554. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  1555. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1556. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  1557. font = QtGui.QFont()
  1558. font.setBold(True)
  1559. font.setWeight(75)
  1560. for k in [1, 2]:
  1561. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1562. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  1563. self.tool_row += 1
  1564. # add a last row with the Total number of slots
  1565. empty_2 = QtWidgets.QTableWidgetItem('')
  1566. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1567. empty_3 = QtWidgets.QTableWidgetItem('')
  1568. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1569. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1570. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1571. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1572. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1573. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  1574. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  1575. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  1576. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1577. for kl in [1, 2, 3]:
  1578. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  1579. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1580. # sort the tool diameter column
  1581. # self.ui.tools_table.sortItems(1)
  1582. # all the tools are selected by default
  1583. self.ui.tools_table.selectColumn(0)
  1584. #
  1585. self.ui.tools_table.resizeColumnsToContents()
  1586. self.ui.tools_table.resizeRowsToContents()
  1587. vertical_header = self.ui.tools_table.verticalHeader()
  1588. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1589. vertical_header.hide()
  1590. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1591. horizontal_header = self.ui.tools_table.horizontalHeader()
  1592. horizontal_header.setMinimumSectionSize(10)
  1593. horizontal_header.setDefaultSectionSize(70)
  1594. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1595. horizontal_header.resizeSection(0, 20)
  1596. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1597. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1598. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1599. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  1600. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  1601. horizontal_header.resizeSection(5, 17)
  1602. self.ui.tools_table.setColumnWidth(5, 17)
  1603. # horizontal_header.setStretchLastSection(True)
  1604. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1605. # horizontal_header.setStretchLastSection(True)
  1606. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1607. self.ui.tools_table.setSortingEnabled(False)
  1608. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  1609. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  1610. if not self.drills:
  1611. self.ui.tdlabel.hide()
  1612. self.ui.tooldia_entry.hide()
  1613. self.ui.generate_milling_button.hide()
  1614. else:
  1615. self.ui.tdlabel.show()
  1616. self.ui.tooldia_entry.show()
  1617. self.ui.generate_milling_button.show()
  1618. if not self.slots:
  1619. self.ui.stdlabel.hide()
  1620. self.ui.slot_tooldia_entry.hide()
  1621. self.ui.generate_milling_slots_button.hide()
  1622. else:
  1623. self.ui.stdlabel.show()
  1624. self.ui.slot_tooldia_entry.show()
  1625. self.ui.generate_milling_slots_button.show()
  1626. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1627. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1628. self.ui_connect()
  1629. def set_ui(self, ui):
  1630. """
  1631. Configures the user interface for this object.
  1632. Connects options to form fields.
  1633. :param ui: User interface object.
  1634. :type ui: ExcellonObjectUI
  1635. :return: None
  1636. """
  1637. FlatCAMObj.set_ui(self, ui)
  1638. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1639. self.form_fields.update({
  1640. "plot": self.ui.plot_cb,
  1641. "solid": self.ui.solid_cb,
  1642. "drillz": self.ui.cutz_entry,
  1643. "travelz": self.ui.travelz_entry,
  1644. "feedrate": self.ui.feedrate_entry,
  1645. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1646. "tooldia": self.ui.tooldia_entry,
  1647. "slot_tooldia": self.ui.slot_tooldia_entry,
  1648. "toolchange": self.ui.toolchange_cb,
  1649. "toolchangez": self.ui.toolchangez_entry,
  1650. "spindlespeed": self.ui.spindlespeed_entry,
  1651. "dwell": self.ui.dwell_cb,
  1652. "dwelltime": self.ui.dwelltime_entry,
  1653. "startz": self.ui.estartz_entry,
  1654. "endz": self.ui.eendz_entry,
  1655. "ppname_e": self.ui.pp_excellon_name_cb,
  1656. "z_pdepth": self.ui.pdepth_entry,
  1657. "feedrate_probe": self.ui.feedrate_probe_entry,
  1658. "gcode_type": self.ui.excellon_gcode_type_radio
  1659. })
  1660. for name in list(self.app.postprocessors.keys()):
  1661. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1662. if name == 'hpgl':
  1663. continue
  1664. self.ui.pp_excellon_name_cb.addItem(name)
  1665. # Fill form fields
  1666. self.to_form()
  1667. # initialize the dict that holds the tools offset
  1668. t_default_offset = self.app.defaults["excellon_offset"]
  1669. if not self.tool_offset:
  1670. for value in self.tools.values():
  1671. if self.units == 'MM':
  1672. dia = float('%.2f' % float(value['C']))
  1673. else:
  1674. dia = float('%.4f' % float(value['C']))
  1675. self.tool_offset[dia] = t_default_offset
  1676. # Show/Hide Advanced Options
  1677. if self.app.defaults["global_app_level"] == 'b':
  1678. self.ui.level.setText(_(
  1679. '<span style="color:green;"><b>Basic</b></span>'
  1680. ))
  1681. self.ui.tools_table.setColumnHidden(4, True)
  1682. self.ui.estartz_label.hide()
  1683. self.ui.estartz_entry.hide()
  1684. self.ui.eendz_label.hide()
  1685. self.ui.eendz_entry.hide()
  1686. self.ui.feedrate_rapid_label.hide()
  1687. self.ui.feedrate_rapid_entry.hide()
  1688. self.ui.pdepth_label.hide()
  1689. self.ui.pdepth_entry.hide()
  1690. self.ui.feedrate_probe_label.hide()
  1691. self.ui.feedrate_probe_entry.hide()
  1692. else:
  1693. self.ui.level.setText(_(
  1694. '<span style="color:red;"><b>Advanced</b></span>'
  1695. ))
  1696. assert isinstance(self.ui, ExcellonObjectUI), \
  1697. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1698. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1699. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1700. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1701. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1702. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1703. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  1704. def ui_connect(self):
  1705. for row in range(self.ui.tools_table.rowCount() - 2):
  1706. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  1707. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1708. def ui_disconnect(self):
  1709. for row in range(self.ui.tools_table.rowCount()):
  1710. try:
  1711. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  1712. except TypeError:
  1713. pass
  1714. try:
  1715. self.ui.plot_cb.stateChanged.disconnect()
  1716. except TypeError:
  1717. pass
  1718. def on_tool_offset_edit(self):
  1719. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1720. self.ui.tools_table.itemChanged.disconnect()
  1721. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1722. self.is_modified = True
  1723. row_of_item_changed = self.ui.tools_table.currentRow()
  1724. if self.units == 'MM':
  1725. dia = float('%.2f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1726. else:
  1727. dia = float('%.4f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1728. current_table_offset_edited = None
  1729. if self.ui.tools_table.currentItem() is not None:
  1730. try:
  1731. current_table_offset_edited = float(self.ui.tools_table.currentItem().text())
  1732. except ValueError:
  1733. # try to convert comma to decimal point. if it's still not working error message and return
  1734. try:
  1735. current_table_offset_edited = float(self.ui.tools_table.currentItem().text().replace(',', '.'))
  1736. self.ui.tools_table.currentItem().setText(
  1737. self.ui.tools_table.currentItem().text().replace(',', '.'))
  1738. except ValueError:
  1739. self.app.inform.emit(_(
  1740. "[ERROR_NOTCL] Wrong value format entered, use a number."
  1741. ))
  1742. self.ui.tools_table.currentItem().setText(str(self.tool_offset[dia]))
  1743. return
  1744. self.tool_offset[dia] = current_table_offset_edited
  1745. # we reactivate the signals after the after the tool editing
  1746. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1747. def get_selected_tools_list(self):
  1748. """
  1749. Returns the keys to the self.tools dictionary corresponding
  1750. to the selections on the tool list in the GUI.
  1751. :return: List of tools.
  1752. :rtype: list
  1753. """
  1754. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1755. def get_selected_tools_table_items(self):
  1756. """
  1757. Returns a list of lists, each list in the list is made out of row elements
  1758. :return: List of table_tools items.
  1759. :rtype: list
  1760. """
  1761. table_tools_items = []
  1762. for x in self.ui.tools_table.selectedItems():
  1763. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  1764. # which does not have text
  1765. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1766. for column in range(0, self.ui.tools_table.columnCount() - 1)])
  1767. for item in table_tools_items:
  1768. item[0] = str(item[0])
  1769. return table_tools_items
  1770. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1):
  1771. """
  1772. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1773. :return: has_slots and Excellon_code
  1774. """
  1775. excellon_code = ''
  1776. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1777. has_slots = 0
  1778. # drills processing
  1779. try:
  1780. if self.drills:
  1781. length = whole + fract
  1782. for tool in self.tools:
  1783. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  1784. for drill in self.drills:
  1785. if form == 'dec' and tool == drill['tool']:
  1786. drill_x = drill['point'].x * factor
  1787. drill_y = drill['point'].y * factor
  1788. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  1789. elif e_zeros == 'LZ' and tool == drill['tool']:
  1790. drill_x = drill['point'].x * factor
  1791. drill_y = drill['point'].y * factor
  1792. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  1793. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  1794. # extract whole part and decimal part
  1795. exc_x_formatted = exc_x_formatted.partition('.')
  1796. exc_y_formatted = exc_y_formatted.partition('.')
  1797. # left padd the 'whole' part with zeros
  1798. x_whole = exc_x_formatted[0].rjust(whole, '0')
  1799. y_whole = exc_y_formatted[0].rjust(whole, '0')
  1800. # restore the coordinate padded in the left with 0 and added the decimal part
  1801. # without the decinal dot
  1802. exc_x_formatted = x_whole + exc_x_formatted[2]
  1803. exc_y_formatted = y_whole + exc_y_formatted[2]
  1804. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1805. yform=exc_y_formatted)
  1806. elif tool == drill['tool']:
  1807. drill_x = drill['point'].x * factor
  1808. drill_y = drill['point'].y * factor
  1809. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  1810. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  1811. # pad with rear zeros
  1812. exc_x_formatted.ljust(length, '0')
  1813. exc_y_formatted.ljust(length, '0')
  1814. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1815. yform=exc_y_formatted)
  1816. except Exception as e:
  1817. log.debug(str(e))
  1818. # slots processing
  1819. try:
  1820. if self.slots:
  1821. has_slots = 1
  1822. for tool in self.tools:
  1823. if int(tool) < 10:
  1824. excellon_code += 'T0' + str(tool) + '\n'
  1825. else:
  1826. excellon_code += 'T' + str(tool) + '\n'
  1827. for slot in self.slots:
  1828. if form == 'dec' and tool == slot['tool']:
  1829. start_slot_x = slot['start'].x * factor
  1830. start_slot_y = slot['start'].y * factor
  1831. stop_slot_x = slot['stop'].x * factor
  1832. stop_slot_y = slot['stop'].y * factor
  1833. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  1834. start_slot_y,
  1835. dec=fract)
  1836. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  1837. stop_slot_y,
  1838. dec=fract)
  1839. elif e_zeros == 'LZ' and tool == slot['tool']:
  1840. start_slot_x = slot['start'].x * factor
  1841. start_slot_y = slot['start'].y * factor
  1842. stop_slot_x = slot['stop'].x * factor
  1843. stop_slot_y = slot['stop'].y * factor
  1844. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1845. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1846. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1847. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1848. # extract whole part and decimal part
  1849. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  1850. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  1851. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  1852. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  1853. # left padd the 'whole' part with zeros
  1854. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  1855. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  1856. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  1857. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  1858. # restore the coordinate padded in the left with 0 and added the decimal part
  1859. # without the decinal dot
  1860. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  1861. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  1862. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  1863. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  1864. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1865. ystart=start_slot_y_formatted)
  1866. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1867. ystop=stop_slot_y_formatted)
  1868. elif tool == slot['tool']:
  1869. start_slot_x = slot['start'].x * factor
  1870. start_slot_y = slot['start'].y * factor
  1871. stop_slot_x = slot['stop'].x * factor
  1872. stop_slot_y = slot['stop'].y * factor
  1873. length = whole + fract
  1874. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1875. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1876. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1877. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1878. # pad with rear zeros
  1879. start_slot_x_formatted.ljust(length, '0')
  1880. start_slot_y_formatted.ljust(length, '0')
  1881. stop_slot_x_formatted.ljust(length, '0')
  1882. stop_slot_y_formatted.ljust(length, '0')
  1883. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1884. ystart=start_slot_y_formatted)
  1885. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1886. ystop=stop_slot_y_formatted)
  1887. except Exception as e:
  1888. log.debug(str(e))
  1889. if not self.drills and not self.slots:
  1890. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  1891. return 'fail'
  1892. return has_slots, excellon_code
  1893. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1894. """
  1895. Note: This method is a good template for generic operations as
  1896. it takes it's options from parameters or otherwise from the
  1897. object's options and returns a (success, msg) tuple as feedback
  1898. for shell operations.
  1899. :return: Success/failure condition tuple (bool, str).
  1900. :rtype: tuple
  1901. """
  1902. # Get the tools from the list. These are keys
  1903. # to self.tools
  1904. if tools is None:
  1905. tools = self.get_selected_tools_list()
  1906. if outname is None:
  1907. outname = self.options["name"] + "_mill"
  1908. if tooldia is None:
  1909. tooldia = float(self.options["tooldia"])
  1910. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1911. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1912. sort = []
  1913. for k, v in self.tools.items():
  1914. sort.append((k, v.get('C')))
  1915. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1916. if tools == "all":
  1917. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1918. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1919. if len(tools) == 0:
  1920. self.app.inform.emit(_(
  1921. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1922. ))
  1923. return False, "Error: No tools."
  1924. for tool in tools:
  1925. if tooldia > self.tools[tool]["C"]:
  1926. self.app.inform.emit(_(
  1927. "[ERROR_NOTCL] Milling tool for DRILLS is larger than hole size. Cancelled."
  1928. ))
  1929. return False, "Error: Milling tool is larger than hole."
  1930. def geo_init(geo_obj, app_obj):
  1931. assert isinstance(geo_obj, FlatCAMGeometry), \
  1932. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1933. app_obj.progress.emit(20)
  1934. # ## Add properties to the object
  1935. # get the tool_table items in a list of row items
  1936. tool_table_items = self.get_selected_tools_table_items()
  1937. # insert an information only element in the front
  1938. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1939. geo_obj.options['Tools_in_use'] = tool_table_items
  1940. geo_obj.options['type'] = 'Excellon Geometry'
  1941. geo_obj.options["cnctooldia"] = str(tooldia)
  1942. geo_obj.solid_geometry = []
  1943. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1944. # for FlatCAM is 6 decimals,
  1945. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1946. for hole in self.drills:
  1947. if hole['tool'] in tools:
  1948. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1949. if buffer_value == 0:
  1950. geo_obj.solid_geometry.append(
  1951. Point(hole['point']).buffer(0.0000001).exterior)
  1952. else:
  1953. geo_obj.solid_geometry.append(
  1954. Point(hole['point']).buffer(buffer_value).exterior)
  1955. if use_thread:
  1956. def geo_thread(app_obj):
  1957. app_obj.new_object("geometry", outname, geo_init)
  1958. app_obj.progress.emit(100)
  1959. # Create a promise with the new name
  1960. self.app.collection.promise(outname)
  1961. # Send to worker
  1962. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1963. else:
  1964. self.app.new_object("geometry", outname, geo_init)
  1965. return True, ""
  1966. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1967. """
  1968. Note: This method is a good template for generic operations as
  1969. it takes it's options from parameters or otherwise from the
  1970. object's options and returns a (success, msg) tuple as feedback
  1971. for shell operations.
  1972. :return: Success/failure condition tuple (bool, str).
  1973. :rtype: tuple
  1974. """
  1975. # Get the tools from the list. These are keys
  1976. # to self.tools
  1977. if tools is None:
  1978. tools = self.get_selected_tools_list()
  1979. if outname is None:
  1980. outname = self.options["name"] + "_mill"
  1981. if tooldia is None:
  1982. tooldia = float(self.options["slot_tooldia"])
  1983. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1984. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1985. sort = []
  1986. for k, v in self.tools.items():
  1987. sort.append((k, v.get('C')))
  1988. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1989. if tools == "all":
  1990. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1991. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1992. if len(tools) == 0:
  1993. self.app.inform.emit(_(
  1994. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1995. ))
  1996. return False, "Error: No tools."
  1997. for tool in tools:
  1998. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1999. adj_toolstable_tooldia = float('%.4f' % float(tooldia))
  2000. adj_file_tooldia = float('%.4f' % float(self.tools[tool]["C"]))
  2001. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  2002. self.app.inform.emit(_(
  2003. "[ERROR_NOTCL] Milling tool for SLOTS is larger than hole size. Cancelled."
  2004. ))
  2005. return False, "Error: Milling tool is larger than hole."
  2006. def geo_init(geo_obj, app_obj):
  2007. assert isinstance(geo_obj, FlatCAMGeometry), \
  2008. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2009. app_obj.progress.emit(20)
  2010. # ## Add properties to the object
  2011. # get the tool_table items in a list of row items
  2012. tool_table_items = self.get_selected_tools_table_items()
  2013. # insert an information only element in the front
  2014. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2015. geo_obj.options['Tools_in_use'] = tool_table_items
  2016. geo_obj.options['type'] = 'Excellon Geometry'
  2017. geo_obj.options["cnctooldia"] = str(tooldia)
  2018. geo_obj.solid_geometry = []
  2019. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2020. # for FlatCAM is 6 decimals,
  2021. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2022. for slot in self.slots:
  2023. if slot['tool'] in tools:
  2024. toolstable_tool = float('%.4f' % float(tooldia))
  2025. file_tool = float('%.4f' % float(self.tools[tool]["C"]))
  2026. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2027. # for the file_tool (tooldia actually)
  2028. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  2029. if buffer_value == 0:
  2030. start = slot['start']
  2031. stop = slot['stop']
  2032. lines_string = LineString([start, stop])
  2033. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  2034. geo_obj.solid_geometry.append(poly)
  2035. else:
  2036. start = slot['start']
  2037. stop = slot['stop']
  2038. lines_string = LineString([start, stop])
  2039. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  2040. geo_obj.solid_geometry.append(poly)
  2041. if use_thread:
  2042. def geo_thread(app_obj):
  2043. app_obj.new_object("geometry", outname + '_slot', geo_init)
  2044. app_obj.progress.emit(100)
  2045. # Create a promise with the new name
  2046. self.app.collection.promise(outname)
  2047. # Send to worker
  2048. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2049. else:
  2050. self.app.new_object("geometry", outname + '_slot', geo_init)
  2051. return True, ""
  2052. def on_generate_milling_button_click(self, *args):
  2053. self.app.report_usage("excellon_on_create_milling_drills button")
  2054. self.read_form()
  2055. self.generate_milling_drills(use_thread=False)
  2056. def on_generate_milling_slots_button_click(self, *args):
  2057. self.app.report_usage("excellon_on_create_milling_slots_button")
  2058. self.read_form()
  2059. self.generate_milling_slots(use_thread=False)
  2060. def on_pp_changed(self):
  2061. current_pp = self.ui.pp_excellon_name_cb.get_value()
  2062. if "toolchange_probe" in current_pp.lower():
  2063. self.ui.pdepth_entry.setVisible(True)
  2064. self.ui.pdepth_label.show()
  2065. self.ui.feedrate_probe_entry.setVisible(True)
  2066. self.ui.feedrate_probe_label.show()
  2067. else:
  2068. self.ui.pdepth_entry.setVisible(False)
  2069. self.ui.pdepth_label.hide()
  2070. self.ui.feedrate_probe_entry.setVisible(False)
  2071. self.ui.feedrate_probe_label.hide()
  2072. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  2073. self.ui.feedrate_rapid_label.show()
  2074. self.ui.feedrate_rapid_entry.show()
  2075. else:
  2076. self.ui.feedrate_rapid_label.hide()
  2077. self.ui.feedrate_rapid_entry.hide()
  2078. def on_create_cncjob_button_click(self, *args):
  2079. self.app.report_usage("excellon_on_create_cncjob_button")
  2080. self.read_form()
  2081. # Get the tools from the list
  2082. tools = self.get_selected_tools_list()
  2083. if len(tools) == 0:
  2084. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  2085. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  2086. # in this case regardless of the selection status of that tool, use it.
  2087. if self.ui.tools_table.rowCount() == 3:
  2088. tools.append(self.ui.tools_table.item(0, 0).text())
  2089. else:
  2090. self.app.inform.emit(_(
  2091. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  2092. ))
  2093. return
  2094. xmin = self.options['xmin']
  2095. ymin = self.options['ymin']
  2096. xmax = self.options['xmax']
  2097. ymax = self.options['ymax']
  2098. job_name = self.options["name"] + "_cnc"
  2099. pp_excellon_name = self.options["ppname_e"]
  2100. # Object initialization function for app.new_object()
  2101. def job_init(job_obj, app_obj):
  2102. assert isinstance(job_obj, FlatCAMCNCjob), \
  2103. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2104. # get the tool_table items in a list of row items
  2105. tool_table_items = self.get_selected_tools_table_items()
  2106. # insert an information only element in the front
  2107. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2108. # ## Add properties to the object
  2109. job_obj.origin_kind = 'excellon'
  2110. job_obj.options['Tools_in_use'] = tool_table_items
  2111. job_obj.options['type'] = 'Excellon'
  2112. job_obj.options['ppname_e'] = pp_excellon_name
  2113. app_obj.progress.emit(20)
  2114. job_obj.z_cut = float(self.options["drillz"])
  2115. job_obj.tool_offset = self.tool_offset
  2116. job_obj.z_move = float(self.options["travelz"])
  2117. job_obj.feedrate = float(self.options["feedrate"])
  2118. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  2119. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] else None
  2120. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  2121. job_obj.dwell = self.options["dwell"]
  2122. job_obj.dwelltime = float(self.options["dwelltime"])
  2123. job_obj.pp_excellon_name = pp_excellon_name
  2124. job_obj.toolchange_xy_type = "excellon"
  2125. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  2126. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  2127. job_obj.options['xmin'] = xmin
  2128. job_obj.options['ymin'] = ymin
  2129. job_obj.options['xmax'] = xmax
  2130. job_obj.options['ymax'] = ymax
  2131. try:
  2132. job_obj.z_pdepth = float(self.options["z_pdepth"])
  2133. except ValueError:
  2134. # try to convert comma to decimal point. if it's still not working error message and return
  2135. try:
  2136. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  2137. except ValueError:
  2138. self.app.inform.emit(
  2139. _(
  2140. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  2141. ))
  2142. try:
  2143. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  2144. except ValueError:
  2145. # try to convert comma to decimal point. if it's still not working error message and return
  2146. try:
  2147. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  2148. except ValueError:
  2149. self.app.inform.emit(
  2150. _(
  2151. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  2152. 'or self.options["feedrate_probe"]'
  2153. )
  2154. )
  2155. # There could be more than one drill size...
  2156. # job_obj.tooldia = # TODO: duplicate variable!
  2157. # job_obj.options["tooldia"] =
  2158. tools_csv = ','.join(tools)
  2159. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv,
  2160. drillz=float(self.options['drillz']),
  2161. toolchange=self.options["toolchange"],
  2162. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  2163. toolchangez=float(self.options["toolchangez"]),
  2164. startz=float(self.options["startz"]) if
  2165. self.options["startz"] else None,
  2166. endz=float(self.options["endz"]),
  2167. excellon_optimization_type=self.app.defaults[
  2168. "excellon_optimization_type"])
  2169. if ret_val == 'fail':
  2170. return 'fail'
  2171. app_obj.progress.emit(50)
  2172. job_obj.gcode_parse()
  2173. app_obj.progress.emit(60)
  2174. job_obj.create_geometry()
  2175. app_obj.progress.emit(80)
  2176. # To be run in separate thread
  2177. def job_thread(app_obj):
  2178. with self.app.proc_container.new(_("Generating CNC Code")):
  2179. app_obj.new_object("cncjob", job_name, job_init)
  2180. app_obj.progress.emit(100)
  2181. # Create promise for the new name.
  2182. self.app.collection.promise(job_name)
  2183. # Send to worker
  2184. # self.app.worker.add_task(job_thread, [self.app])
  2185. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2186. def convert_units(self, units):
  2187. factor = Excellon.convert_units(self, units)
  2188. self.options['drillz'] = float(self.options['drillz']) * factor
  2189. self.options['travelz'] = float(self.options['travelz']) * factor
  2190. self.options['feedrate'] = float(self.options['feedrate']) * factor
  2191. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  2192. self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  2193. if self.app.defaults["excellon_toolchangexy"] == '':
  2194. self.options['toolchangexy'] = "0.0, 0.0"
  2195. else:
  2196. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  2197. if len(coords_xy) < 2:
  2198. self.app.inform.emit(_(
  2199. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  2200. "in the format (x, y) \nbut now there is only one value, not two. "
  2201. ))
  2202. return 'fail'
  2203. coords_xy[0] *= factor
  2204. coords_xy[1] *= factor
  2205. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2206. if self.options['startz'] is not None:
  2207. self.options['startz'] = float(self.options['startz']) * factor
  2208. self.options['endz'] = float(self.options['endz']) * factor
  2209. def on_solid_cb_click(self, *args):
  2210. if self.muted_ui:
  2211. return
  2212. self.read_form_item('solid')
  2213. self.plot()
  2214. def on_plot_cb_click(self, *args):
  2215. if self.muted_ui:
  2216. return
  2217. self.plot()
  2218. self.read_form_item('plot')
  2219. self.ui_disconnect()
  2220. cb_flag = self.ui.plot_cb.isChecked()
  2221. for row in range(self.ui.tools_table.rowCount() - 2):
  2222. table_cb = self.ui.tools_table.cellWidget(row, 5)
  2223. if cb_flag:
  2224. table_cb.setChecked(True)
  2225. else:
  2226. table_cb.setChecked(False)
  2227. self.ui_connect()
  2228. def on_plot_cb_click_table(self):
  2229. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2230. self.ui_disconnect()
  2231. # cw = self.sender()
  2232. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  2233. # cw_row = cw_index.row()
  2234. check_row = 0
  2235. self.shapes.clear(update=True)
  2236. for tool_key in self.tools:
  2237. solid_geometry = self.tools[tool_key]['solid_geometry']
  2238. # find the geo_tool_table row associated with the tool_key
  2239. for row in range(self.ui.tools_table.rowCount()):
  2240. tool_item = int(self.ui.tools_table.item(row, 0).text())
  2241. if tool_item == int(tool_key):
  2242. check_row = row
  2243. break
  2244. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  2245. self.options['plot'] = True
  2246. # self.plot_element(element=solid_geometry, visible=True)
  2247. # Plot excellon (All polygons?)
  2248. if self.options["solid"]:
  2249. for geo in solid_geometry:
  2250. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2251. visible=self.options['plot'],
  2252. layer=2)
  2253. else:
  2254. for geo in solid_geometry:
  2255. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2256. for ints in geo.interiors:
  2257. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2258. self.shapes.redraw()
  2259. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2260. # if all the row plot's are enabled also enable the general plot checkbox
  2261. cb_cnt = 0
  2262. total_row = self.ui.tools_table.rowCount()
  2263. for row in range(total_row - 2):
  2264. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  2265. cb_cnt += 1
  2266. else:
  2267. cb_cnt -= 1
  2268. if cb_cnt < total_row - 2:
  2269. self.ui.plot_cb.setChecked(False)
  2270. else:
  2271. self.ui.plot_cb.setChecked(True)
  2272. self.ui_connect()
  2273. # def plot_element(self, element, color='red', visible=None, layer=None):
  2274. #
  2275. # visible = visible if visible else self.options['plot']
  2276. #
  2277. # try:
  2278. # for sub_el in element:
  2279. # self.plot_element(sub_el)
  2280. #
  2281. # except TypeError: # Element is not iterable...
  2282. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2283. def plot(self, kind=None):
  2284. # Does all the required setup and returns False
  2285. # if the 'ptint' option is set to False.
  2286. if not FlatCAMObj.plot(self):
  2287. return
  2288. # try:
  2289. # # Plot Excellon (All polygons?)
  2290. # if self.options["solid"]:
  2291. # for tool in self.tools:
  2292. # for geo in self.tools[tool]['solid_geometry']:
  2293. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2294. # visible=self.options['plot'],
  2295. # layer=2)
  2296. # else:
  2297. # for tool in self.tools:
  2298. # for geo in self.tools[tool]['solid_geometry']:
  2299. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2300. # for ints in geo.interiors:
  2301. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  2302. #
  2303. # self.shapes.redraw()
  2304. # return
  2305. # except (ObjectDeleted, AttributeError, KeyError):
  2306. # self.shapes.clear(update=True)
  2307. # this stays for compatibility reasons, in case we try to open old projects
  2308. try:
  2309. __ = iter(self.solid_geometry)
  2310. except TypeError:
  2311. self.solid_geometry = [self.solid_geometry]
  2312. try:
  2313. # Plot Excellon (All polygons?)
  2314. if self.options["solid"]:
  2315. for geo in self.solid_geometry:
  2316. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2317. visible=self.options['plot'],
  2318. layer=2)
  2319. else:
  2320. for geo in self.solid_geometry:
  2321. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2322. for ints in geo.interiors:
  2323. self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  2324. self.shapes.redraw()
  2325. except (ObjectDeleted, AttributeError):
  2326. self.shapes.clear(update=True)
  2327. class FlatCAMGeometry(FlatCAMObj, Geometry):
  2328. """
  2329. Geometric object not associated with a specific
  2330. format.
  2331. """
  2332. optionChanged = QtCore.pyqtSignal(str)
  2333. ui_type = GeometryObjectUI
  2334. def merge(self, geo_list, geo_final, multigeo=None):
  2335. """
  2336. Merges the geometry of objects in grb_list into
  2337. the geometry of geo_final.
  2338. :param geo_list: List of FlatCAMGerber Objects to join.
  2339. :param geo_final: Destination FlatCAMGerber object.
  2340. :return: None
  2341. """
  2342. if geo_final.solid_geometry is None:
  2343. geo_final.solid_geometry = []
  2344. if type(geo_final.solid_geometry) is not list:
  2345. geo_final.solid_geometry = [geo_final.solid_geometry]
  2346. for geo in geo_list:
  2347. for option in geo.options:
  2348. if option is not 'name':
  2349. try:
  2350. geo_final.options[option] = geo.options[option]
  2351. except Exception as e:
  2352. log.warning("Failed to copy option.", option)
  2353. # Expand lists
  2354. if type(geo) is list:
  2355. FlatCAMGeometry.merge(self, geo_list=geo, geo_final=geo_final)
  2356. # If not list, just append
  2357. else:
  2358. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  2359. if multigeo is None or multigeo is False:
  2360. geo_final.multigeo = False
  2361. try:
  2362. geo_final.solid_geometry.append(geo.solid_geometry)
  2363. except Exception as e:
  2364. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  2365. else:
  2366. geo_final.multigeo = True
  2367. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  2368. # tools object attribute, as a key value
  2369. geo_final.solid_geometry = []
  2370. # find the tool_uid maximum value in the geo_final
  2371. geo_final_uid_list = []
  2372. for key in geo_final.tools:
  2373. geo_final_uid_list.append(int(key))
  2374. try:
  2375. max_uid = max(geo_final_uid_list, key=int)
  2376. except ValueError:
  2377. max_uid = 0
  2378. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2379. # to merge the obj.tools as it is likely there is none to merge.
  2380. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  2381. for tool_uid in geo.tools:
  2382. max_uid += 1
  2383. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  2384. @staticmethod
  2385. def get_pts(o):
  2386. """
  2387. Returns a list of all points in the object, where
  2388. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2389. of such. Search is done recursively.
  2390. :param: geometric object
  2391. :return: List of points
  2392. :rtype: list
  2393. """
  2394. pts = []
  2395. # Iterable: descend into each item.
  2396. try:
  2397. for subo in o:
  2398. pts += FlatCAMGeometry.get_pts(subo)
  2399. # Non-iterable
  2400. except TypeError:
  2401. if o is not None:
  2402. if type(o) == MultiPolygon:
  2403. for poly in o:
  2404. pts += FlatCAMGeometry.get_pts(poly)
  2405. # ## Descend into .exerior and .interiors
  2406. elif type(o) == Polygon:
  2407. pts += FlatCAMGeometry.get_pts(o.exterior)
  2408. for i in o.interiors:
  2409. pts += FlatCAMGeometry.get_pts(i)
  2410. elif type(o) == MultiLineString:
  2411. for line in o:
  2412. pts += FlatCAMGeometry.get_pts(line)
  2413. # ## Has .coords: list them.
  2414. else:
  2415. pts += list(o.coords)
  2416. else:
  2417. return
  2418. return pts
  2419. def __init__(self, name):
  2420. FlatCAMObj.__init__(self, name)
  2421. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2422. self.kind = "geometry"
  2423. self.options.update({
  2424. "plot": True,
  2425. "cutz": -0.002,
  2426. "vtipdia": 0.1,
  2427. "vtipangle": 30,
  2428. "travelz": 0.1,
  2429. "feedrate": 5.0,
  2430. "feedrate_z": 5.0,
  2431. "feedrate_rapid": 5.0,
  2432. "spindlespeed": None,
  2433. "dwell": True,
  2434. "dwelltime": 1000,
  2435. "multidepth": False,
  2436. "depthperpass": 0.002,
  2437. "extracut": False,
  2438. "endz": 2.0,
  2439. "toolchange": False,
  2440. "toolchangez": 1.0,
  2441. "toolchangexy": "0.0, 0.0",
  2442. "startz": None,
  2443. "ppname_g": 'default',
  2444. "z_pdepth": -0.02,
  2445. "feedrate_probe": 3.0,
  2446. })
  2447. if "cnctooldia" not in self.options:
  2448. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2449. # try:
  2450. # self.options["cnctooldia"] = [
  2451. # float(eval(dia)) for dia in str(self.app.defaults["geometry_cnctooldia"]).split(",")
  2452. # ]
  2453. # except Exception as e:
  2454. # log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> Geometry General -> "
  2455. # "Tool dia. %s" % str(e))
  2456. # return
  2457. self.options["startz"] = self.app.defaults["geometry_startz"]
  2458. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2459. self.tooluid = 0
  2460. '''
  2461. self.tools = {}
  2462. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2463. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2464. {tooluid: {
  2465. 'tooldia': 1,
  2466. 'offset': 'Path',
  2467. 'offset_value': 0.0
  2468. 'type': 'Rough',
  2469. 'tool_type': 'C1',
  2470. 'data': self.default_tool_data
  2471. 'solid_geometry': []
  2472. }
  2473. }
  2474. '''
  2475. self.tools = {}
  2476. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2477. # those elements are the ones used for generating GCode
  2478. self.sel_tools = {}
  2479. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2480. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  2481. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2482. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2483. self.v_tool_type = None
  2484. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  2485. # the default value is False
  2486. self.multigeo = False
  2487. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  2488. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  2489. self. special_group = None
  2490. self.old_pp_state = ''
  2491. self.old_toolchangeg_state = ''
  2492. # Attributes to be included in serialization
  2493. # Always append to it because it carries contents
  2494. # from predecessors.
  2495. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2496. def build_ui(self):
  2497. self.ui_disconnect()
  2498. FlatCAMObj.build_ui(self)
  2499. offset = 0
  2500. tool_idx = 0
  2501. n = len(self.tools)
  2502. self.ui.geo_tools_table.setRowCount(n)
  2503. for tooluid_key, tooluid_value in self.tools.items():
  2504. tool_idx += 1
  2505. row_no = tool_idx - 1
  2506. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2507. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2508. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2509. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2510. # There are no tool bits in MM with more than 3 decimals diameter.
  2511. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2512. if self.units == 'MM':
  2513. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2514. else:
  2515. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2516. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2517. offset_item = QtWidgets.QComboBox()
  2518. for item in self.offset_item_options:
  2519. offset_item.addItem(item)
  2520. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2521. idx = offset_item.findText(tooluid_value['offset'])
  2522. offset_item.setCurrentIndex(idx)
  2523. type_item = QtWidgets.QComboBox()
  2524. for item in self.type_item_options:
  2525. type_item.addItem(item)
  2526. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2527. idx = type_item.findText(tooluid_value['type'])
  2528. type_item.setCurrentIndex(idx)
  2529. tool_type_item = QtWidgets.QComboBox()
  2530. for item in self.tool_type_item_options:
  2531. tool_type_item.addItem(item)
  2532. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2533. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2534. tool_type_item.setCurrentIndex(idx)
  2535. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2536. plot_item = FCCheckBox()
  2537. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2538. if self.ui.plot_cb.isChecked():
  2539. plot_item.setChecked(True)
  2540. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2541. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2542. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2543. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2544. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  2545. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2546. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2547. try:
  2548. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2549. except Exception as e:
  2550. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2551. # make the diameter column editable
  2552. for row in range(tool_idx):
  2553. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2554. QtCore.Qt.ItemIsEditable |
  2555. QtCore.Qt.ItemIsEnabled)
  2556. # sort the tool diameter column
  2557. # self.ui.geo_tools_table.sortItems(1)
  2558. # all the tools are selected by default
  2559. # self.ui.geo_tools_table.selectColumn(0)
  2560. self.ui.geo_tools_table.resizeColumnsToContents()
  2561. self.ui.geo_tools_table.resizeRowsToContents()
  2562. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2563. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2564. vertical_header.hide()
  2565. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2566. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2567. horizontal_header.setMinimumSectionSize(10)
  2568. horizontal_header.setDefaultSectionSize(70)
  2569. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2570. horizontal_header.resizeSection(0, 20)
  2571. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2572. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2573. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2574. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2575. horizontal_header.resizeSection(4, 40)
  2576. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2577. horizontal_header.resizeSection(4, 17)
  2578. # horizontal_header.setStretchLastSection(True)
  2579. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2580. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2581. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2582. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2583. # self.ui.geo_tools_table.setSortingEnabled(True)
  2584. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2585. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2586. # update UI for all rows - useful after units conversion but only if there is at least one row
  2587. row_cnt = self.ui.geo_tools_table.rowCount()
  2588. if row_cnt > 0:
  2589. for r in range(row_cnt):
  2590. self.update_ui(r)
  2591. # select only the first tool / row
  2592. selected_row = 0
  2593. try:
  2594. self.select_tools_table_row(selected_row, clearsel=True)
  2595. # update the Geometry UI
  2596. self.update_ui()
  2597. except Exception as e:
  2598. # when the tools table is empty there will be this error but once the table is populated it will go away
  2599. log.debug(str(e))
  2600. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2601. # and can create some problems
  2602. if self.multigeo is False:
  2603. self.ui.geo_tools_table.setColumnHidden(6, True)
  2604. else:
  2605. self.ui.geo_tools_table.setColumnHidden(6, False)
  2606. self.set_tool_offset_visibility(selected_row)
  2607. self.ui_connect()
  2608. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  2609. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  2610. self.ui.name_entry.set_value(self.options['name'])
  2611. def set_ui(self, ui):
  2612. FlatCAMObj.set_ui(self, ui)
  2613. log.debug("FlatCAMGeometry.set_ui()")
  2614. assert isinstance(self.ui, GeometryObjectUI), \
  2615. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2616. # populate postprocessor names in the combobox
  2617. for name in list(self.app.postprocessors.keys()):
  2618. self.ui.pp_geometry_name_cb.addItem(name)
  2619. self.form_fields.update({
  2620. "plot": self.ui.plot_cb,
  2621. "cutz": self.ui.cutz_entry,
  2622. "vtipdia": self.ui.tipdia_entry,
  2623. "vtipangle": self.ui.tipangle_entry,
  2624. "travelz": self.ui.travelz_entry,
  2625. "feedrate": self.ui.cncfeedrate_entry,
  2626. "feedrate_z": self.ui.cncplunge_entry,
  2627. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2628. "spindlespeed": self.ui.cncspindlespeed_entry,
  2629. "dwell": self.ui.dwell_cb,
  2630. "dwelltime": self.ui.dwelltime_entry,
  2631. "multidepth": self.ui.mpass_cb,
  2632. "ppname_g": self.ui.pp_geometry_name_cb,
  2633. "z_pdepth": self.ui.pdepth_entry,
  2634. "feedrate_probe": self.ui.feedrate_probe_entry,
  2635. "depthperpass": self.ui.maxdepth_entry,
  2636. "extracut": self.ui.extracut_cb,
  2637. "toolchange": self.ui.toolchangeg_cb,
  2638. "toolchangez": self.ui.toolchangez_entry,
  2639. "endz": self.ui.gendz_entry,
  2640. })
  2641. # Fill form fields only on object create
  2642. self.to_form()
  2643. self.ui.tipdialabel.hide()
  2644. self.ui.tipdia_entry.hide()
  2645. self.ui.tipanglelabel.hide()
  2646. self.ui.tipangle_entry.hide()
  2647. self.ui.cutz_entry.setDisabled(False)
  2648. # store here the default data for Geometry Data
  2649. self.default_data = {}
  2650. self.default_data.update({
  2651. "name": None,
  2652. "plot": None,
  2653. "cutz": None,
  2654. "vtipdia": None,
  2655. "vtipangle": None,
  2656. "travelz": None,
  2657. "feedrate": None,
  2658. "feedrate_z": None,
  2659. "feedrate_rapid": None,
  2660. "dwell": None,
  2661. "dwelltime": None,
  2662. "multidepth": None,
  2663. "ppname_g": None,
  2664. "depthperpass": None,
  2665. "extracut": None,
  2666. "toolchange": None,
  2667. "toolchangez": None,
  2668. "endz": None,
  2669. "spindlespeed": None,
  2670. "toolchangexy": None,
  2671. "startz": None
  2672. })
  2673. # fill in self.default_data values from self.options
  2674. for def_key in self.default_data:
  2675. for opt_key, opt_val in self.options.items():
  2676. if def_key == opt_key:
  2677. self.default_data[def_key] = deepcopy(opt_val)
  2678. try:
  2679. temp_tools = self.options["cnctooldia"].split(",")
  2680. tools_list = [
  2681. float(eval(dia)) for dia in temp_tools if dia != ''
  2682. ]
  2683. except Exception as e:
  2684. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> Geometry General -> "
  2685. "Tool dia. %s" % str(e))
  2686. return
  2687. self.tooluid += 1
  2688. if not self.tools:
  2689. for toold in tools_list:
  2690. self.tools.update({
  2691. self.tooluid: {
  2692. 'tooldia': float(toold),
  2693. 'offset': 'Path',
  2694. 'offset_value': 0.0,
  2695. 'type': _('Rough'),
  2696. 'tool_type': 'C1',
  2697. 'data': self.default_data,
  2698. 'solid_geometry': self.solid_geometry
  2699. }
  2700. })
  2701. self.tooluid += 1
  2702. else:
  2703. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2704. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2705. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2706. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2707. # following convoluted way of changing the keys from string to float type
  2708. temp_tools = {}
  2709. new_key = 0.0
  2710. for tooluid_key in self.tools:
  2711. val = deepcopy(self.tools[tooluid_key])
  2712. new_key = deepcopy(int(tooluid_key))
  2713. temp_tools[new_key] = val
  2714. self.tools.clear()
  2715. self.tools = deepcopy(temp_tools)
  2716. self.ui.tool_offset_entry.hide()
  2717. self.ui.tool_offset_lbl.hide()
  2718. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2719. self.old_pp_state = self.default_data['multidepth']
  2720. self.old_toolchangeg_state = self.default_data['toolchange']
  2721. if not isinstance(self.ui, GeometryObjectUI):
  2722. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2723. return
  2724. self.ui.geo_tools_table.setupContextMenu()
  2725. self.ui.geo_tools_table.addContextMenu(
  2726. _("Copy"), self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2727. self.ui.geo_tools_table.addContextMenu(
  2728. _("Delete"), lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2729. # Show/Hide Advanced Options
  2730. if self.app.defaults["global_app_level"] == 'b':
  2731. self.ui.level.setText(_(
  2732. '<span style="color:green;"><b>Basic</b></span>'
  2733. ))
  2734. self.ui.geo_tools_table.setColumnHidden(2, True)
  2735. self.ui.geo_tools_table.setColumnHidden(3, True)
  2736. self.ui.geo_tools_table.setColumnHidden(4, True)
  2737. self.ui.addtool_entry_lbl.hide()
  2738. self.ui.addtool_entry.hide()
  2739. self.ui.addtool_btn.hide()
  2740. self.ui.copytool_btn.hide()
  2741. self.ui.deltool_btn.hide()
  2742. self.ui.endzlabel.hide()
  2743. self.ui.gendz_entry.hide()
  2744. self.ui.fr_rapidlabel.hide()
  2745. self.ui.cncfeedrate_rapid_entry.hide()
  2746. self.ui.extracut_cb.hide()
  2747. self.ui.pdepth_label.hide()
  2748. self.ui.pdepth_entry.hide()
  2749. self.ui.feedrate_probe_label.hide()
  2750. self.ui.feedrate_probe_entry.hide()
  2751. else:
  2752. self.ui.level.setText(_(
  2753. '<span style="color:red;"><b>Advanced</b></span>'
  2754. ))
  2755. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2756. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2757. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  2758. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2759. self.ui.addtool_entry.returnPressed.connect(lambda: self.on_tool_add())
  2760. def set_tool_offset_visibility(self, current_row):
  2761. if current_row is None:
  2762. return
  2763. try:
  2764. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2765. if tool_offset is not None:
  2766. tool_offset_txt = tool_offset.currentText()
  2767. if tool_offset_txt == 'Custom':
  2768. self.ui.tool_offset_entry.show()
  2769. self.ui.tool_offset_lbl.show()
  2770. else:
  2771. self.ui.tool_offset_entry.hide()
  2772. self.ui.tool_offset_lbl.hide()
  2773. except Exception as e:
  2774. log.debug("set_tool_offset_visibility() --> " + str(e))
  2775. return
  2776. def on_offset_value_edited(self):
  2777. """
  2778. This will save the offset_value into self.tools storage whenever the offset value is edited
  2779. :return:
  2780. """
  2781. for current_row in self.ui.geo_tools_table.selectedItems():
  2782. # sometime the header get selected and it has row number -1
  2783. # we don't want to do anything with the header :)
  2784. if current_row.row() < 0:
  2785. continue
  2786. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2787. self.set_tool_offset_visibility(current_row.row())
  2788. for tooluid_key, tooluid_value in self.tools.items():
  2789. if int(tooluid_key) == tool_uid:
  2790. try:
  2791. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2792. except ValueError:
  2793. # try to convert comma to decimal point. if it's still not working error message and return
  2794. try:
  2795. tooluid_value['offset_value'] = float(
  2796. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2797. )
  2798. except ValueError:
  2799. self.app.inform.emit(_(
  2800. "[ERROR_NOTCL] Wrong value format entered, "
  2801. "use a number."
  2802. )
  2803. )
  2804. return
  2805. def ui_connect(self):
  2806. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2807. # changes in geometry UI
  2808. for i in range(self.ui.grid3.count()):
  2809. # try:
  2810. # # works for CheckBoxes
  2811. # self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2812. # except Exception as e:
  2813. # # works for ComboBoxes
  2814. # try:
  2815. # self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2816. # except Exception as e2:
  2817. # # works for Entry
  2818. # try:
  2819. # self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2820. # except Exception as e3:
  2821. # pass
  2822. current_widget = self.ui.grid3.itemAt(i).widget()
  2823. if isinstance(current_widget, FCCheckBox):
  2824. current_widget.stateChanged.connect(self.gui_form_to_storage)
  2825. elif isinstance(current_widget, FCComboBox):
  2826. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  2827. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  2828. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  2829. current_widget.editingFinished.connect(self.gui_form_to_storage)
  2830. for row in range(self.ui.geo_tools_table.rowCount()):
  2831. for col in [2, 3, 4]:
  2832. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2833. self.on_tooltable_cellwidget_change)
  2834. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2835. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2836. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2837. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2838. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2839. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2840. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2841. for row in range(self.ui.geo_tools_table.rowCount()):
  2842. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2843. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2844. def ui_disconnect(self):
  2845. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2846. # changes in geometry UI
  2847. for i in range(self.ui.grid3.count()):
  2848. # try:
  2849. # # works for CheckBoxes
  2850. # self.ui.grid3.itemAt(i).widget().stateChanged.disconnect(self.gui_form_to_storage)
  2851. # except Exception as e:
  2852. # # works for ComboBoxes
  2853. # try:
  2854. # self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect(self.gui_form_to_storage)
  2855. # except Exception as e2:
  2856. # # works for Entry
  2857. # try:
  2858. # self.ui.grid3.itemAt(i).widget().editingFinished.disconnect(self.gui_form_to_storage)
  2859. # except Exception as e3:
  2860. # pass
  2861. current_widget = self.ui.grid3.itemAt(i).widget()
  2862. if isinstance(current_widget, FCCheckBox):
  2863. try:
  2864. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect(self.gui_form_to_storage)
  2865. except TypeError:
  2866. pass
  2867. elif isinstance(current_widget, FCComboBox):
  2868. try:
  2869. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect(self.gui_form_to_storage)
  2870. except TypeError:
  2871. pass
  2872. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  2873. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  2874. try:
  2875. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect(self.gui_form_to_storage)
  2876. except TypeError:
  2877. pass
  2878. for row in range(self.ui.geo_tools_table.rowCount()):
  2879. for col in [2, 3, 4]:
  2880. try:
  2881. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2882. except TypeError:
  2883. pass
  2884. try:
  2885. self.ui.addtool_btn.clicked.disconnect()
  2886. except TypeError:
  2887. pass
  2888. try:
  2889. self.ui.copytool_btn.clicked.disconnect()
  2890. except TypeError:
  2891. pass
  2892. try:
  2893. self.ui.deltool_btn.clicked.disconnect()
  2894. except TypeError:
  2895. pass
  2896. try:
  2897. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2898. except TypeError:
  2899. pass
  2900. try:
  2901. self.ui.geo_tools_table.itemChanged.disconnect()
  2902. except TypeError:
  2903. pass
  2904. try:
  2905. self.ui.tool_offset_entry.editingFinished.disconnect()
  2906. except TypeError:
  2907. pass
  2908. for row in range(self.ui.geo_tools_table.rowCount()):
  2909. try:
  2910. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2911. except TypeError:
  2912. pass
  2913. try:
  2914. self.ui.plot_cb.stateChanged.disconnect()
  2915. except TypeError:
  2916. pass
  2917. def on_tool_add(self, dia=None):
  2918. self.ui_disconnect()
  2919. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2920. # because the Default value for Tool is used.
  2921. change_message = False
  2922. if dia is not None:
  2923. tooldia = dia
  2924. else:
  2925. try:
  2926. tooldia = float(self.ui.addtool_entry.get_value())
  2927. except ValueError:
  2928. # try to convert comma to decimal point. if it's still not working error message and return
  2929. try:
  2930. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2931. except ValueError:
  2932. change_message = True
  2933. tooldia = self.options["cnctooldia"][0]
  2934. if tooldia is None:
  2935. self.build_ui()
  2936. self.app.inform.emit(_(
  2937. "[ERROR_NOTCL] Please enter the desired tool diameter in Float format."
  2938. ))
  2939. return
  2940. # construct a list of all 'tooluid' in the self.tools
  2941. tool_uid_list = []
  2942. for tooluid_key in self.tools:
  2943. tool_uid_item = int(tooluid_key)
  2944. tool_uid_list.append(tool_uid_item)
  2945. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2946. if not tool_uid_list:
  2947. max_uid = 0
  2948. else:
  2949. max_uid = max(tool_uid_list)
  2950. self.tooluid = max_uid + 1
  2951. if self.units == 'IN':
  2952. tooldia = float('%.4f' % tooldia)
  2953. else:
  2954. tooldia = float('%.2f' % tooldia)
  2955. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2956. # otherwise we add a tool with data copied from last tool
  2957. if not self.tools:
  2958. self.tools.update({
  2959. self.tooluid: {
  2960. 'tooldia': tooldia,
  2961. 'offset': 'Path',
  2962. 'offset_value': 0.0,
  2963. 'type': _('Rough'),
  2964. 'tool_type': 'C1',
  2965. 'data': deepcopy(self.default_data),
  2966. 'solid_geometry': self.solid_geometry
  2967. }
  2968. })
  2969. else:
  2970. last_data = self.tools[max_uid]['data']
  2971. last_offset = self.tools[max_uid]['offset']
  2972. last_offset_value = self.tools[max_uid]['offset_value']
  2973. last_type = self.tools[max_uid]['type']
  2974. last_tool_type = self.tools[max_uid]['tool_type']
  2975. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2976. # if previous geometry was empty (it may happen for the first tool added)
  2977. # then copy the object.solid_geometry
  2978. if not last_solid_geometry:
  2979. last_solid_geometry = self.solid_geometry
  2980. self.tools.update({
  2981. self.tooluid: {
  2982. 'tooldia': tooldia,
  2983. 'offset': last_offset,
  2984. 'offset_value': last_offset_value,
  2985. 'type': last_type,
  2986. 'tool_type': last_tool_type,
  2987. 'data': deepcopy(last_data),
  2988. 'solid_geometry': deepcopy(last_solid_geometry)
  2989. }
  2990. })
  2991. self.tools[self.tooluid]['data']['name'] = self.options['name']
  2992. self.ui.tool_offset_entry.hide()
  2993. self.ui.tool_offset_lbl.hide()
  2994. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2995. try:
  2996. self.ser_attrs.remove('tools')
  2997. except TypeError:
  2998. pass
  2999. self.ser_attrs.append('tools')
  3000. if change_message is False:
  3001. self.app.inform.emit(_(
  3002. "[success] Tool added in Tool Table."
  3003. ))
  3004. else:
  3005. change_message = False
  3006. self.app.inform.emit(_(
  3007. "[ERROR_NOTCL] Default Tool added. Wrong value format entered."
  3008. ))
  3009. self.build_ui()
  3010. def on_tool_copy(self, all=None):
  3011. self.ui_disconnect()
  3012. # find the tool_uid maximum value in the self.tools
  3013. uid_list = []
  3014. for key in self.tools:
  3015. uid_list.append(int(key))
  3016. try:
  3017. max_uid = max(uid_list, key=int)
  3018. except ValueError:
  3019. max_uid = 0
  3020. if all is None:
  3021. if self.ui.geo_tools_table.selectedItems():
  3022. for current_row in self.ui.geo_tools_table.selectedItems():
  3023. # sometime the header get selected and it has row number -1
  3024. # we don't want to do anything with the header :)
  3025. if current_row.row() < 0:
  3026. continue
  3027. try:
  3028. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3029. self.set_tool_offset_visibility(current_row.row())
  3030. max_uid += 1
  3031. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  3032. except AttributeError:
  3033. self.app.inform.emit(_(
  3034. "[WARNING_NOTCL] Failed. Select a tool to copy."
  3035. ))
  3036. self.build_ui()
  3037. return
  3038. except Exception as e:
  3039. log.debug("on_tool_copy() --> " + str(e))
  3040. # deselect the table
  3041. # self.ui.geo_tools_table.clearSelection()
  3042. else:
  3043. self.app.inform.emit(_(
  3044. "[WARNING_NOTCL] Failed. Select a tool to copy."
  3045. ))
  3046. self.build_ui()
  3047. return
  3048. else:
  3049. # we copy all tools in geo_tools_table
  3050. try:
  3051. temp_tools = deepcopy(self.tools)
  3052. max_uid += 1
  3053. for tooluid in temp_tools:
  3054. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3055. temp_tools.clear()
  3056. except Exception as e:
  3057. log.debug("on_tool_copy() --> " + str(e))
  3058. # if there are no more tools in geo tools table then hide the tool offset
  3059. if not self.tools:
  3060. self.ui.tool_offset_entry.hide()
  3061. self.ui.tool_offset_lbl.hide()
  3062. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3063. try:
  3064. self.ser_attrs.remove('tools')
  3065. except Exception as e:
  3066. pass
  3067. self.ser_attrs.append('tools')
  3068. self.build_ui()
  3069. self.app.inform.emit(_(
  3070. "[success] Tool was copied in Tool Table."
  3071. ))
  3072. def on_tool_edit(self, current_item):
  3073. self.ui_disconnect()
  3074. current_row = current_item.row()
  3075. try:
  3076. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3077. except ValueError:
  3078. # try to convert comma to decimal point. if it's still not working error message and return
  3079. try:
  3080. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3081. except ValueError:
  3082. self.app.inform.emit(_(
  3083. "[ERROR_NOTCL] Wrong value format entered, "
  3084. "use a number."
  3085. ))
  3086. return
  3087. tool_dia = float('%.4f' % d)
  3088. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3089. self.tools[tooluid]['tooldia'] = tool_dia
  3090. try:
  3091. self.ser_attrs.remove('tools')
  3092. self.ser_attrs.append('tools')
  3093. except TypeError:
  3094. pass
  3095. self.app.inform.emit(_(
  3096. "[success] Tool was edited in Tool Table."
  3097. ))
  3098. self.build_ui()
  3099. def on_tool_delete(self, all=None):
  3100. self.ui_disconnect()
  3101. if all is None:
  3102. if self.ui.geo_tools_table.selectedItems():
  3103. for current_row in self.ui.geo_tools_table.selectedItems():
  3104. # sometime the header get selected and it has row number -1
  3105. # we don't want to do anything with the header :)
  3106. if current_row.row() < 0:
  3107. continue
  3108. try:
  3109. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3110. self.set_tool_offset_visibility(current_row.row())
  3111. temp_tools = deepcopy(self.tools)
  3112. for tooluid_key in self.tools:
  3113. if int(tooluid_key) == tooluid_del:
  3114. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3115. # as a property of the object otherwise there will be nothing to hold it
  3116. if len(self.tools) == 1:
  3117. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3118. temp_tools.pop(tooluid_del, None)
  3119. self.tools = deepcopy(temp_tools)
  3120. temp_tools.clear()
  3121. except AttributeError:
  3122. self.app.inform.emit(_("[WARNING_NOTCL] Failed. Select a tool to delete."))
  3123. self.build_ui()
  3124. return
  3125. except Exception as e:
  3126. log.debug("on_tool_delete() --> " + str(e))
  3127. # deselect the table
  3128. # self.ui.geo_tools_table.clearSelection()
  3129. else:
  3130. self.app.inform.emit(_("[WARNING_NOTCL] Failed. Select a tool to delete."))
  3131. self.build_ui()
  3132. return
  3133. else:
  3134. # we delete all tools in geo_tools_table
  3135. self.tools.clear()
  3136. self.app.plot_all()
  3137. # if there are no more tools in geo tools table then hide the tool offset
  3138. if not self.tools:
  3139. self.ui.tool_offset_entry.hide()
  3140. self.ui.tool_offset_lbl.hide()
  3141. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3142. try:
  3143. self.ser_attrs.remove('tools')
  3144. except TypeError:
  3145. pass
  3146. self.ser_attrs.append('tools')
  3147. self.build_ui()
  3148. self.app.inform.emit(_("[success] Tool was deleted in Tool Table."))
  3149. obj_active = self.app.collection.get_active()
  3150. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  3151. # we make it back SingleGeo
  3152. if self.ui.geo_tools_table.rowCount() <= 0:
  3153. obj_active.multigeo = False
  3154. obj_active.options['xmin'] = 0
  3155. obj_active.options['ymin'] = 0
  3156. obj_active.options['xmax'] = 0
  3157. obj_active.options['ymax'] = 0
  3158. if obj_active.multigeo is True:
  3159. try:
  3160. xmin, ymin, xmax, ymax = obj_active.bounds()
  3161. obj_active.options['xmin'] = xmin
  3162. obj_active.options['ymin'] = ymin
  3163. obj_active.options['xmax'] = xmax
  3164. obj_active.options['ymax'] = ymax
  3165. except Exception as e:
  3166. obj_active.options['xmin'] = 0
  3167. obj_active.options['ymin'] = 0
  3168. obj_active.options['xmax'] = 0
  3169. obj_active.options['ymax'] = 0
  3170. def on_row_selection_change(self):
  3171. self.update_ui()
  3172. def update_ui(self, row=None):
  3173. self.ui_disconnect()
  3174. if row is None:
  3175. try:
  3176. current_row = self.ui.geo_tools_table.currentRow()
  3177. except Exception as e:
  3178. current_row = 0
  3179. else:
  3180. current_row = row
  3181. if current_row < 0:
  3182. current_row = 0
  3183. self.set_tool_offset_visibility(current_row)
  3184. # populate the form with the data from the tool associated with the row parameter
  3185. try:
  3186. item = self.ui.geo_tools_table.item(current_row, 5)
  3187. if item is not None:
  3188. tooluid = int(item.text())
  3189. else:
  3190. return
  3191. except Exception as e:
  3192. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3193. return
  3194. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3195. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3196. try:
  3197. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  3198. if item is not None:
  3199. tool_type_txt = item.currentText()
  3200. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3201. else:
  3202. return
  3203. except Exception as e:
  3204. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3205. return
  3206. try:
  3207. # set the form with data from the newly selected tool
  3208. for tooluid_key, tooluid_value in self.tools.items():
  3209. if int(tooluid_key) == tooluid:
  3210. for key, value in tooluid_value.items():
  3211. if key == 'data':
  3212. form_value_storage = tooluid_value[key]
  3213. self.update_form(form_value_storage)
  3214. if key == 'offset_value':
  3215. # update the offset value in the entry even if the entry is hidden
  3216. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  3217. if key == 'tool_type' and value == 'V':
  3218. self.update_cutz()
  3219. except Exception as e:
  3220. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  3221. self.ui_connect()
  3222. def ui_update_v_shape(self, tool_type_txt):
  3223. if tool_type_txt == 'V':
  3224. self.ui.tipdialabel.show()
  3225. self.ui.tipdia_entry.show()
  3226. self.ui.tipanglelabel.show()
  3227. self.ui.tipangle_entry.show()
  3228. self.ui.cutz_entry.setDisabled(True)
  3229. self.update_cutz()
  3230. else:
  3231. self.ui.tipdialabel.hide()
  3232. self.ui.tipdia_entry.hide()
  3233. self.ui.tipanglelabel.hide()
  3234. self.ui.tipangle_entry.hide()
  3235. self.ui.cutz_entry.setDisabled(False)
  3236. def update_cutz(self):
  3237. try:
  3238. vdia = float(self.ui.tipdia_entry.get_value())
  3239. except ValueError:
  3240. # try to convert comma to decimal point. if it's still not working error message and return
  3241. try:
  3242. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  3243. except ValueError:
  3244. self.app.inform.emit(_(
  3245. "[ERROR_NOTCL] Wrong value format entered, "
  3246. "use a number."
  3247. ))
  3248. return
  3249. try:
  3250. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  3251. except ValueError:
  3252. # try to convert comma to decimal point. if it's still not working error message and return
  3253. try:
  3254. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  3255. except ValueError:
  3256. self.app.inform.emit(_(
  3257. "[ERROR_NOTCL] Wrong value format entered, "
  3258. "use a number."
  3259. ))
  3260. return
  3261. row = self.ui.geo_tools_table.currentRow()
  3262. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  3263. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  3264. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  3265. new_cutz = float('%.4f' % -new_cutz)
  3266. self.ui.cutz_entry.set_value(new_cutz)
  3267. # store the new CutZ value into storage (self.tools)
  3268. for tooluid_key, tooluid_value in self.tools.items():
  3269. if int(tooluid_key) == tool_uid:
  3270. tooluid_value['data']['cutz'] = new_cutz
  3271. def on_tooltable_cellwidget_change(self):
  3272. cw = self.sender()
  3273. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3274. cw_row = cw_index.row()
  3275. cw_col = cw_index.column()
  3276. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  3277. # store the text of the cellWidget that changed it's index in the self.tools
  3278. for tooluid_key, tooluid_value in self.tools.items():
  3279. if int(tooluid_key) == current_uid:
  3280. cb_txt = cw.currentText()
  3281. if cw_col == 2:
  3282. tooluid_value['offset'] = cb_txt
  3283. if cb_txt == 'Custom':
  3284. self.ui.tool_offset_entry.show()
  3285. self.ui.tool_offset_lbl.show()
  3286. else:
  3287. self.ui.tool_offset_entry.hide()
  3288. self.ui.tool_offset_lbl.hide()
  3289. # reset the offset_value in storage self.tools
  3290. tooluid_value['offset_value'] = 0.0
  3291. elif cw_col == 3:
  3292. # force toolpath type as 'Iso' if the tool type is V-Shape
  3293. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  3294. tooluid_value['type'] = _('Iso')
  3295. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3296. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3297. else:
  3298. tooluid_value['type'] = cb_txt
  3299. elif cw_col == 4:
  3300. tooluid_value['tool_type'] = cb_txt
  3301. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  3302. if cb_txt == 'V':
  3303. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3304. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3305. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  3306. def update_form(self, dict_storage):
  3307. for form_key in self.form_fields:
  3308. for storage_key in dict_storage:
  3309. if form_key == storage_key:
  3310. try:
  3311. self.form_fields[form_key].set_value(dict_storage[form_key])
  3312. except Exception as e:
  3313. log.debug(str(e))
  3314. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  3315. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  3316. self.ui.ois_dwell_geo.on_cb_change()
  3317. self.ui.ois_mpass_geo.on_cb_change()
  3318. self.ui.ois_tcz_geo.on_cb_change()
  3319. def gui_form_to_storage(self):
  3320. self.ui_disconnect()
  3321. widget_changed = self.sender()
  3322. try:
  3323. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3324. except Exception as e:
  3325. return
  3326. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3327. if widget_idx == 1 or widget_idx == 3:
  3328. self.update_cutz()
  3329. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  3330. # ui_diconnect() so I use this 'hack'
  3331. if isinstance(widget_changed, FCCheckBox):
  3332. if widget_changed.text() == 'Multi-Depth:':
  3333. self.ui.ois_mpass_geo.on_cb_change()
  3334. if widget_changed.text() == 'Tool change':
  3335. self.ui.ois_tcz_geo.on_cb_change()
  3336. if widget_changed.text() == 'Dwell:':
  3337. self.ui.ois_dwell_geo.on_cb_change()
  3338. row = self.ui.geo_tools_table.currentRow()
  3339. if row < 0:
  3340. row = 0
  3341. # store all the data associated with the row parameter to the self.tools storage
  3342. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3343. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3344. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3345. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3346. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3347. try:
  3348. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3349. except ValueError:
  3350. # try to convert comma to decimal point. if it's still not working error message and return
  3351. try:
  3352. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  3353. except ValueError:
  3354. self.app.inform.emit(_(
  3355. "[ERROR_NOTCL] Wrong value format entered, "
  3356. "use a number."
  3357. ))
  3358. return
  3359. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3360. temp_tools = {}
  3361. temp_dia = {}
  3362. temp_data = {}
  3363. for tooluid_key, tooluid_value in self.tools.items():
  3364. if int(tooluid_key) == tooluid_item:
  3365. for key, value in tooluid_value.items():
  3366. if key == 'tooldia':
  3367. temp_dia[key] = tooldia_item
  3368. # update the 'offset', 'type' and 'tool_type' sections
  3369. if key == 'offset':
  3370. temp_dia[key] = offset_item
  3371. if key == 'type':
  3372. temp_dia[key] = type_item
  3373. if key == 'tool_type':
  3374. temp_dia[key] = tool_type_item
  3375. if key == 'offset_value':
  3376. temp_dia[key] = offset_value_item
  3377. if key == 'data':
  3378. # update the 'data' section
  3379. for data_key in tooluid_value[key].keys():
  3380. for form_key, form_value in self.form_fields.items():
  3381. if form_key == data_key:
  3382. temp_data[data_key] = form_value.get_value()
  3383. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3384. # updated from self.app.defaults
  3385. if data_key not in self.form_fields:
  3386. temp_data[data_key] = value[data_key]
  3387. temp_dia[key] = deepcopy(temp_data)
  3388. temp_data.clear()
  3389. if key == 'solid_geometry':
  3390. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3391. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3392. else:
  3393. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  3394. self.tools.clear()
  3395. self.tools = deepcopy(temp_tools)
  3396. temp_tools.clear()
  3397. self.ui_connect()
  3398. def select_tools_table_row(self, row, clearsel=None):
  3399. if clearsel:
  3400. self.ui.geo_tools_table.clearSelection()
  3401. if self.ui.geo_tools_table.rowCount() > 0:
  3402. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3403. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3404. def export_dxf(self):
  3405. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3406. dwg = None
  3407. try:
  3408. dwg = ezdxf.new('R2010')
  3409. msp = dwg.modelspace()
  3410. def g2dxf(dxf_space, geo):
  3411. if isinstance(geo, MultiPolygon):
  3412. for poly in geo:
  3413. ext_points = list(poly.exterior.coords)
  3414. dxf_space.add_lwpolyline(ext_points)
  3415. for interior in poly.interiors:
  3416. dxf_space.add_lwpolyline(list(interior.coords))
  3417. if isinstance(geo, Polygon):
  3418. ext_points = list(geo.exterior.coords)
  3419. dxf_space.add_lwpolyline(ext_points)
  3420. for interior in geo.interiors:
  3421. dxf_space.add_lwpolyline(list(interior.coords))
  3422. if isinstance(geo, MultiLineString):
  3423. for line in geo:
  3424. dxf_space.add_lwpolyline(list(line.coords))
  3425. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  3426. dxf_space.add_lwpolyline(list(geo.coords))
  3427. multigeo_solid_geometry = []
  3428. if self.multigeo:
  3429. for tool in self.tools:
  3430. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  3431. else:
  3432. multigeo_solid_geometry = self.solid_geometry
  3433. for geo in multigeo_solid_geometry:
  3434. if type(geo) == list:
  3435. for g in geo:
  3436. g2dxf(msp, g)
  3437. else:
  3438. g2dxf(msp, geo)
  3439. # points = FlatCAMGeometry.get_pts(geo)
  3440. # msp.add_lwpolyline(points)
  3441. except Exception as e:
  3442. log.debug(str(e))
  3443. return dwg
  3444. def get_selected_tools_table_items(self):
  3445. """
  3446. Returns a list of lists, each list in the list is made out of row elements
  3447. :return: List of table_tools items.
  3448. :rtype: list
  3449. """
  3450. table_tools_items = []
  3451. if self.multigeo:
  3452. for x in self.ui.geo_tools_table.selectedItems():
  3453. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  3454. for column in range(0, self.ui.geo_tools_table.columnCount())])
  3455. else:
  3456. for x in self.ui.geo_tools_table.selectedItems():
  3457. r = []
  3458. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  3459. # so we don't read them
  3460. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  3461. # the columns have items that have text but also have items that are widgets
  3462. # for which the text they hold has to be read differently
  3463. try:
  3464. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  3465. except AttributeError:
  3466. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  3467. except Exception as e:
  3468. pass
  3469. r.append(txt)
  3470. table_tools_items.append(r)
  3471. for item in table_tools_items:
  3472. item[0] = str(item[0])
  3473. return table_tools_items
  3474. def on_pp_changed(self):
  3475. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3476. if current_pp == 'hpgl':
  3477. self.old_pp_state = self.ui.mpass_cb.get_value()
  3478. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3479. self.ui.mpass_cb.set_value(False)
  3480. self.ui.mpass_cb.setDisabled(True)
  3481. self.ui.toolchangeg_cb.set_value(True)
  3482. self.ui.toolchangeg_cb.setDisabled(True)
  3483. else:
  3484. self.ui.mpass_cb.set_value(self.old_pp_state)
  3485. self.ui.mpass_cb.setDisabled(False)
  3486. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3487. self.ui.toolchangeg_cb.setDisabled(False)
  3488. if "toolchange_probe" in current_pp.lower():
  3489. self.ui.pdepth_entry.setVisible(True)
  3490. self.ui.pdepth_label.show()
  3491. self.ui.feedrate_probe_entry.setVisible(True)
  3492. self.ui.feedrate_probe_label.show()
  3493. else:
  3494. self.ui.pdepth_entry.setVisible(False)
  3495. self.ui.pdepth_label.hide()
  3496. self.ui.feedrate_probe_entry.setVisible(False)
  3497. self.ui.feedrate_probe_label.hide()
  3498. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  3499. self.ui.fr_rapidlabel.show()
  3500. self.ui.cncfeedrate_rapid_entry.show()
  3501. else:
  3502. self.ui.fr_rapidlabel.hide()
  3503. self.ui.cncfeedrate_rapid_entry.hide()
  3504. def on_generatecnc_button_click(self, *args):
  3505. log.debug("Generating CNCJob from Geometry ...")
  3506. self.app.report_usage("geometry_on_generatecnc_button")
  3507. self.read_form()
  3508. self.sel_tools = {}
  3509. try:
  3510. if self.special_group:
  3511. self.app.inform.emit(_(
  3512. "[WARNING_NOTCL] This Geometry can't be processed because it is %s geometry."
  3513. ) % str(self.special_group))
  3514. return
  3515. except AttributeError:
  3516. pass
  3517. # test to see if we have tools available in the tool table
  3518. if self.ui.geo_tools_table.selectedItems():
  3519. for x in self.ui.geo_tools_table.selectedItems():
  3520. try:
  3521. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3522. except ValueError:
  3523. # try to convert comma to decimal point. if it's still not working error message and return
  3524. try:
  3525. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3526. except ValueError:
  3527. self.app.inform.emit(_(
  3528. "[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  3529. "use a number."
  3530. ))
  3531. return
  3532. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3533. for tooluid_key, tooluid_value in self.tools.items():
  3534. if int(tooluid_key) == tooluid:
  3535. self.sel_tools.update({
  3536. tooluid: deepcopy(tooluid_value)
  3537. })
  3538. self.mtool_gen_cncjob()
  3539. self.ui.geo_tools_table.clearSelection()
  3540. elif self.ui.geo_tools_table.rowCount() == 1:
  3541. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3542. for tooluid_key, tooluid_value in self.tools.items():
  3543. if int(tooluid_key) == tooluid:
  3544. self.sel_tools.update({
  3545. tooluid: deepcopy(tooluid_value)
  3546. })
  3547. self.mtool_gen_cncjob()
  3548. self.ui.geo_tools_table.clearSelection()
  3549. else:
  3550. self.app.inform.emit(_(
  3551. "[ERROR_NOTCL] Failed. No tool selected in the tool table ..."
  3552. ))
  3553. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3554. """
  3555. Creates a multi-tool CNCJob out of this Geometry object.
  3556. The actual work is done by the target FlatCAMCNCjob object's
  3557. `generate_from_geometry_2()` method.
  3558. :param z_cut: Cut depth (negative)
  3559. :param z_move: Hight of the tool when travelling (not cutting)
  3560. :param feedrate: Feed rate while cutting on X - Y plane
  3561. :param feedrate_z: Feed rate while cutting on Z plane
  3562. :param feedrate_rapid: Feed rate while moving with rapids
  3563. :param tooldia: Tool diameter
  3564. :param outname: Name of the new object
  3565. :param spindlespeed: Spindle speed (RPM)
  3566. :param ppname_g Name of the postprocessor
  3567. :return: None
  3568. """
  3569. offset_str = ''
  3570. multitool_gcode = ''
  3571. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3572. outname = "%s_%s" % (self.options["name"], 'cnc')
  3573. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3574. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3575. try:
  3576. xmin = self.options['xmin']
  3577. ymin = self.options['ymin']
  3578. xmax = self.options['xmax']
  3579. ymax = self.options['ymax']
  3580. except Exception as e:
  3581. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3582. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  3583. msg += _('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s') % str(e)
  3584. msg += traceback.format_exc()
  3585. self.app.inform.emit(msg)
  3586. return
  3587. # Object initialization function for app.new_object()
  3588. # RUNNING ON SEPARATE THREAD!
  3589. def job_init_single_geometry(job_obj, app_obj):
  3590. log.debug("Creating a CNCJob out of a single-geometry")
  3591. assert isinstance(job_obj, FlatCAMCNCjob), \
  3592. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3593. # count the tools
  3594. tool_cnt = 0
  3595. dia_cnc_dict = {}
  3596. # this turn on the FlatCAMCNCJob plot for multiple tools
  3597. job_obj.multitool = True
  3598. job_obj.multigeo = False
  3599. job_obj.cnc_tools.clear()
  3600. # job_obj.create_geometry()
  3601. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3602. job_obj.segx = segx
  3603. job_obj.segy = segy
  3604. try:
  3605. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3606. except ValueError:
  3607. # try to convert comma to decimal point. if it's still not working error message and return
  3608. try:
  3609. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3610. except ValueError:
  3611. self.app.inform.emit(
  3612. _(
  3613. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3614. ))
  3615. try:
  3616. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3617. except ValueError:
  3618. # try to convert comma to decimal point. if it's still not working error message and return
  3619. try:
  3620. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3621. except ValueError:
  3622. self.app.inform.emit(
  3623. _(
  3624. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3625. 'or self.options["feedrate_probe"]'
  3626. ))
  3627. for tooluid_key in self.sel_tools:
  3628. tool_cnt += 1
  3629. app_obj.progress.emit(20)
  3630. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3631. if diadict_key == 'tooldia':
  3632. tooldia_val = float('%.4f' % float(diadict_value))
  3633. dia_cnc_dict.update({
  3634. diadict_key: tooldia_val
  3635. })
  3636. if diadict_key == 'offset':
  3637. o_val = diadict_value.lower()
  3638. dia_cnc_dict.update({
  3639. diadict_key: o_val
  3640. })
  3641. if diadict_key == 'type':
  3642. t_val = diadict_value
  3643. dia_cnc_dict.update({
  3644. diadict_key: t_val
  3645. })
  3646. if diadict_key == 'tool_type':
  3647. tt_val = diadict_value
  3648. dia_cnc_dict.update({
  3649. diadict_key: tt_val
  3650. })
  3651. if diadict_key == 'data':
  3652. for data_key, data_value in diadict_value.items():
  3653. if data_key == "multidepth":
  3654. multidepth = data_value
  3655. if data_key == "depthperpass":
  3656. depthpercut = data_value
  3657. if data_key == "extracut":
  3658. extracut = data_value
  3659. if data_key == "startz":
  3660. startz = data_value
  3661. if data_key == "endz":
  3662. endz = data_value
  3663. if data_key == "toolchangez":
  3664. toolchangez = data_value
  3665. if data_key == "toolchangexy":
  3666. toolchangexy = data_value
  3667. if data_key == "toolchange":
  3668. toolchange = data_value
  3669. if data_key == "cutz":
  3670. z_cut = data_value
  3671. if data_key == "travelz":
  3672. z_move = data_value
  3673. if data_key == "feedrate":
  3674. feedrate = data_value
  3675. if data_key == "feedrate_z":
  3676. feedrate_z = data_value
  3677. if data_key == "feedrate_rapid":
  3678. feedrate_rapid = data_value
  3679. if data_key == "ppname_g":
  3680. pp_geometry_name = data_value
  3681. if data_key == "spindlespeed":
  3682. spindlespeed = data_value
  3683. if data_key == "dwell":
  3684. dwell = data_value
  3685. if data_key == "dwelltime":
  3686. dwelltime = data_value
  3687. datadict = deepcopy(diadict_value)
  3688. dia_cnc_dict.update({
  3689. diadict_key: datadict
  3690. })
  3691. if dia_cnc_dict['offset'] == 'in':
  3692. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3693. offset_str = 'inside'
  3694. elif dia_cnc_dict['offset'].lower() == 'out':
  3695. tool_offset = dia_cnc_dict['tooldia'] / 2
  3696. offset_str = 'outside'
  3697. elif dia_cnc_dict['offset'].lower() == 'path':
  3698. offset_str = 'onpath'
  3699. tool_offset = 0.0
  3700. else:
  3701. offset_str = 'custom'
  3702. try:
  3703. offset_value = float(self.ui.tool_offset_entry.get_value())
  3704. except ValueError:
  3705. # try to convert comma to decimal point. if it's still not working error message and return
  3706. try:
  3707. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  3708. except ValueError:
  3709. self.app.inform.emit(_(
  3710. "[ERROR_NOTCL] Wrong value format entered, "
  3711. "use a number."
  3712. ))
  3713. return
  3714. if offset_value:
  3715. tool_offset = float(offset_value)
  3716. else:
  3717. self.app.inform.emit(
  3718. _(
  3719. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3720. "Add a Tool Offset or change the Offset Type."
  3721. )
  3722. )
  3723. return
  3724. dia_cnc_dict.update({
  3725. 'offset_value': tool_offset
  3726. })
  3727. spindledir = self.app.defaults['geometry_spindledir']
  3728. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3729. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3730. # Propagate options
  3731. job_obj.options["tooldia"] = tooldia_val
  3732. job_obj.options['type'] = 'Geometry'
  3733. job_obj.options['tool_dia'] = tooldia_val
  3734. job_obj.options['xmin'] = xmin
  3735. job_obj.options['ymin'] = ymin
  3736. job_obj.options['xmax'] = xmax
  3737. job_obj.options['ymax'] = ymax
  3738. app_obj.progress.emit(40)
  3739. tol = float(self.app.defaults['global_tolerance'])
  3740. res = job_obj.generate_from_geometry_2(
  3741. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  3742. z_cut=z_cut, z_move=z_move,
  3743. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3744. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  3745. multidepth=multidepth, depthpercut=depthpercut,
  3746. extracut=extracut, startz=startz, endz=endz,
  3747. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3748. pp_geometry_name=pp_geometry_name,
  3749. tool_no=tool_cnt)
  3750. if res == 'fail':
  3751. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3752. return 'fail'
  3753. else:
  3754. dia_cnc_dict['gcode'] = res
  3755. app_obj.progress.emit(50)
  3756. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3757. # object is the source of gcode
  3758. job_obj.toolchange_xy_type = "geometry"
  3759. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3760. # TODO this serve for bounding box creation only; should be optimized
  3761. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3762. app_obj.progress.emit(80)
  3763. job_obj.cnc_tools.update({
  3764. tooluid_key: deepcopy(dia_cnc_dict)
  3765. })
  3766. dia_cnc_dict.clear()
  3767. # Object initialization function for app.new_object()
  3768. # RUNNING ON SEPARATE THREAD!
  3769. def job_init_multi_geometry(job_obj, app_obj):
  3770. log.debug("Creating a CNCJob out of a multi-geometry")
  3771. assert isinstance(job_obj, FlatCAMCNCjob), \
  3772. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3773. # count the tools
  3774. tool_cnt = 0
  3775. dia_cnc_dict = {}
  3776. current_uid = int(1)
  3777. # this turn on the FlatCAMCNCJob plot for multiple tools
  3778. job_obj.multitool = True
  3779. job_obj.multigeo = True
  3780. job_obj.cnc_tools.clear()
  3781. job_obj.options['xmin'] = xmin
  3782. job_obj.options['ymin'] = ymin
  3783. job_obj.options['xmax'] = xmax
  3784. job_obj.options['ymax'] = ymax
  3785. try:
  3786. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3787. except ValueError:
  3788. # try to convert comma to decimal point. if it's still not working error message and return
  3789. try:
  3790. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3791. except ValueError:
  3792. self.app.inform.emit(
  3793. _(
  3794. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3795. ))
  3796. try:
  3797. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3798. except ValueError:
  3799. # try to convert comma to decimal point. if it's still not working error message and return
  3800. try:
  3801. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3802. except ValueError:
  3803. self.app.inform.emit(
  3804. _(
  3805. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3806. 'or self.options["feedrate_probe"]'
  3807. ))
  3808. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  3809. if not self.solid_geometry:
  3810. a = 0
  3811. for tooluid_key in self.tools:
  3812. if self.tools[tooluid_key]['solid_geometry'] is None:
  3813. a += 1
  3814. if a == len(self.tools):
  3815. self.app.inform.emit(_(
  3816. '[ERROR_NOTCL] Cancelled. Empty file, it has no geometry...'
  3817. ))
  3818. return 'fail'
  3819. for tooluid_key in self.sel_tools:
  3820. tool_cnt += 1
  3821. app_obj.progress.emit(20)
  3822. # find the tool_dia associated with the tooluid_key
  3823. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3824. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3825. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3826. for k, v in self.tools.items():
  3827. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3828. current_uid = int(k)
  3829. break
  3830. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3831. if diadict_key == 'tooldia':
  3832. tooldia_val = float('%.4f' % float(diadict_value))
  3833. dia_cnc_dict.update({
  3834. diadict_key: tooldia_val
  3835. })
  3836. if diadict_key == 'offset':
  3837. o_val = diadict_value.lower()
  3838. dia_cnc_dict.update({
  3839. diadict_key: o_val
  3840. })
  3841. if diadict_key == 'type':
  3842. t_val = diadict_value
  3843. dia_cnc_dict.update({
  3844. diadict_key: t_val
  3845. })
  3846. if diadict_key == 'tool_type':
  3847. tt_val = diadict_value
  3848. dia_cnc_dict.update({
  3849. diadict_key: tt_val
  3850. })
  3851. if diadict_key == 'data':
  3852. for data_key, data_value in diadict_value.items():
  3853. if data_key == "multidepth":
  3854. multidepth = data_value
  3855. if data_key == "depthperpass":
  3856. depthpercut = data_value
  3857. if data_key == "extracut":
  3858. extracut = data_value
  3859. if data_key == "startz":
  3860. startz = data_value
  3861. if data_key == "endz":
  3862. endz = data_value
  3863. if data_key == "toolchangez":
  3864. toolchangez = data_value
  3865. if data_key == "toolchangexy":
  3866. toolchangexy = data_value
  3867. if data_key == "toolchange":
  3868. toolchange = data_value
  3869. if data_key == "cutz":
  3870. z_cut = data_value
  3871. if data_key == "travelz":
  3872. z_move = data_value
  3873. if data_key == "feedrate":
  3874. feedrate = data_value
  3875. if data_key == "feedrate_z":
  3876. feedrate_z = data_value
  3877. if data_key == "feedrate_rapid":
  3878. feedrate_rapid = data_value
  3879. if data_key == "ppname_g":
  3880. pp_geometry_name = data_value
  3881. if data_key == "spindlespeed":
  3882. spindlespeed = data_value
  3883. if data_key == "dwell":
  3884. dwell = data_value
  3885. if data_key == "dwelltime":
  3886. dwelltime = data_value
  3887. datadict = deepcopy(diadict_value)
  3888. dia_cnc_dict.update({
  3889. diadict_key: datadict
  3890. })
  3891. if dia_cnc_dict['offset'] == 'in':
  3892. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3893. offset_str = 'inside'
  3894. elif dia_cnc_dict['offset'].lower() == 'out':
  3895. tool_offset = dia_cnc_dict['tooldia'] / 2
  3896. offset_str = 'outside'
  3897. elif dia_cnc_dict['offset'].lower() == 'path':
  3898. offset_str = 'onpath'
  3899. tool_offset = 0.0
  3900. else:
  3901. offset_str = 'custom'
  3902. try:
  3903. offset_value = float(self.ui.tool_offset_entry.get_value())
  3904. except ValueError:
  3905. # try to convert comma to decimal point. if it's still not working error message and return
  3906. try:
  3907. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  3908. except ValueError:
  3909. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  3910. "use a number."))
  3911. return
  3912. if offset_value:
  3913. tool_offset = float(offset_value)
  3914. else:
  3915. self.app.inform.emit(_(
  3916. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3917. "Add a Tool Offset or change the Offset Type."))
  3918. return
  3919. dia_cnc_dict.update({
  3920. 'offset_value': tool_offset
  3921. })
  3922. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3923. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3924. # Propagate options
  3925. job_obj.options["tooldia"] = tooldia_val
  3926. job_obj.options['type'] = 'Geometry'
  3927. job_obj.options['tool_dia'] = tooldia_val
  3928. app_obj.progress.emit(40)
  3929. spindledir = self.app.defaults['geometry_spindledir']
  3930. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3931. tol = float(self.app.defaults['global_tolerance'])
  3932. res = job_obj.generate_from_multitool_geometry(
  3933. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3934. tolerance=tol, z_cut=z_cut, z_move=z_move,
  3935. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3936. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  3937. multidepth=multidepth, depthpercut=depthpercut,
  3938. extracut=extracut, startz=startz, endz=endz,
  3939. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3940. pp_geometry_name=pp_geometry_name,
  3941. tool_no=tool_cnt)
  3942. if res == 'fail':
  3943. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3944. return 'fail'
  3945. else:
  3946. dia_cnc_dict['gcode'] = res
  3947. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3948. # TODO this serve for bounding box creation only; should be optimized
  3949. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3950. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3951. # object is the source of gcode
  3952. job_obj.toolchange_xy_type = "geometry"
  3953. app_obj.progress.emit(80)
  3954. job_obj.cnc_tools.update({
  3955. tooluid_key: deepcopy(dia_cnc_dict)
  3956. })
  3957. dia_cnc_dict.clear()
  3958. if use_thread:
  3959. # To be run in separate thread
  3960. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3961. # separate solid_geometry in the self.tools dictionary
  3962. def job_thread(app_obj):
  3963. if self.solid_geometry:
  3964. with self.app.proc_container.new(_("Generating CNC Code")):
  3965. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3966. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3967. app_obj.progress.emit(100)
  3968. else:
  3969. with self.app.proc_container.new(_("Generating CNC Code")):
  3970. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3971. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3972. app_obj.progress.emit(100)
  3973. # Create a promise with the name
  3974. self.app.collection.promise(outname)
  3975. # Send to worker
  3976. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3977. else:
  3978. if self.solid_geometry:
  3979. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3980. else:
  3981. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3982. def generatecncjob(self, outname=None,
  3983. tooldia=None, offset=None,
  3984. z_cut=None, z_move=None,
  3985. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3986. spindlespeed=None, dwell=None, dwelltime=None,
  3987. multidepth=None, depthperpass=None,
  3988. toolchange=None, toolchangez=None, toolchangexy=None,
  3989. extracut=None, startz=None, endz=None,
  3990. ppname_g=None,
  3991. segx=None,
  3992. segy=None,
  3993. use_thread=True):
  3994. """
  3995. Only used for TCL Command.
  3996. Creates a CNCJob out of this Geometry object. The actual
  3997. work is done by the target FlatCAMCNCjob object's
  3998. `generate_from_geometry_2()` method.
  3999. :param z_cut: Cut depth (negative)
  4000. :param z_move: Hight of the tool when travelling (not cutting)
  4001. :param feedrate: Feed rate while cutting on X - Y plane
  4002. :param feedrate_z: Feed rate while cutting on Z plane
  4003. :param feedrate_rapid: Feed rate while moving with rapids
  4004. :param tooldia: Tool diameter
  4005. :param outname: Name of the new object
  4006. :param spindlespeed: Spindle speed (RPM)
  4007. :param ppname_g Name of the postprocessor
  4008. :return: None
  4009. """
  4010. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  4011. outname = outname if outname is not None else self.options["name"]
  4012. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  4013. z_move = z_move if z_move is not None else float(self.options["travelz"])
  4014. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  4015. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  4016. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  4017. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  4018. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  4019. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4020. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4021. extracut = extracut if extracut is not None else float(self.options["extracut"])
  4022. startz = startz if startz is not None else self.options["startz"]
  4023. endz = endz if endz is not None else float(self.options["endz"])
  4024. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4025. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4026. toolchange = toolchange if toolchange else self.options["toolchange"]
  4027. offset = offset if offset else 0.0
  4028. # int or None.
  4029. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  4030. dwell = dwell if dwell else self.options["dwell"]
  4031. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  4032. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  4033. # Object initialization function for app.new_object()
  4034. # RUNNING ON SEPARATE THREAD!
  4035. def job_init(job_obj, app_obj):
  4036. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4037. # Propagate options
  4038. job_obj.options["tooldia"] = tooldia
  4039. app_obj.progress.emit(20)
  4040. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4041. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4042. app_obj.progress.emit(40)
  4043. job_obj.options['type'] = 'Geometry'
  4044. job_obj.options['tool_dia'] = tooldia
  4045. job_obj.segx = segx
  4046. job_obj.segy = segy
  4047. try:
  4048. job_obj.z_pdepth = float(self.options["z_pdepth"])
  4049. except ValueError:
  4050. # try to convert comma to decimal point. if it's still not working error message and return
  4051. try:
  4052. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  4053. except ValueError:
  4054. self.app.inform.emit(
  4055. _(
  4056. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  4057. ))
  4058. try:
  4059. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4060. except ValueError:
  4061. # try to convert comma to decimal point. if it's still not working error message and return
  4062. try:
  4063. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  4064. except ValueError:
  4065. self.app.inform.emit(
  4066. _(
  4067. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  4068. 'or self.options["feedrate_probe"]'
  4069. ))
  4070. job_obj.options['xmin'] = self.options['xmin']
  4071. job_obj.options['ymin'] = self.options['ymin']
  4072. job_obj.options['xmax'] = self.options['xmax']
  4073. job_obj.options['ymax'] = self.options['ymax']
  4074. tol = float(self.app.defaults['global_tolerance'])
  4075. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=tol,
  4076. z_cut=z_cut, z_move=z_move,
  4077. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4078. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4079. multidepth=multidepth, depthpercut=depthperpass,
  4080. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4081. extracut=extracut, startz=startz, endz=endz,
  4082. pp_geometry_name=ppname_g
  4083. )
  4084. app_obj.progress.emit(50)
  4085. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4086. # source of gcode
  4087. job_obj.toolchange_xy_type = "geometry"
  4088. job_obj.gcode_parse()
  4089. app_obj.progress.emit(80)
  4090. if use_thread:
  4091. # To be run in separate thread
  4092. def job_thread(app_obj):
  4093. with self.app.proc_container.new(_("Generating CNC Code")):
  4094. app_obj.new_object("cncjob", outname, job_init)
  4095. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  4096. app_obj.progress.emit(100)
  4097. # Create a promise with the name
  4098. self.app.collection.promise(outname)
  4099. # Send to worker
  4100. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4101. else:
  4102. self.app.new_object("cncjob", outname, job_init)
  4103. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4104. # if self.muted_ui:
  4105. # return
  4106. # self.read_form_item('plot')
  4107. def scale(self, xfactor, yfactor=None, point=None):
  4108. """
  4109. Scales all geometry by a given factor.
  4110. :param xfactor: Factor by which to scale the object's geometry/
  4111. :type xfactor: float
  4112. :param yfactor: Factor by which to scale the object's geometry/
  4113. :type yfactor: float
  4114. :return: None
  4115. :rtype: None
  4116. """
  4117. try:
  4118. xfactor = float(xfactor)
  4119. except Exception as e:
  4120. self.app.inform.emit(_(
  4121. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  4122. return
  4123. if yfactor is None:
  4124. yfactor = xfactor
  4125. else:
  4126. try:
  4127. yfactor = float(yfactor)
  4128. except Exception as e:
  4129. self.app.inform.emit(_("[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  4130. return
  4131. if point is None:
  4132. px = 0
  4133. py = 0
  4134. else:
  4135. px, py = point
  4136. # if type(self.solid_geometry) == list:
  4137. # geo_list = self.flatten(self.solid_geometry)
  4138. # self.solid_geometry = []
  4139. # # for g in geo_list:
  4140. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  4141. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  4142. # for g in geo_list]
  4143. # else:
  4144. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  4145. # origin=(px, py))
  4146. # self.app.inform.emit("[success] Geometry Scale done.")
  4147. def scale_recursion(geom):
  4148. if type(geom) is list:
  4149. geoms = list()
  4150. for local_geom in geom:
  4151. geoms.append(scale_recursion(local_geom))
  4152. return geoms
  4153. else:
  4154. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4155. if self.multigeo is True:
  4156. for tool in self.tools:
  4157. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4158. else:
  4159. self.solid_geometry = scale_recursion(self.solid_geometry)
  4160. self.app.inform.emit(_(
  4161. "[success] Geometry Scale done."
  4162. ))
  4163. def offset(self, vect):
  4164. """
  4165. Offsets all geometry by a given vector/
  4166. :param vect: (x, y) vector by which to offset the object's geometry.
  4167. :type vect: tuple
  4168. :return: None
  4169. :rtype: None
  4170. """
  4171. try:
  4172. dx, dy = vect
  4173. except TypeError:
  4174. self.app.inform.emit(_(
  4175. "[ERROR_NOTCL] An (x,y) pair of values are needed. "
  4176. "Probable you entered only one value in the Offset field."
  4177. ))
  4178. return
  4179. def translate_recursion(geom):
  4180. if type(geom) is list:
  4181. geoms = list()
  4182. for local_geom in geom:
  4183. geoms.append(translate_recursion(local_geom))
  4184. return geoms
  4185. else:
  4186. return affinity.translate(geom, xoff=dx, yoff=dy)
  4187. if self.multigeo is True:
  4188. for tool in self.tools:
  4189. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  4190. else:
  4191. self.solid_geometry = translate_recursion(self.solid_geometry)
  4192. self.app.inform.emit(_("[success] Geometry Offset done."))
  4193. def convert_units(self, units):
  4194. self.ui_disconnect()
  4195. factor = Geometry.convert_units(self, units)
  4196. self.options['cutz'] = float(self.options['cutz']) * factor
  4197. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  4198. self.options['travelz'] = float(self.options['travelz']) * factor
  4199. self.options['feedrate'] = float(self.options['feedrate']) * factor
  4200. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  4201. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  4202. self.options['endz'] = float(self.options['endz']) * factor
  4203. # self.options['cnctooldia'] *= factor
  4204. # self.options['painttooldia'] *= factor
  4205. # self.options['paintmargin'] *= factor
  4206. # self.options['paintoverlap'] *= factor
  4207. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  4208. if self.app.defaults["geometry_toolchangexy"] == '':
  4209. self.options['toolchangexy'] = "0.0, 0.0"
  4210. else:
  4211. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  4212. if len(coords_xy) < 2:
  4213. self.app.inform.emit(_(
  4214. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4215. "in the format (x, y) \nbut now there is only one value, not two. "
  4216. ))
  4217. return 'fail'
  4218. coords_xy[0] *= factor
  4219. coords_xy[1] *= factor
  4220. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4221. if self.options['startz'] is not None:
  4222. self.options['startz'] = float(self.options['startz']) * factor
  4223. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4224. 'endz', 'toolchangez']
  4225. if isinstance(self, FlatCAMGeometry):
  4226. temp_tools_dict = {}
  4227. tool_dia_copy = {}
  4228. data_copy = {}
  4229. for tooluid_key, tooluid_value in self.tools.items():
  4230. for dia_key, dia_value in tooluid_value.items():
  4231. if dia_key == 'tooldia':
  4232. dia_value *= factor
  4233. dia_value = float('%.4f' % dia_value)
  4234. tool_dia_copy[dia_key] = dia_value
  4235. if dia_key == 'offset':
  4236. tool_dia_copy[dia_key] = dia_value
  4237. if dia_key == 'offset_value':
  4238. dia_value *= factor
  4239. tool_dia_copy[dia_key] = dia_value
  4240. # convert the value in the Custom Tool Offset entry in UI
  4241. custom_offset = None
  4242. try:
  4243. custom_offset = float(self.ui.tool_offset_entry.get_value())
  4244. except ValueError:
  4245. # try to convert comma to decimal point. if it's still not working error message and return
  4246. try:
  4247. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4248. except ValueError:
  4249. self.app.inform.emit(_(
  4250. "[ERROR_NOTCL] Wrong value format entered, "
  4251. "use a number."
  4252. ))
  4253. return
  4254. except TypeError:
  4255. pass
  4256. if custom_offset:
  4257. custom_offset *= factor
  4258. self.ui.tool_offset_entry.set_value(custom_offset)
  4259. if dia_key == 'type':
  4260. tool_dia_copy[dia_key] = dia_value
  4261. if dia_key == 'tool_type':
  4262. tool_dia_copy[dia_key] = dia_value
  4263. if dia_key == 'data':
  4264. for data_key, data_value in dia_value.items():
  4265. # convert the form fields that are convertible
  4266. for param in param_list:
  4267. if data_key == param and data_value is not None:
  4268. data_copy[data_key] = data_value * factor
  4269. # copy the other dict entries that are not convertible
  4270. if data_key not in param_list:
  4271. data_copy[data_key] = data_value
  4272. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4273. data_copy.clear()
  4274. temp_tools_dict.update({
  4275. tooluid_key: deepcopy(tool_dia_copy)
  4276. })
  4277. tool_dia_copy.clear()
  4278. self.tools.clear()
  4279. self.tools = deepcopy(temp_tools_dict)
  4280. # if there is a value in the new tool field then convert that one too
  4281. tooldia = self.ui.addtool_entry.get_value()
  4282. if tooldia:
  4283. tooldia *= factor
  4284. # limit the decimals to 2 for METRIC and 3 for INCH
  4285. if units.lower() == 'in':
  4286. tooldia = float('%.4f' % tooldia)
  4287. else:
  4288. tooldia = float('%.2f' % tooldia)
  4289. self.ui.addtool_entry.set_value(tooldia)
  4290. return factor
  4291. def plot_element(self, element, color='red', visible=None):
  4292. visible = visible if visible else self.options['plot']
  4293. try:
  4294. for sub_el in element:
  4295. self.plot_element(sub_el)
  4296. except TypeError: # Element is not iterable...
  4297. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  4298. def plot(self, visible=None, kind=None):
  4299. """
  4300. Plot the object.
  4301. :param visible: Controls if the added shape is visible of not
  4302. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  4303. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  4304. :return:
  4305. """
  4306. # Does all the required setup and returns False
  4307. # if the 'ptint' option is set to False.
  4308. if not FlatCAMObj.plot(self):
  4309. return
  4310. try:
  4311. # plot solid geometries found as members of self.tools attribute dict
  4312. # for MultiGeo
  4313. if self.multigeo is True: # geo multi tool usage
  4314. for tooluid_key in self.tools:
  4315. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4316. self.plot_element(solid_geometry, visible=visible)
  4317. # plot solid geometry that may be an direct attribute of the geometry object
  4318. # for SingleGeo
  4319. if self.solid_geometry:
  4320. self.plot_element(self.solid_geometry, visible=visible)
  4321. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  4322. self.shapes.redraw()
  4323. except (ObjectDeleted, AttributeError):
  4324. self.shapes.clear(update=True)
  4325. def on_plot_cb_click(self, *args):
  4326. if self.muted_ui:
  4327. return
  4328. self.plot()
  4329. self.read_form_item('plot')
  4330. self.ui_disconnect()
  4331. cb_flag = self.ui.plot_cb.isChecked()
  4332. for row in range(self.ui.geo_tools_table.rowCount()):
  4333. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  4334. if cb_flag:
  4335. table_cb.setChecked(True)
  4336. else:
  4337. table_cb.setChecked(False)
  4338. self.ui_connect()
  4339. def on_plot_cb_click_table(self):
  4340. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4341. self.ui_disconnect()
  4342. # cw = self.sender()
  4343. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4344. # cw_row = cw_index.row()
  4345. check_row = 0
  4346. self.shapes.clear(update=True)
  4347. for tooluid_key in self.tools:
  4348. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4349. # find the geo_tool_table row associated with the tooluid_key
  4350. for row in range(self.ui.geo_tools_table.rowCount()):
  4351. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4352. if tooluid_item == int(tooluid_key):
  4353. check_row = row
  4354. break
  4355. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  4356. self.plot_element(element=solid_geometry, visible=True)
  4357. self.shapes.redraw()
  4358. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4359. # if all the row plot's are enabled also enable the general plot checkbox
  4360. cb_cnt = 0
  4361. total_row = self.ui.geo_tools_table.rowCount()
  4362. for row in range(total_row):
  4363. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  4364. cb_cnt += 1
  4365. else:
  4366. cb_cnt -= 1
  4367. if cb_cnt < total_row:
  4368. self.ui.plot_cb.setChecked(False)
  4369. else:
  4370. self.ui.plot_cb.setChecked(True)
  4371. self.ui_connect()
  4372. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4373. """
  4374. Represents G-Code.
  4375. """
  4376. optionChanged = QtCore.pyqtSignal(str)
  4377. ui_type = CNCObjectUI
  4378. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4379. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4380. spindlespeed=None):
  4381. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4382. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4383. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4384. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4385. FlatCAMObj.__init__(self, name)
  4386. self.kind = "cncjob"
  4387. self.options.update({
  4388. "plot": True,
  4389. "tooldia": 0.03937, # 0.4mm in inches
  4390. "append": "",
  4391. "prepend": "",
  4392. "dwell": False,
  4393. "dwelltime": 1,
  4394. "type": 'Geometry',
  4395. "toolchange_macro": '',
  4396. "toolchange_macro_enable": False
  4397. })
  4398. '''
  4399. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4400. diameter of the tools and the value is another dict that will hold the data under the following form:
  4401. {tooldia: {
  4402. 'tooluid': 1,
  4403. 'offset': 'Path',
  4404. 'type_item': 'Rough',
  4405. 'tool_type': 'C1',
  4406. 'data': {} # a dict to hold the parameters
  4407. 'gcode': "" # a string with the actual GCODE
  4408. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  4409. (cut or move)
  4410. 'solid_geometry': []
  4411. },
  4412. ...
  4413. }
  4414. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  4415. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4416. '''
  4417. self.cnc_tools = {}
  4418. '''
  4419. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4420. diameter of the tools and the value is another dict that will hold the data under the following form:
  4421. {tooldia: {
  4422. 'tool': int,
  4423. 'nr_drills': int,
  4424. 'nr_slots': int,
  4425. 'offset': float,
  4426. 'data': {} # a dict to hold the parameters
  4427. 'gcode': "" # a string with the actual GCODE
  4428. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4429. 'solid_geometry': []
  4430. },
  4431. ...
  4432. }
  4433. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  4434. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  4435. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4436. '''
  4437. self.exc_cnc_tools = {}
  4438. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  4439. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  4440. self.special_group = None
  4441. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  4442. # (like the one in the TCL Command), False
  4443. self.multitool = False
  4444. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  4445. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  4446. self.g_x_re = re.compile(gcodex_re_string)
  4447. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  4448. self.g_y_re = re.compile(gcodey_re_string)
  4449. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  4450. self.g_z_re = re.compile(gcodez_re_string)
  4451. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  4452. self.g_f_re = re.compile(gcodef_re_string)
  4453. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  4454. self.g_t_re = re.compile(gcodet_re_string)
  4455. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  4456. self.g_nr_re = re.compile(gcodenr_re_string)
  4457. # Attributes to be included in serialization
  4458. # Always append to it because it carries contents
  4459. # from predecessors.
  4460. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  4461. self.annotation = self.app.plotcanvas.new_text_group()
  4462. def build_ui(self):
  4463. self.ui_disconnect()
  4464. FlatCAMObj.build_ui(self)
  4465. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  4466. if self.cnc_tools:
  4467. self.ui.cnc_tools_table.show()
  4468. else:
  4469. self.ui.cnc_tools_table.hide()
  4470. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4471. offset = 0
  4472. tool_idx = 0
  4473. n = len(self.cnc_tools)
  4474. self.ui.cnc_tools_table.setRowCount(n)
  4475. for dia_key, dia_value in self.cnc_tools.items():
  4476. tool_idx += 1
  4477. row_no = tool_idx - 1
  4478. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  4479. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4480. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  4481. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  4482. # There are no tool bits in MM with more than 2 decimals diameter.
  4483. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  4484. if self.units == 'MM':
  4485. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  4486. else:
  4487. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  4488. offset_txt = list(str(dia_value['offset']))
  4489. offset_txt[0] = offset_txt[0].upper()
  4490. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  4491. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  4492. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  4493. id.setFlags(QtCore.Qt.ItemIsEnabled)
  4494. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4495. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4496. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4497. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4498. # hack so the checkbox stay centered in the table cell
  4499. # used this:
  4500. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  4501. # plot_item = QtWidgets.QWidget()
  4502. # checkbox = FCCheckBox()
  4503. # checkbox.setCheckState(QtCore.Qt.Checked)
  4504. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  4505. # qhboxlayout.addWidget(checkbox)
  4506. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  4507. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  4508. plot_item = FCCheckBox()
  4509. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  4510. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  4511. if self.ui.plot_cb.isChecked():
  4512. plot_item.setChecked(True)
  4513. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  4514. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  4515. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  4516. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  4517. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  4518. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  4519. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  4520. # make the diameter column editable
  4521. # for row in range(tool_idx):
  4522. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  4523. # QtCore.Qt.ItemIsEnabled)
  4524. for row in range(tool_idx):
  4525. self.ui.cnc_tools_table.item(row, 0).setFlags(
  4526. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  4527. self.ui.cnc_tools_table.resizeColumnsToContents()
  4528. self.ui.cnc_tools_table.resizeRowsToContents()
  4529. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  4530. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4531. vertical_header.hide()
  4532. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4533. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  4534. horizontal_header.setMinimumSectionSize(10)
  4535. horizontal_header.setDefaultSectionSize(70)
  4536. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  4537. horizontal_header.resizeSection(0, 20)
  4538. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4539. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4540. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  4541. horizontal_header.resizeSection(4, 40)
  4542. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  4543. horizontal_header.resizeSection(4, 17)
  4544. # horizontal_header.setStretchLastSection(True)
  4545. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4546. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4547. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4548. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4549. # self.ui.geo_tools_table.setSortingEnabled(True)
  4550. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4551. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4552. self.ui_connect()
  4553. def set_ui(self, ui):
  4554. FlatCAMObj.set_ui(self, ui)
  4555. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4556. assert isinstance(self.ui, CNCObjectUI), \
  4557. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4558. # this signal has to be connected to it's slot before the defaults are populated
  4559. # the decision done in the slot has to override the default value set bellow
  4560. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  4561. self.form_fields.update({
  4562. "plot": self.ui.plot_cb,
  4563. # "tooldia": self.ui.tooldia_entry,
  4564. "append": self.ui.append_text,
  4565. "prepend": self.ui.prepend_text,
  4566. "toolchange_macro": self.ui.toolchange_text,
  4567. "toolchange_macro_enable": self.ui.toolchange_cb
  4568. })
  4569. # Fill form fields only on object create
  4570. self.to_form()
  4571. # this means that the object that created this CNCJob was an Excellon
  4572. try:
  4573. if self.travel_distance:
  4574. self.ui.t_distance_label.show()
  4575. self.ui.t_distance_entry.setVisible(True)
  4576. self.ui.t_distance_entry.setDisabled(True)
  4577. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4578. self.ui.units_label.setText(str(self.units).lower())
  4579. self.ui.units_label.setDisabled(True)
  4580. except AttributeError:
  4581. pass
  4582. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4583. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4584. try:
  4585. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  4586. except TypeError:
  4587. pass
  4588. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  4589. # set if to display text annotations
  4590. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  4591. # Show/Hide Advanced Options
  4592. if self.app.defaults["global_app_level"] == 'b':
  4593. self.ui.level.setText(_(
  4594. '<span style="color:green;"><b>Basic</b></span>'
  4595. ))
  4596. self.ui.cnc_frame.hide()
  4597. else:
  4598. self.ui.level.setText(_(
  4599. '<span style="color:red;"><b>Advanced</b></span>'
  4600. ))
  4601. self.ui.cnc_frame.show()
  4602. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4603. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4604. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  4605. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  4606. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4607. def on_cnc_custom_parameters(self, signal_text):
  4608. if signal_text == 'Parameters':
  4609. return
  4610. else:
  4611. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4612. def ui_connect(self):
  4613. for row in range(self.ui.cnc_tools_table.rowCount()):
  4614. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4615. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4616. def ui_disconnect(self):
  4617. for row in range(self.ui.cnc_tools_table.rowCount()):
  4618. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4619. try:
  4620. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4621. except TypeError:
  4622. pass
  4623. def on_updateplot_button_click(self, *args):
  4624. """
  4625. Callback for the "Updata Plot" button. Reads the form for updates
  4626. and plots the object.
  4627. """
  4628. self.read_form()
  4629. self.plot()
  4630. def on_plot_kind_change(self):
  4631. kind = self.ui.cncplot_method_combo.get_value()
  4632. self.plot(kind=kind)
  4633. def on_exportgcode_button_click(self, *args):
  4634. self.app.report_usage("cncjob_on_exportgcode_button")
  4635. self.read_form()
  4636. name = self.app.collection.get_active().options['name']
  4637. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4638. _filter_ = "RML1 Files (*.rol);;" \
  4639. "All Files (*.*)"
  4640. elif 'hpgl' in self.pp_geometry_name:
  4641. _filter_ = "HPGL Files (*.plt);;" \
  4642. "All Files (*.*)"
  4643. else:
  4644. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4645. "G-Code Files (*.g-code);;All Files (*.*)"
  4646. try:
  4647. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4648. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4649. caption=_("Export Machine Code ..."),
  4650. directory=dir_file_to_save,
  4651. filter=_filter_
  4652. )
  4653. except TypeError:
  4654. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  4655. filename = str(filename)
  4656. if filename == '':
  4657. self.app.inform.emit(_(
  4658. "[WARNING_NOTCL] Export Machine Code cancelled ..."))
  4659. return
  4660. preamble = str(self.ui.prepend_text.get_value())
  4661. postamble = str(self.ui.append_text.get_value())
  4662. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4663. if gc == 'fail':
  4664. return
  4665. if self.app.defaults["global_open_style"] is False:
  4666. self.app.file_opened.emit("gcode", filename)
  4667. self.app.file_saved.emit("gcode", filename)
  4668. self.app.inform.emit(_("[success] Machine Code file saved to: %s") % filename)
  4669. def on_edit_code_click(self, *args):
  4670. preamble = str(self.ui.prepend_text.get_value())
  4671. postamble = str(self.ui.append_text.get_value())
  4672. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4673. if gc == 'fail':
  4674. return
  4675. else:
  4676. self.app.gcode_edited = gc
  4677. self.app.init_code_editor(name=_("Code Editor"))
  4678. self.app.ui.buttonOpen.clicked.connect(self.app.handleOpen)
  4679. self.app.ui.buttonSave.clicked.connect(self.app.handleSaveGCode)
  4680. # then append the text from GCode to the text editor
  4681. try:
  4682. for line in self.app.gcode_edited:
  4683. proc_line = str(line).strip('\n')
  4684. self.app.ui.code_editor.append(proc_line)
  4685. except Exception as e:
  4686. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  4687. self.app.inform.emit(_('[ERROR]FlatCAMCNNJob.on_edit_code_click() -->%s') % str(e))
  4688. return
  4689. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4690. self.app.handleTextChanged()
  4691. self.app.ui.show()
  4692. def gcode_header(self):
  4693. log.debug("FlatCAMCNCJob.gcode_header()")
  4694. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4695. marlin = False
  4696. hpgl = False
  4697. probe_pp = False
  4698. try:
  4699. for key in self.cnc_tools:
  4700. ppg = self.cnc_tools[key]['data']['ppname_g']
  4701. if ppg == 'marlin' or ppg == 'Repetier':
  4702. marlin = True
  4703. break
  4704. if ppg == 'hpgl':
  4705. hpgl = True
  4706. break
  4707. if "toolchange_probe" in ppg.lower():
  4708. probe_pp = True
  4709. break
  4710. except Exception as e:
  4711. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4712. try:
  4713. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  4714. marlin = True
  4715. except Exception as e:
  4716. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4717. try:
  4718. if "toolchange_probe" in self.options['ppname_e'].lower():
  4719. probe_pp = True
  4720. except Exception as e:
  4721. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4722. if marlin is True:
  4723. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4724. (str(self.app.version), str(self.app.version_date)) + '\n'
  4725. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4726. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4727. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4728. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4729. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4730. gcode += ';Created on ' + time_str + '\n' + '\n'
  4731. elif hpgl is True:
  4732. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4733. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4734. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4735. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4736. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4737. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4738. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4739. gcode += 'CO "Created on ' + time_str + '";\n'
  4740. elif probe_pp is True:
  4741. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4742. (str(self.app.version), str(self.app.version_date)) + '\n'
  4743. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4744. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4745. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4746. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4747. 'Then zero the Z axis.)\n' + '\n'
  4748. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4749. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4750. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4751. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4752. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4753. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4754. else:
  4755. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4756. (str(self.app.version), str(self.app.version_date)) + '\n'
  4757. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4758. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4759. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4760. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4761. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4762. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4763. return gcode
  4764. def gcode_footer(self, end_command=None):
  4765. """
  4766. :param end_command: 'M02' or 'M30' - String
  4767. :return:
  4768. """
  4769. if end_command:
  4770. return end_command
  4771. else:
  4772. return 'M02'
  4773. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4774. gcode = ''
  4775. roland = False
  4776. hpgl = False
  4777. try:
  4778. if self.special_group:
  4779. self.app.inform.emit(_("[WARNING_NOTCL] This CNCJob object can't be processed because "
  4780. "it is a %s CNCJob object.") % str(self.special_group))
  4781. return 'fail'
  4782. except AttributeError:
  4783. pass
  4784. # detect if using Roland postprocessor
  4785. try:
  4786. for key in self.cnc_tools:
  4787. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4788. roland = True
  4789. break
  4790. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4791. hpgl = True
  4792. break
  4793. except Exception as e:
  4794. try:
  4795. for key in self.cnc_tools:
  4796. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4797. roland = True
  4798. break
  4799. except Exception as e:
  4800. pass
  4801. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4802. if roland is False and hpgl is False:
  4803. gcode = self.gcode_header()
  4804. # detect if using multi-tool and make the Gcode summation correctly for each case
  4805. if self.multitool is True:
  4806. for tooluid_key in self.cnc_tools:
  4807. for key, value in self.cnc_tools[tooluid_key].items():
  4808. if key == 'gcode':
  4809. gcode += value
  4810. break
  4811. else:
  4812. gcode += self.gcode
  4813. if roland is True:
  4814. g = preamble + gcode + postamble
  4815. elif hpgl is True:
  4816. g = self.gcode_header() + preamble + gcode + postamble
  4817. else:
  4818. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4819. g_idx = gcode.rfind('G20')
  4820. # if it did not find 'G20' then search for 'G21'
  4821. if g_idx == -1:
  4822. g_idx = gcode.rfind('G21')
  4823. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4824. if g_idx == -1:
  4825. self.app.inform.emit(_(
  4826. "[ERROR_NOTCL] G-code does not have a units code: either G20 or G21"
  4827. ))
  4828. return
  4829. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + self.gcode_footer()
  4830. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  4831. if self.ui.toolchange_cb.get_value() is True:
  4832. # match = self.re_toolchange.search(g)
  4833. if 'M6' in g:
  4834. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  4835. if m6_code is None or m6_code == '':
  4836. self.app.inform.emit(_(
  4837. "[ERROR_NOTCL] Cancelled. The Toolchange Custom code is enabled "
  4838. "but it's empty."
  4839. ))
  4840. return 'fail'
  4841. g = g.replace('M6', m6_code)
  4842. self.app.inform.emit(_(
  4843. "[success] Toolchange G-code was replaced by a custom code."
  4844. ))
  4845. # lines = StringIO(self.gcode)
  4846. lines = StringIO(g)
  4847. # Write
  4848. if filename is not None:
  4849. try:
  4850. with open(filename, 'w') as f:
  4851. for line in lines:
  4852. f.write(line)
  4853. except FileNotFoundError:
  4854. self.app.inform.emit(_(
  4855. "[WARNING_NOTCL] No such file or directory"
  4856. ))
  4857. return
  4858. elif to_file is False:
  4859. # Just for adding it to the recent files list.
  4860. if self.app.defaults["global_open_style"] is False:
  4861. self.app.file_opened.emit("cncjob", filename)
  4862. self.app.file_saved.emit("cncjob", filename)
  4863. self.app.inform.emit("[success] Saved to: " + filename)
  4864. else:
  4865. return lines
  4866. def on_toolchange_custom_clicked(self, signal):
  4867. try:
  4868. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  4869. if self.ui.toolchange_cb.get_value():
  4870. self.ui.toolchange_cb.set_value(False)
  4871. self.app.inform.emit(
  4872. _(
  4873. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: 'toolchange_custom'"
  4874. ))
  4875. except KeyError:
  4876. try:
  4877. for key in self.cnc_tools:
  4878. ppg = self.cnc_tools[key]['data']['ppname_g']
  4879. if 'toolchange_custom' not in str(ppg).lower():
  4880. print(ppg)
  4881. if self.ui.toolchange_cb.get_value():
  4882. self.ui.toolchange_cb.set_value(False)
  4883. self.app.inform.emit(
  4884. _(
  4885. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: "
  4886. "'toolchange_custom'"
  4887. ))
  4888. except KeyError:
  4889. self.app.inform.emit(
  4890. _(
  4891. "[ERROR] There is no postprocessor file."
  4892. ))
  4893. def get_gcode(self, preamble='', postamble=''):
  4894. # we need this to be able get_gcode separatelly for shell command export_gcode
  4895. return preamble + '\n' + self.gcode + "\n" + postamble
  4896. def get_svg(self):
  4897. # we need this to be able get_svg separately for shell command export_svg
  4898. pass
  4899. def on_plot_cb_click(self, *args):
  4900. if self.muted_ui:
  4901. return
  4902. kind = self.ui.cncplot_method_combo.get_value()
  4903. self.plot(kind=kind)
  4904. self.read_form_item('plot')
  4905. self.ui_disconnect()
  4906. cb_flag = self.ui.plot_cb.isChecked()
  4907. for row in range(self.ui.cnc_tools_table.rowCount()):
  4908. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4909. if cb_flag:
  4910. table_cb.setChecked(True)
  4911. else:
  4912. table_cb.setChecked(False)
  4913. self.ui_connect()
  4914. def on_plot_cb_click_table(self):
  4915. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4916. self.ui_disconnect()
  4917. # cw = self.sender()
  4918. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4919. # cw_row = cw_index.row()
  4920. kind = self.ui.cncplot_method_combo.get_value()
  4921. self.shapes.clear(update=True)
  4922. for tooluid_key in self.cnc_tools:
  4923. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4924. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4925. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4926. for r in range(self.ui.cnc_tools_table.rowCount()):
  4927. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4928. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4929. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  4930. self.shapes.redraw()
  4931. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4932. # if all the row plot's are enabled also enable the general plot checkbox
  4933. cb_cnt = 0
  4934. total_row = self.ui.cnc_tools_table.rowCount()
  4935. for row in range(total_row):
  4936. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4937. cb_cnt += 1
  4938. else:
  4939. cb_cnt -= 1
  4940. if cb_cnt < total_row:
  4941. self.ui.plot_cb.setChecked(False)
  4942. else:
  4943. self.ui.plot_cb.setChecked(True)
  4944. self.ui_connect()
  4945. def plot(self, visible=None, kind='all'):
  4946. # Does all the required setup and returns False
  4947. # if the 'ptint' option is set to False.
  4948. if not FlatCAMObj.plot(self):
  4949. return
  4950. visible = visible if visible else self.options['plot']
  4951. try:
  4952. if self.multitool is False: # single tool usage
  4953. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4954. else:
  4955. # multiple tools usage
  4956. for tooluid_key in self.cnc_tools:
  4957. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4958. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4959. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4960. self.shapes.redraw()
  4961. except (ObjectDeleted, AttributeError):
  4962. self.shapes.clear(update=True)
  4963. self.annotation.clear(update=True)
  4964. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  4965. self.app.plotcanvas.text_collection.enabled = True
  4966. else:
  4967. self.app.plotcanvas.text_collection.enabled = False
  4968. def on_annotation_change(self):
  4969. if self.ui.annotation_cb.get_value():
  4970. self.app.plotcanvas.text_collection.enabled = True
  4971. else:
  4972. self.app.plotcanvas.text_collection.enabled = False
  4973. # kind = self.ui.cncplot_method_combo.get_value()
  4974. # self.plot(kind=kind)
  4975. self.annotation.redraw()
  4976. def convert_units(self, units):
  4977. factor = CNCjob.convert_units(self, units)
  4978. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4979. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4980. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4981. 'endz', 'toolchangez']
  4982. temp_tools_dict = {}
  4983. tool_dia_copy = {}
  4984. data_copy = {}
  4985. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4986. for dia_key, dia_value in tooluid_value.items():
  4987. if dia_key == 'tooldia':
  4988. dia_value *= factor
  4989. dia_value = float('%.4f' % dia_value)
  4990. tool_dia_copy[dia_key] = dia_value
  4991. if dia_key == 'offset':
  4992. tool_dia_copy[dia_key] = dia_value
  4993. if dia_key == 'offset_value':
  4994. dia_value *= factor
  4995. tool_dia_copy[dia_key] = dia_value
  4996. if dia_key == 'type':
  4997. tool_dia_copy[dia_key] = dia_value
  4998. if dia_key == 'tool_type':
  4999. tool_dia_copy[dia_key] = dia_value
  5000. if dia_key == 'data':
  5001. for data_key, data_value in dia_value.items():
  5002. # convert the form fields that are convertible
  5003. for param in param_list:
  5004. if data_key == param and data_value is not None:
  5005. data_copy[data_key] = data_value * factor
  5006. # copy the other dict entries that are not convertible
  5007. if data_key not in param_list:
  5008. data_copy[data_key] = data_value
  5009. tool_dia_copy[dia_key] = deepcopy(data_copy)
  5010. data_copy.clear()
  5011. if dia_key == 'gcode':
  5012. tool_dia_copy[dia_key] = dia_value
  5013. if dia_key == 'gcode_parsed':
  5014. tool_dia_copy[dia_key] = dia_value
  5015. if dia_key == 'solid_geometry':
  5016. tool_dia_copy[dia_key] = dia_value
  5017. # if dia_key == 'solid_geometry':
  5018. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  5019. # if dia_key == 'gcode_parsed':
  5020. # for g in dia_value:
  5021. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  5022. #
  5023. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  5024. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  5025. temp_tools_dict.update({
  5026. tooluid_key: deepcopy(tool_dia_copy)
  5027. })
  5028. tool_dia_copy.clear()
  5029. self.cnc_tools.clear()
  5030. self.cnc_tools = deepcopy(temp_tools_dict)
  5031. # end of file