FlatCAMObj.py 279 KB

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