FlatCAMObj.py 275 KB

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