FlatCAMObj.py 342 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985
  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. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. from shapely.ops import cascaded_union
  13. import shapely.affinity as affinity
  14. from copy import deepcopy
  15. from copy import copy
  16. from io import StringIO
  17. import traceback
  18. import inspect # TODO: For debugging only.
  19. from datetime import datetime
  20. from flatcamEditors.FlatCAMTextEditor import TextEditor
  21. from flatcamGUI.ObjectUI import *
  22. from FlatCAMCommon import LoudDict
  23. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  24. from flatcamParsers.ParseExcellon import Excellon
  25. from flatcamParsers.ParseGerber import Gerber
  26. from camlib import Geometry, CNCjob
  27. import FlatCAMApp
  28. from flatcamGUI.VisPyVisuals import ShapeCollection
  29. import tkinter as tk
  30. import os
  31. import sys
  32. import itertools
  33. import ezdxf
  34. import math
  35. import numpy as np
  36. import gettext
  37. import FlatCAMTranslation as fcTranslate
  38. import builtins
  39. fcTranslate.apply_language('strings')
  40. if '_' not in builtins.__dict__:
  41. _ = gettext.gettext
  42. # Interrupts plotting process if FlatCAMObj has been deleted
  43. class ObjectDeleted(Exception):
  44. pass
  45. class ValidationError(Exception):
  46. def __init__(self, message, errors):
  47. super().__init__(message)
  48. self.errors = errors
  49. # #######################################
  50. # # FlatCAMObj ##
  51. # #######################################
  52. class FlatCAMObj(QtCore.QObject):
  53. """
  54. Base type of objects handled in FlatCAM. These become interactive
  55. in the GUI, can be plotted, and their options can be modified
  56. by the user in their respective forms.
  57. """
  58. # Instance of the application to which these are related.
  59. # The app should set this value.
  60. app = None
  61. # signal to plot a single object
  62. plot_single_object = QtCore.pyqtSignal()
  63. def __init__(self, name):
  64. """
  65. Constructor.
  66. :param name: Name of the object given by the user.
  67. :return: FlatCAMObj
  68. """
  69. QtCore.QObject.__init__(self)
  70. # View
  71. self.ui = None
  72. self.options = LoudDict(name=name)
  73. self.options.set_change_callback(self.on_options_change)
  74. self.form_fields = {}
  75. # store here the default data for Geometry Data
  76. self.default_data = {}
  77. # 2D mode
  78. # Axes must exist and be attached to canvas.
  79. self.axes = None
  80. self.kind = None # Override with proper name
  81. if self.app.is_legacy is False:
  82. self.shapes = self.app.plotcanvas.new_shape_group()
  83. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, pool=self.app.pool, layers=2)
  84. else:
  85. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name=name)
  86. self.mark_shapes = dict()
  87. self.item = None # Link with project view item
  88. self.muted_ui = False
  89. self.deleted = False
  90. try:
  91. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  92. self.app.defaults["global_tolerance"] else 0.01
  93. except ValueError:
  94. self._drawing_tolerance = 0.01
  95. self.isHovering = False
  96. self.notHovering = True
  97. # Flag to show if a selection shape is drawn
  98. self.selection_shape_drawn = False
  99. # self.units = 'IN'
  100. self.units = self.app.defaults['units']
  101. self.plot_single_object.connect(self.single_object_plot)
  102. def __del__(self):
  103. pass
  104. def __str__(self):
  105. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  106. def from_dict(self, d):
  107. """
  108. This supersedes ``from_dict`` in derived classes. Derived classes
  109. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  110. ``self.options`` is only updated, not overwritten. This ensures that
  111. options set by the app do not vanish when reading the objects
  112. from a project file.
  113. :param d: Dictionary with attributes to set.
  114. :return: None
  115. """
  116. for attr in self.ser_attrs:
  117. if attr == 'options':
  118. self.options.update(d[attr])
  119. else:
  120. try:
  121. setattr(self, attr, d[attr])
  122. except KeyError:
  123. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. "
  124. "Means that we are loading an old project that don't"
  125. "have all attributes in the latest FlatCAM." % str(attr))
  126. pass
  127. def on_options_change(self, key):
  128. # Update form on programmatically options change
  129. self.set_form_item(key)
  130. # Set object visibility
  131. if key == 'plot':
  132. self.visible = self.options['plot']
  133. self.optionChanged.emit(key)
  134. def set_ui(self, ui):
  135. self.ui = ui
  136. self.form_fields = {"name": self.ui.name_entry}
  137. assert isinstance(self.ui, ObjectUI)
  138. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  139. try:
  140. # it will raise an exception for those FlatCAM objects that do not build UI with the common elements
  141. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  142. except (TypeError, AttributeError):
  143. pass
  144. try:
  145. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  146. except (TypeError, AttributeError):
  147. pass
  148. try:
  149. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  150. except (TypeError, AttributeError):
  151. pass
  152. # Creates problems on focusOut
  153. try:
  154. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  155. except (TypeError, AttributeError):
  156. pass
  157. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  158. def build_ui(self):
  159. """
  160. Sets up the UI/form for this object. Show the UI
  161. in the App.
  162. :return: None
  163. :rtype: None
  164. """
  165. self.muted_ui = True
  166. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  167. try:
  168. # HACK: disconnect the scale entry signal since on focus out event will trigger an undesired scale()
  169. # it seems that the takewidget() does generate a focus out event for the QDoubleSpinbox ...
  170. # and reconnect after the takeWidget() is done
  171. # self.ui.scale_entry.returnPressed.disconnect(self.on_scale_button_click)
  172. self.app.ui.selected_scroll_area.takeWidget()
  173. # self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  174. except Exception as e:
  175. self.app.log.debug("FlatCAMObj.build_ui() --> Nothing to remove: %s" % str(e))
  176. self.app.ui.selected_scroll_area.setWidget(self.ui)
  177. self.muted_ui = False
  178. def on_name_activate(self, silent=None):
  179. old_name = copy(self.options["name"])
  180. new_name = self.ui.name_entry.get_value()
  181. if new_name != old_name:
  182. # update the SHELL auto-completer model data
  183. try:
  184. self.app.myKeywords.remove(old_name)
  185. self.app.myKeywords.append(new_name)
  186. self.app.shell._edit.set_model_data(self.app.myKeywords)
  187. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  188. except Exception:
  189. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  190. self.options["name"] = self.ui.name_entry.get_value()
  191. self.default_data["name"] = self.ui.name_entry.get_value()
  192. self.app.collection.update_view()
  193. if silent:
  194. self.app.inform.emit('[success] %s: %s %s: %s' % (
  195. _("Name changed from"), str(old_name), _("to"), str(new_name)
  196. )
  197. )
  198. def on_offset_button_click(self):
  199. self.app.report_usage("obj_on_offset_button")
  200. self.read_form()
  201. vector_val = self.ui.offsetvector_entry.get_value()
  202. def worker_task():
  203. with self.app.proc_container.new(_("Offsetting...")):
  204. self.offset(vector_val)
  205. self.app.proc_container.update_view_text('')
  206. with self.app.proc_container.new('%s...' % _("Plotting")):
  207. self.plot()
  208. self.app.object_changed.emit(self)
  209. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  210. def on_scale_button_click(self):
  211. self.read_form()
  212. try:
  213. factor = float(eval(self.ui.scale_entry.get_value()))
  214. except Exception as e:
  215. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  216. log.debug("FlatCAMObj.on_scale_button_click() -- %s" % str(e))
  217. return
  218. if type(factor) != float:
  219. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  220. # if factor is 1.0 do nothing, there is no point in scaling with a factor of 1.0
  221. if factor == 1.0:
  222. self.app.inform.emit('[success] %s' % _("Scale done."))
  223. return
  224. log.debug("FlatCAMObj.on_scale_button_click()")
  225. def worker_task():
  226. with self.app.proc_container.new(_("Scaling...")):
  227. self.scale(factor)
  228. self.app.inform.emit('[success] %s' % _("Scale done."))
  229. self.app.proc_container.update_view_text('')
  230. with self.app.proc_container.new('%s...' % _("Plotting")):
  231. self.plot()
  232. self.app.object_changed.emit(self)
  233. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  234. def on_skew_button_click(self):
  235. self.app.report_usage("obj_on_skew_button")
  236. self.read_form()
  237. x_angle = self.ui.xangle_entry.get_value()
  238. y_angle = self.ui.yangle_entry.get_value()
  239. def worker_task():
  240. with self.app.proc_container.new(_("Skewing...")):
  241. self.skew(x_angle, y_angle)
  242. self.app.proc_container.update_view_text('')
  243. with self.app.proc_container.new('%s...' % _("Plotting")):
  244. self.plot()
  245. self.app.object_changed.emit(self)
  246. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  247. def to_form(self):
  248. """
  249. Copies options to the UI form.
  250. :return: None
  251. """
  252. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  253. for option in self.options:
  254. try:
  255. self.set_form_item(option)
  256. except Exception:
  257. self.app.log.warning("Unexpected error:", sys.exc_info())
  258. def read_form(self):
  259. """
  260. Reads form into ``self.options``.
  261. :return: None
  262. :rtype: None
  263. """
  264. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  265. for option in self.options:
  266. try:
  267. self.read_form_item(option)
  268. except Exception:
  269. self.app.log.warning("Unexpected error:", sys.exc_info())
  270. def set_form_item(self, option):
  271. """
  272. Copies the specified option to the UI form.
  273. :param option: Name of the option (Key in ``self.options``).
  274. :type option: str
  275. :return: None
  276. """
  277. try:
  278. self.form_fields[option].set_value(self.options[option])
  279. except KeyError:
  280. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  281. pass
  282. def read_form_item(self, option):
  283. """
  284. Reads the specified option from the UI form into ``self.options``.
  285. :param option: Name of the option.
  286. :type option: str
  287. :return: None
  288. """
  289. try:
  290. self.options[option] = self.form_fields[option].get_value()
  291. except KeyError:
  292. pass
  293. # self.app.log.warning("Failed to read option from field: %s" % option)
  294. def plot(self):
  295. """
  296. Plot this object (Extend this method to implement the actual plotting).
  297. Call this in descendants before doing the plotting.
  298. :return: Whether to continue plotting or not depending on the "plot" option.
  299. :rtype: bool
  300. """
  301. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  302. if self.deleted:
  303. return False
  304. self.clear()
  305. return True
  306. def single_object_plot(self):
  307. def plot_task():
  308. with self.app.proc_container.new('%s...' % _("Plotting")):
  309. self.plot()
  310. self.app.object_changed.emit(self)
  311. self.app.worker_task.emit({'fcn': plot_task, 'params': []})
  312. def serialize(self):
  313. """
  314. Returns a representation of the object as a dictionary so
  315. it can be later exported as JSON. Override this method.
  316. :return: Dictionary representing the object
  317. :rtype: dict
  318. """
  319. return
  320. def deserialize(self, obj_dict):
  321. """
  322. Re-builds an object from its serialized version.
  323. :param obj_dict: Dictionary representing a FlatCAMObj
  324. :type obj_dict: dict
  325. :return: None
  326. """
  327. return
  328. def add_shape(self, **kwargs):
  329. if self.deleted:
  330. raise ObjectDeleted()
  331. else:
  332. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  333. return key
  334. def add_mark_shape(self, apid, **kwargs):
  335. if self.deleted:
  336. raise ObjectDeleted()
  337. else:
  338. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, layer=0, **kwargs)
  339. return key
  340. def update_filters(self, last_ext, filter_string):
  341. """
  342. Will modify the filter string that is used when saving a file (a list of file extensions) to have the last
  343. used file extension as the first one in the special string
  344. :param last_ext: the file extension that was last used to save a file
  345. :param filter_string: a key in self.app.defaults that holds a string with the filter from QFileDialog
  346. used when saving a file
  347. :return: None
  348. """
  349. filters = copy(self.app.defaults[filter_string])
  350. filter_list = filters.split(';;')
  351. filter_list_enum_1 = enumerate(filter_list)
  352. # search for the last element in the filters which should always be "All Files (*.*)"
  353. last_elem = ''
  354. for elem in list(filter_list_enum_1):
  355. if '(*.*)' in elem[1]:
  356. last_elem = filter_list.pop(elem[0])
  357. filter_list_enum = enumerate(filter_list)
  358. for elem in list(filter_list_enum):
  359. if '.' + last_ext in elem[1]:
  360. used_ext = filter_list.pop(elem[0])
  361. # sort the extensions back
  362. filter_list.sort(key=lambda x: x.rpartition('.')[2])
  363. # add as a first element the last used extension
  364. filter_list.insert(0, used_ext)
  365. # add back the element that should always be the last (All Files)
  366. filter_list.append(last_elem)
  367. self.app.defaults[filter_string] = ';;'.join(filter_list)
  368. return
  369. @staticmethod
  370. def poly2rings(poly):
  371. return [poly.exterior] + [interior for interior in poly.interiors]
  372. @property
  373. def visible(self):
  374. return self.shapes.visible
  375. @visible.setter
  376. def visible(self, value, threaded=True):
  377. log.debug("FlatCAMObj.visible()")
  378. def worker_task(app_obj):
  379. self.shapes.visible = value
  380. if self.app.is_legacy is False:
  381. # Not all object types has annotations
  382. try:
  383. self.annotation.visible = value
  384. except Exception as e:
  385. pass
  386. if threaded is False:
  387. worker_task(app_obj=self.app)
  388. else:
  389. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  390. @property
  391. def drawing_tolerance(self):
  392. self.units = self.app.defaults['units'].upper()
  393. tol = self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  394. return tol
  395. @drawing_tolerance.setter
  396. def drawing_tolerance(self, value):
  397. self.units = self.app.defaults['units'].upper()
  398. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  399. def clear(self, update=False):
  400. self.shapes.clear(update)
  401. # Not all object types has annotations
  402. try:
  403. self.annotation.clear(update)
  404. except AttributeError:
  405. pass
  406. def delete(self):
  407. # Free resources
  408. del self.ui
  409. del self.options
  410. # Set flag
  411. self.deleted = True
  412. class FlatCAMGerber(FlatCAMObj, Gerber):
  413. """
  414. Represents Gerber code.
  415. """
  416. optionChanged = QtCore.pyqtSignal(str)
  417. replotApertures = QtCore.pyqtSignal()
  418. ui_type = GerberObjectUI
  419. def merge(self, grb_list, grb_final):
  420. """
  421. Merges the geometry of objects in geo_list into
  422. the geometry of geo_final.
  423. :param grb_list: List of FlatCAMGerber Objects to join.
  424. :param grb_final: Destination FlatCAMGeometry object.
  425. :return: None
  426. """
  427. if grb_final.solid_geometry is None:
  428. grb_final.solid_geometry = []
  429. grb_final.follow_geometry = []
  430. if not grb_final.apertures:
  431. grb_final.apertures = {}
  432. if type(grb_final.solid_geometry) is not list:
  433. grb_final.solid_geometry = [grb_final.solid_geometry]
  434. grb_final.follow_geometry = [grb_final.follow_geometry]
  435. for grb in grb_list:
  436. # Expand lists
  437. if type(grb) is list:
  438. FlatCAMGerber.merge(grb, grb_final)
  439. else: # If not list, just append
  440. for option in grb.options:
  441. if option is not 'name':
  442. try:
  443. grb_final.options[option] = grb.options[option]
  444. except KeyError:
  445. log.warning("Failed to copy option.", option)
  446. try:
  447. for geos in grb.solid_geometry:
  448. grb_final.solid_geometry.append(geos)
  449. grb_final.follow_geometry.append(geos)
  450. except TypeError:
  451. grb_final.solid_geometry.append(grb.solid_geometry)
  452. grb_final.follow_geometry.append(grb.solid_geometry)
  453. for ap in grb.apertures:
  454. if ap not in grb_final.apertures:
  455. grb_final.apertures[ap] = grb.apertures[ap]
  456. else:
  457. # create a list of integers out of the grb.apertures keys and find the max of that value
  458. # then, the aperture duplicate is assigned an id value incremented with 1,
  459. # and finally made string because the apertures dict keys are strings
  460. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  461. grb_final.apertures[max_ap] = {}
  462. grb_final.apertures[max_ap]['geometry'] = []
  463. for k, v in grb.apertures[ap].items():
  464. grb_final.apertures[max_ap][k] = deepcopy(v)
  465. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  466. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  467. def __init__(self, name):
  468. self.decimals = self.app.decimals
  469. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  470. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  471. FlatCAMObj.__init__(self, name)
  472. self.kind = "gerber"
  473. # The 'name' is already in self.options from FlatCAMObj
  474. # Automatically updates the UI
  475. self.options.update({
  476. "plot": True,
  477. "multicolored": False,
  478. "solid": False,
  479. "tool_type": 'circular',
  480. "vtipdia": 0.1,
  481. "vtipangle": 30,
  482. "vcutz": -0.05,
  483. "isotooldia": 0.016,
  484. "isopasses": 1,
  485. "isooverlap": 15,
  486. "milling_type": "cl",
  487. "combine_passes": True,
  488. "noncoppermargin": 0.0,
  489. "noncopperrounded": False,
  490. "bboxmargin": 0.0,
  491. "bboxrounded": False,
  492. "aperture_display": False,
  493. "follow": False,
  494. "iso_scope": 'all',
  495. "iso_type": 'full'
  496. })
  497. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  498. self.iso_type = 2
  499. self.multigeo = False
  500. self.follow = False
  501. self.apertures_row = 0
  502. # store the source file here
  503. self.source_file = ""
  504. # list of rows with apertures plotted
  505. self.marked_rows = []
  506. # Mouse events
  507. self.mr = None
  508. self.mm = None
  509. self.mp = None
  510. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  511. self.poly_dict = dict()
  512. # store the status of grid snapping
  513. self.grid_status_memory = None
  514. self.units_found = self.app.defaults['units']
  515. self.fill_color = self.app.defaults['gerber_plot_fill']
  516. self.outline_color = self.app.defaults['gerber_plot_line']
  517. self.alpha_level = 'bf'
  518. # keep track if the UI is built so we don't have to build it every time
  519. self.ui_build = False
  520. # build only once the aperture storage (takes time)
  521. self.build_aperture_storage = False
  522. # Attributes to be included in serialization
  523. # Always append to it because it carries contents
  524. # from predecessors.
  525. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  526. def set_ui(self, ui):
  527. """
  528. Maps options with GUI inputs.
  529. Connects GUI events to methods.
  530. :param ui: GUI object.
  531. :type ui: GerberObjectUI
  532. :return: None
  533. """
  534. FlatCAMObj.set_ui(self, ui)
  535. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  536. self.units = self.app.defaults['units'].upper()
  537. self.replotApertures.connect(self.on_mark_cb_click_table)
  538. self.form_fields.update({
  539. "plot": self.ui.plot_cb,
  540. "multicolored": self.ui.multicolored_cb,
  541. "solid": self.ui.solid_cb,
  542. "tool_type": self.ui.tool_type_radio,
  543. "vtipdia": self.ui.tipdia_spinner,
  544. "vtipangle": self.ui.tipangle_spinner,
  545. "vcutz": self.ui.cutz_spinner,
  546. "isotooldia": self.ui.iso_tool_dia_entry,
  547. "isopasses": self.ui.iso_width_entry,
  548. "isooverlap": self.ui.iso_overlap_entry,
  549. "milling_type": self.ui.milling_type_radio,
  550. "combine_passes": self.ui.combine_passes_cb,
  551. "noncoppermargin": self.ui.noncopper_margin_entry,
  552. "noncopperrounded": self.ui.noncopper_rounded_cb,
  553. "bboxmargin": self.ui.bbmargin_entry,
  554. "bboxrounded": self.ui.bbrounded_cb,
  555. "aperture_display": self.ui.aperture_table_visibility_cb,
  556. "follow": self.ui.follow_cb,
  557. "iso_scope": self.ui.iso_scope_radio,
  558. "iso_type": self.ui.iso_type_radio
  559. })
  560. # Fill form fields only on object create
  561. self.to_form()
  562. assert isinstance(self.ui, GerberObjectUI)
  563. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  564. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  565. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  566. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  567. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  568. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  569. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  570. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  571. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  572. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  573. # set the model for the Area Exception comboboxes
  574. self.ui.obj_combo.setModel(self.app.collection)
  575. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  576. self.ui.obj_combo.setCurrentIndex(1)
  577. self.ui.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  578. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type_change)
  579. # establish visibility for the GUI elements found in the slot function
  580. self.ui.tool_type_radio.activated_custom.emit(self.options['tool_type'])
  581. # Show/Hide Advanced Options
  582. if self.app.defaults["global_app_level"] == 'b':
  583. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  584. self.options['tool_type'] = 'circular'
  585. self.ui.tool_type_label.hide()
  586. self.ui.tool_type_radio.hide()
  587. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  588. self.ui.tool_type_radio.set_value('circular')
  589. self.ui.tipdialabel.hide()
  590. self.ui.tipdia_spinner.hide()
  591. self.ui.tipanglelabel.hide()
  592. self.ui.tipangle_spinner.hide()
  593. self.ui.cutzlabel.hide()
  594. self.ui.cutz_spinner.hide()
  595. self.ui.apertures_table_label.hide()
  596. self.ui.aperture_table_visibility_cb.hide()
  597. self.ui.milling_type_label.hide()
  598. self.ui.milling_type_radio.hide()
  599. self.ui.iso_type_label.hide()
  600. self.ui.iso_type_radio.hide()
  601. self.ui.follow_cb.hide()
  602. self.ui.except_cb.setChecked(False)
  603. self.ui.except_cb.hide()
  604. else:
  605. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  606. self.ui.tipdia_spinner.valueChanged.connect(self.on_calculate_tooldia)
  607. self.ui.tipangle_spinner.valueChanged.connect(self.on_calculate_tooldia)
  608. self.ui.cutz_spinner.valueChanged.connect(self.on_calculate_tooldia)
  609. if self.app.defaults["gerber_buffering"] == 'no':
  610. self.ui.create_buffer_button.show()
  611. try:
  612. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  613. except TypeError:
  614. pass
  615. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  616. else:
  617. self.ui.create_buffer_button.hide()
  618. # set initial state of the aperture table and associated widgets
  619. self.on_aperture_table_visibility_change()
  620. self.build_ui()
  621. self.units_found = self.app.defaults['units']
  622. def on_calculate_tooldia(self):
  623. try:
  624. tdia = float(self.ui.tipdia_spinner.get_value())
  625. except Exception:
  626. return
  627. try:
  628. dang = float(self.ui.tipangle_spinner.get_value())
  629. except Exception:
  630. return
  631. try:
  632. cutz = float(self.ui.cutz_spinner.get_value())
  633. except Exception:
  634. return
  635. cutz *= -1
  636. if cutz < 0:
  637. cutz *= -1
  638. half_tip_angle = dang / 2
  639. tool_diameter = tdia + (2 * cutz * math.tan(math.radians(half_tip_angle)))
  640. self.ui.iso_tool_dia_entry.set_value(tool_diameter)
  641. def on_type_obj_index_changed(self, index):
  642. obj_type = self.ui.type_obj_combo.currentIndex()
  643. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  644. self.ui.obj_combo.setCurrentIndex(0)
  645. def on_tool_type_change(self, state):
  646. if state == 'circular':
  647. self.ui.tipdialabel.hide()
  648. self.ui.tipdia_spinner.hide()
  649. self.ui.tipanglelabel.hide()
  650. self.ui.tipangle_spinner.hide()
  651. self.ui.cutzlabel.hide()
  652. self.ui.cutz_spinner.hide()
  653. self.ui.iso_tool_dia_entry.setDisabled(False)
  654. # update the value in the self.iso_tool_dia_entry once this is selected
  655. self.ui.iso_tool_dia_entry.set_value(self.options['isotooldia'])
  656. else:
  657. self.ui.tipdialabel.show()
  658. self.ui.tipdia_spinner.show()
  659. self.ui.tipanglelabel.show()
  660. self.ui.tipangle_spinner.show()
  661. self.ui.cutzlabel.show()
  662. self.ui.cutz_spinner.show()
  663. self.ui.iso_tool_dia_entry.setDisabled(True)
  664. # update the value in the self.iso_tool_dia_entry once this is selected
  665. self.on_calculate_tooldia()
  666. def build_ui(self):
  667. FlatCAMObj.build_ui(self)
  668. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  669. self.ui_build = True
  670. try:
  671. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  672. self.ui.apertures_table.itemChanged.disconnect()
  673. except (TypeError, AttributeError):
  674. pass
  675. self.apertures_row = 0
  676. aper_no = self.apertures_row + 1
  677. sort = []
  678. for k, v in list(self.apertures.items()):
  679. sort.append(int(k))
  680. sorted_apertures = sorted(sort)
  681. n = len(sorted_apertures)
  682. self.ui.apertures_table.setRowCount(n)
  683. for ap_code in sorted_apertures:
  684. ap_code = str(ap_code)
  685. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  686. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  687. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  688. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  689. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  690. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  691. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  692. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  693. ap_dim_item = QtWidgets.QTableWidgetItem(
  694. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  695. self.decimals, self.apertures[ap_code]['height']
  696. )
  697. )
  698. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  699. elif str(self.apertures[ap_code]['type']) == 'P':
  700. ap_dim_item = QtWidgets.QTableWidgetItem(
  701. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  702. self.decimals, self.apertures[ap_code]['nVertices'])
  703. )
  704. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  705. else:
  706. ap_dim_item = QtWidgets.QTableWidgetItem('')
  707. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  708. try:
  709. if self.apertures[ap_code]['size'] is not None:
  710. ap_size_item = QtWidgets.QTableWidgetItem(
  711. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  712. else:
  713. ap_size_item = QtWidgets.QTableWidgetItem('')
  714. except KeyError:
  715. ap_size_item = QtWidgets.QTableWidgetItem('')
  716. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  717. mark_item = FCCheckBox()
  718. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  719. # if self.ui.aperture_table_visibility_cb.isChecked():
  720. # mark_item.setChecked(True)
  721. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  722. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  723. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  724. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  725. empty_plot_item = QtWidgets.QTableWidgetItem('')
  726. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  727. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  728. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  729. self.apertures_row += 1
  730. self.ui.apertures_table.selectColumn(0)
  731. self.ui.apertures_table.resizeColumnsToContents()
  732. self.ui.apertures_table.resizeRowsToContents()
  733. vertical_header = self.ui.apertures_table.verticalHeader()
  734. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  735. vertical_header.hide()
  736. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  737. horizontal_header = self.ui.apertures_table.horizontalHeader()
  738. horizontal_header.setMinimumSectionSize(10)
  739. horizontal_header.setDefaultSectionSize(70)
  740. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  741. horizontal_header.resizeSection(0, 27)
  742. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  743. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  744. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  745. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  746. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  747. horizontal_header.resizeSection(5, 17)
  748. self.ui.apertures_table.setColumnWidth(5, 17)
  749. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  750. self.ui.apertures_table.setSortingEnabled(False)
  751. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  752. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  753. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  754. if self.marked_rows:
  755. for row in range(self.ui.apertures_table.rowCount()):
  756. try:
  757. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  758. except IndexError:
  759. pass
  760. self.ui_connect()
  761. def ui_connect(self):
  762. for row in range(self.ui.apertures_table.rowCount()):
  763. try:
  764. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  765. except (TypeError, AttributeError):
  766. pass
  767. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  768. try:
  769. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  770. except (TypeError, AttributeError):
  771. pass
  772. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  773. def ui_disconnect(self):
  774. for row in range(self.ui.apertures_table.rowCount()):
  775. try:
  776. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  777. except (TypeError, AttributeError):
  778. pass
  779. try:
  780. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  781. except (TypeError, AttributeError):
  782. pass
  783. def on_generate_buffer(self):
  784. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  785. def buffer_task():
  786. with self.app.proc_container.new('%s...' % _("Buffering")):
  787. if isinstance(self.solid_geometry, list):
  788. self.solid_geometry = MultiPolygon(self.solid_geometry)
  789. self.solid_geometry = self.solid_geometry.buffer(0.0000001)
  790. self.solid_geometry = self.solid_geometry.buffer(-0.0000001)
  791. self.app.inform.emit('[success] %s.' % _("Done"))
  792. self.plot_single_object.emit()
  793. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  794. def on_generatenoncopper_button_click(self, *args):
  795. self.app.report_usage("gerber_on_generatenoncopper_button")
  796. self.read_form()
  797. name = self.options["name"] + "_noncopper"
  798. def geo_init(geo_obj, app_obj):
  799. assert isinstance(geo_obj, FlatCAMGeometry)
  800. if isinstance(self.solid_geometry, list):
  801. try:
  802. self.solid_geometry = MultiPolygon(self.solid_geometry)
  803. except Exception:
  804. self.solid_geometry = cascaded_union(self.solid_geometry)
  805. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  806. if not self.options["noncopperrounded"]:
  807. bounding_box = bounding_box.envelope
  808. non_copper = bounding_box.difference(self.solid_geometry)
  809. if non_copper is None or non_copper.is_empty:
  810. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  811. return "fail"
  812. geo_obj.solid_geometry = non_copper
  813. self.app.new_object("geometry", name, geo_init)
  814. def on_generatebb_button_click(self, *args):
  815. self.app.report_usage("gerber_on_generatebb_button")
  816. self.read_form()
  817. name = self.options["name"] + "_bbox"
  818. def geo_init(geo_obj, app_obj):
  819. assert isinstance(geo_obj, FlatCAMGeometry)
  820. if isinstance(self.solid_geometry, list):
  821. try:
  822. self.solid_geometry = MultiPolygon(self.solid_geometry)
  823. except Exception:
  824. self.solid_geometry = cascaded_union(self.solid_geometry)
  825. # Bounding box with rounded corners
  826. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  827. if not self.options["bboxrounded"]: # Remove rounded corners
  828. bounding_box = bounding_box.envelope
  829. if bounding_box is None or bounding_box.is_empty:
  830. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  831. return "fail"
  832. geo_obj.solid_geometry = bounding_box
  833. self.app.new_object("geometry", name, geo_init)
  834. def on_iso_button_click(self, *args):
  835. obj = self.app.collection.get_active()
  836. self.iso_type = 2
  837. if self.ui.iso_type_radio.get_value() == 'ext':
  838. self.iso_type = 0
  839. if self.ui.iso_type_radio.get_value() == 'int':
  840. self.iso_type = 1
  841. def worker_task(obj, app_obj):
  842. with self.app.proc_container.new(_("Isolating...")):
  843. if self.ui.follow_cb.get_value() is True:
  844. obj.follow_geo()
  845. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  846. obj.ui.plot_cb.toggle()
  847. else:
  848. app_obj.report_usage("gerber_on_iso_button")
  849. self.read_form()
  850. iso_scope = 'all' if self.ui.iso_scope_radio.get_value() == 'all' else 'single'
  851. self.isolate_handler(iso_type=self.iso_type, iso_scope=iso_scope)
  852. self.app.worker_task.emit({'fcn': worker_task, 'params': [obj, self.app]})
  853. def follow_geo(self, outname=None):
  854. """
  855. Creates a geometry object "following" the gerber paths.
  856. :return: None
  857. """
  858. # default_name = self.options["name"] + "_follow"
  859. # follow_name = outname or default_name
  860. if outname is None:
  861. follow_name = self.options["name"] + "_follow"
  862. else:
  863. follow_name = outname
  864. def follow_init(follow_obj, app):
  865. # Propagate options
  866. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  867. follow_obj.solid_geometry = self.follow_geometry
  868. # TODO: Do something if this is None. Offer changing name?
  869. try:
  870. self.app.new_object("geometry", follow_name, follow_init)
  871. except Exception as e:
  872. return "Operation failed: %s" % str(e)
  873. def isolate_handler(self, iso_type, iso_scope):
  874. if iso_scope == 'all':
  875. self.isolate(iso_type=iso_type)
  876. else:
  877. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  878. if self.app.ui.grid_snap_btn.isChecked():
  879. self.grid_status_memory = True
  880. self.app.ui.grid_snap_btn.trigger()
  881. else:
  882. self.grid_status_memory = False
  883. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  884. if self.app.is_legacy is False:
  885. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  886. else:
  887. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  888. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  889. def on_mouse_click_release(self, event):
  890. if self.app.is_legacy is False:
  891. event_pos = event.pos
  892. right_button = 2
  893. self.app.event_is_dragging = self.app.event_is_dragging
  894. else:
  895. event_pos = (event.xdata, event.ydata)
  896. right_button = 3
  897. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  898. try:
  899. x = float(event_pos[0])
  900. y = float(event_pos[1])
  901. except TypeError:
  902. return
  903. event_pos = (x, y)
  904. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  905. if self.app.grid_status():
  906. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  907. else:
  908. curr_pos = (curr_pos[0], curr_pos[1])
  909. if event.button == 1:
  910. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]))
  911. if self.app.selection_type is not None:
  912. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  913. self.app.selection_type = None
  914. elif clicked_poly:
  915. if clicked_poly not in self.poly_dict.values():
  916. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  917. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  918. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  919. visible=True)
  920. self.poly_dict[shape_id] = clicked_poly
  921. self.app.inform.emit(
  922. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  923. _("Click to add next polygon or right click to start isolation."))
  924. )
  925. else:
  926. try:
  927. for k, v in list(self.poly_dict.items()):
  928. if v == clicked_poly:
  929. self.app.tool_shapes.remove(k)
  930. self.poly_dict.pop(k)
  931. break
  932. except TypeError:
  933. return
  934. self.app.inform.emit(
  935. '%s. %s' % (_("Removed polygon"),
  936. _("Click to add/remove next polygon or right click to start isolation."))
  937. )
  938. self.app.tool_shapes.redraw()
  939. else:
  940. self.app.inform.emit(_("No polygon detected under click position."))
  941. elif event.button == right_button and self.app.event_is_dragging is False:
  942. # restore the Grid snapping if it was active before
  943. if self.grid_status_memory is True:
  944. self.app.ui.grid_snap_btn.trigger()
  945. if self.app.is_legacy is False:
  946. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  947. else:
  948. self.app.plotcanvas.graph_event_disconnect(self.mr)
  949. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  950. self.app.on_mouse_click_release_over_plot)
  951. self.app.tool_shapes.clear(update=True)
  952. if self.poly_dict:
  953. poly_list = deepcopy(list(self.poly_dict.values()))
  954. self.isolate(iso_type=self.iso_type, geometry=poly_list)
  955. self.poly_dict.clear()
  956. else:
  957. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  958. def selection_area_handler(self, start_pos, end_pos, sel_type):
  959. """
  960. :param start_pos: mouse position when the selection LMB click was done
  961. :param end_pos: mouse position when the left mouse button is released
  962. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  963. :return:
  964. """
  965. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  966. # delete previous selection shape
  967. self.app.delete_selection_shape()
  968. added_poly_count = 0
  969. try:
  970. for geo in self.solid_geometry:
  971. if geo not in self.poly_dict.values():
  972. if sel_type is True:
  973. if geo.within(poly_selection):
  974. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  975. shape=geo,
  976. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  977. face_color=self.app.defaults[
  978. 'global_sel_draw_color'] + 'AF',
  979. visible=True)
  980. self.poly_dict[shape_id] = geo
  981. added_poly_count += 1
  982. else:
  983. if poly_selection.intersects(geo):
  984. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  985. shape=geo,
  986. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  987. face_color=self.app.defaults[
  988. 'global_sel_draw_color'] + 'AF',
  989. visible=True)
  990. self.poly_dict[shape_id] = geo
  991. added_poly_count += 1
  992. except TypeError:
  993. if self.solid_geometry not in self.poly_dict.values():
  994. if sel_type is True:
  995. if self.solid_geometry.within(poly_selection):
  996. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  997. shape=self.solid_geometry,
  998. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  999. face_color=self.app.defaults[
  1000. 'global_sel_draw_color'] + 'AF',
  1001. visible=True)
  1002. self.poly_dict[shape_id] = self.solid_geometry
  1003. added_poly_count += 1
  1004. else:
  1005. if poly_selection.intersects(self.solid_geometry):
  1006. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  1007. shape=self.solid_geometry,
  1008. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1009. face_color=self.app.defaults[
  1010. 'global_sel_draw_color'] + 'AF',
  1011. visible=True)
  1012. self.poly_dict[shape_id] = self.solid_geometry
  1013. added_poly_count += 1
  1014. if added_poly_count > 0:
  1015. self.app.tool_shapes.redraw()
  1016. self.app.inform.emit(
  1017. '%s: %d. %s' % (_("Added polygon"),
  1018. int(added_poly_count),
  1019. _("Click to add next polygon or right click to start isolation."))
  1020. )
  1021. else:
  1022. self.app.inform.emit(_("No polygon in selection."))
  1023. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  1024. milling_type=None, follow=None, plot=True):
  1025. """
  1026. Creates an isolation routing geometry object in the project.
  1027. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  1028. :param geometry: specific geometry to isolate
  1029. :param dia: Tool diameter
  1030. :param passes: Number of tool widths to cut
  1031. :param overlap: Overlap between passes in fraction of tool diameter
  1032. :param outname: Base name of the output object
  1033. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  1034. :param milling_type: type of milling: conventional or climbing
  1035. :param follow: Boolean: if to generate a 'follow' geometry
  1036. :param plot: Boolean: if to plot the resulting geometry object
  1037. :return: None
  1038. """
  1039. if geometry is None:
  1040. work_geo = self.follow_geometry if follow is True else self.solid_geometry
  1041. else:
  1042. work_geo = geometry
  1043. if dia is None:
  1044. dia = float(self.options["isotooldia"])
  1045. if passes is None:
  1046. passes = int(self.options["isopasses"])
  1047. if overlap is None:
  1048. overlap = float(self.options["isooverlap"])
  1049. overlap /= 100.0
  1050. combine = self.options["combine_passes"] if combine is None else bool(combine)
  1051. if milling_type is None:
  1052. milling_type = self.options["milling_type"]
  1053. if iso_type is None:
  1054. iso_t = 2
  1055. else:
  1056. iso_t = iso_type
  1057. base_name = self.options["name"]
  1058. if combine:
  1059. if outname is None:
  1060. if self.iso_type == 0:
  1061. iso_name = base_name + "_ext_iso"
  1062. elif self.iso_type == 1:
  1063. iso_name = base_name + "_int_iso"
  1064. else:
  1065. iso_name = base_name + "_iso"
  1066. else:
  1067. iso_name = outname
  1068. def iso_init(geo_obj, app_obj):
  1069. # Propagate options
  1070. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1071. geo_obj.tool_type = self.ui.tool_type_radio.get_value().upper()
  1072. geo_obj.solid_geometry = list()
  1073. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1074. if self.ui.tool_type_radio.get_value() == 'v':
  1075. new_cutz = self.ui.cutz_spinner.get_value()
  1076. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1077. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1078. tool_type = 'V'
  1079. else:
  1080. new_cutz = self.app.defaults['geometry_cutz']
  1081. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1082. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1083. tool_type = 'C1'
  1084. # store here the default data for Geometry Data
  1085. default_data = {}
  1086. default_data.update({
  1087. "name": iso_name,
  1088. "plot": self.app.defaults['geometry_plot'],
  1089. "cutz": new_cutz,
  1090. "vtipdia": new_vtipdia,
  1091. "vtipangle": new_vtipangle,
  1092. "travelz": self.app.defaults['geometry_travelz'],
  1093. "feedrate": self.app.defaults['geometry_feedrate'],
  1094. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1095. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1096. "dwell": self.app.defaults['geometry_dwell'],
  1097. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1098. "multidepth": self.app.defaults['geometry_multidepth'],
  1099. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1100. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1101. "extracut": self.app.defaults['geometry_extracut'],
  1102. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1103. "toolchange": self.app.defaults['geometry_toolchange'],
  1104. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1105. "endz": self.app.defaults['geometry_endz'],
  1106. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1107. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1108. "startz": self.app.defaults['geometry_startz']
  1109. })
  1110. geo_obj.tools = dict()
  1111. geo_obj.tools['1'] = dict()
  1112. geo_obj.tools.update({
  1113. '1': {
  1114. 'tooldia': float(self.options["isotooldia"]),
  1115. 'offset': 'Path',
  1116. 'offset_value': 0.0,
  1117. 'type': _('Rough'),
  1118. 'tool_type': tool_type,
  1119. 'data': default_data,
  1120. 'solid_geometry': geo_obj.solid_geometry
  1121. }
  1122. })
  1123. for nr_pass in range(passes):
  1124. iso_offset = dia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * dia)
  1125. # if milling type is climb then the move is counter-clockwise around features
  1126. mill_dir = 1 if milling_type == 'cl' else 0
  1127. geom = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1128. follow=follow, nr_passes=nr_pass)
  1129. if geom == 'fail':
  1130. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1131. return 'fail'
  1132. geo_obj.solid_geometry.append(geom)
  1133. # update the geometry in the tools
  1134. geo_obj.tools['1']['solid_geometry'] = geo_obj.solid_geometry
  1135. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1136. # or just looking in the lists (they are one level depth) and if any is not empty
  1137. # proceed with object creation, if there are empty and the number of them is the length
  1138. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1139. empty_cnt = 0
  1140. if not isinstance(geo_obj.solid_geometry, list) and \
  1141. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1142. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1143. for g in geo_obj.solid_geometry:
  1144. if g:
  1145. break
  1146. else:
  1147. empty_cnt += 1
  1148. if empty_cnt == len(geo_obj.solid_geometry):
  1149. raise ValidationError("Empty Geometry", None)
  1150. else:
  1151. app_obj.inform.emit('[success] %s" %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  1152. # even if combine is checked, one pass is still single-geo
  1153. geo_obj.multigeo = True if passes > 1 else False
  1154. # ############################################################
  1155. # ########## AREA SUBTRACTION ################################
  1156. # ############################################################
  1157. if self.ui.except_cb.get_value():
  1158. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1159. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1160. # TODO: Do something if this is None. Offer changing name?
  1161. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1162. else:
  1163. for i in range(passes):
  1164. offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  1165. if passes > 1:
  1166. if outname is None:
  1167. if self.iso_type == 0:
  1168. iso_name = base_name + "_ext_iso" + str(i + 1)
  1169. elif self.iso_type == 1:
  1170. iso_name = base_name + "_int_iso" + str(i + 1)
  1171. else:
  1172. iso_name = base_name + "_iso" + str(i + 1)
  1173. else:
  1174. iso_name = outname
  1175. else:
  1176. if outname is None:
  1177. if self.iso_type == 0:
  1178. iso_name = base_name + "_ext_iso"
  1179. elif self.iso_type == 1:
  1180. iso_name = base_name + "_int_iso"
  1181. else:
  1182. iso_name = base_name + "_iso"
  1183. else:
  1184. iso_name = outname
  1185. def iso_init(geo_obj, app_obj):
  1186. # Propagate options
  1187. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1188. if self.ui.tool_type_radio.get_value() == 'v':
  1189. geo_obj.tool_type = 'V'
  1190. else:
  1191. geo_obj.tool_type = 'C1'
  1192. # if milling type is climb then the move is counter-clockwise around features
  1193. mill_dir = 1 if milling_type == 'cl' else 0
  1194. geom = self.generate_envelope(offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  1195. follow=follow,
  1196. nr_passes=i)
  1197. if geom == 'fail':
  1198. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1199. return 'fail'
  1200. geo_obj.solid_geometry = geom
  1201. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1202. # even if the resulting geometry is not multigeo we add the tools dict which will hold the data
  1203. # required to be transfered to the Geometry object
  1204. if self.ui.tool_type_radio.get_value() == 'v':
  1205. new_cutz = self.ui.cutz_spinner.get_value()
  1206. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1207. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1208. tool_type = 'V'
  1209. else:
  1210. new_cutz = self.app.defaults['geometry_cutz']
  1211. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1212. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1213. tool_type = 'C1'
  1214. # store here the default data for Geometry Data
  1215. default_data = {}
  1216. default_data.update({
  1217. "name": iso_name,
  1218. "plot": self.app.defaults['geometry_plot'],
  1219. "cutz": new_cutz,
  1220. "vtipdia": new_vtipdia,
  1221. "vtipangle": new_vtipangle,
  1222. "travelz": self.app.defaults['geometry_travelz'],
  1223. "feedrate": self.app.defaults['geometry_feedrate'],
  1224. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1225. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1226. "dwell": self.app.defaults['geometry_dwell'],
  1227. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1228. "multidepth": self.app.defaults['geometry_multidepth'],
  1229. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1230. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1231. "extracut": self.app.defaults['geometry_extracut'],
  1232. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1233. "toolchange": self.app.defaults['geometry_toolchange'],
  1234. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1235. "endz": self.app.defaults['geometry_endz'],
  1236. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1237. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1238. "startz": self.app.defaults['geometry_startz']
  1239. })
  1240. geo_obj.tools = dict()
  1241. geo_obj.tools['1'] = dict()
  1242. geo_obj.tools.update({
  1243. '1': {
  1244. 'tooldia': float(self.options["isotooldia"]),
  1245. 'offset': 'Path',
  1246. 'offset_value': 0.0,
  1247. 'type': _('Rough'),
  1248. 'tool_type': tool_type,
  1249. 'data': default_data,
  1250. 'solid_geometry': geo_obj.solid_geometry
  1251. }
  1252. })
  1253. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1254. # or just looking in the lists (they are one level depth) and if any is not empty
  1255. # proceed with object creation, if there are empty and the number of them is the length
  1256. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1257. empty_cnt = 0
  1258. if not isinstance(geo_obj.solid_geometry, list):
  1259. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1260. for g in geo_obj.solid_geometry:
  1261. if g:
  1262. break
  1263. else:
  1264. empty_cnt += 1
  1265. if empty_cnt == len(geo_obj.solid_geometry):
  1266. raise ValidationError("Empty Geometry", None)
  1267. else:
  1268. app_obj.inform.emit('[success] %s: %s' %
  1269. (_("Isolation geometry created"), geo_obj.options["name"]))
  1270. geo_obj.multigeo = False
  1271. # ############################################################
  1272. # ########## AREA SUBTRACTION ################################
  1273. # ############################################################
  1274. if self.ui.except_cb.get_value():
  1275. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1276. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1277. # TODO: Do something if this is None. Offer changing name?
  1278. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1279. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  1280. # isolation_geometry produces an envelope that is going on the left of the geometry
  1281. # (the copper features). To leave the least amount of burrs on the features
  1282. # the tool needs to travel on the right side of the features (this is called conventional milling)
  1283. # the first pass is the one cutting all of the features, so it needs to be reversed
  1284. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  1285. # to cut on the right side of the left over copper i.e on the left side of the features.
  1286. if follow:
  1287. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  1288. else:
  1289. try:
  1290. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  1291. except Exception as e:
  1292. log.debug('FlatCAMGerber.isolate().generate_envelope() --> %s' % str(e))
  1293. return 'fail'
  1294. if invert:
  1295. try:
  1296. pl = []
  1297. for p in geom:
  1298. if p is not None:
  1299. if isinstance(p, Polygon):
  1300. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  1301. elif isinstance(p, LinearRing):
  1302. pl.append(Polygon(p.coords[::-1]))
  1303. geom = MultiPolygon(pl)
  1304. except TypeError:
  1305. if isinstance(geom, Polygon) and geom is not None:
  1306. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  1307. elif isinstance(geom, LinearRing) and geom is not None:
  1308. geom = Polygon(geom.coords[::-1])
  1309. else:
  1310. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  1311. type(geom))
  1312. except Exception as e:
  1313. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  1314. return 'fail'
  1315. return geom
  1316. def area_subtraction(self, geo, subtractor_geo=None):
  1317. """
  1318. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  1319. :param geo: target geometry from which to subtract
  1320. :param subtractor_geo: geometry that acts as subtractor
  1321. :return:
  1322. """
  1323. new_geometry = []
  1324. target_geo = geo
  1325. if subtractor_geo:
  1326. sub_union = cascaded_union(subtractor_geo)
  1327. else:
  1328. name = self.ui.obj_combo.currentText()
  1329. subtractor_obj = self.app.collection.get_by_name(name)
  1330. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1331. try:
  1332. for geo_elem in target_geo:
  1333. if isinstance(geo_elem, Polygon):
  1334. for ring in self.poly2rings(geo_elem):
  1335. new_geo = ring.difference(sub_union)
  1336. if new_geo and not new_geo.is_empty:
  1337. new_geometry.append(new_geo)
  1338. elif isinstance(geo_elem, MultiPolygon):
  1339. for poly in geo_elem:
  1340. for ring in self.poly2rings(poly):
  1341. new_geo = ring.difference(sub_union)
  1342. if new_geo and not new_geo.is_empty:
  1343. new_geometry.append(new_geo)
  1344. elif isinstance(geo_elem, LineString):
  1345. new_geo = geo_elem.difference(sub_union)
  1346. if new_geo:
  1347. if not new_geo.is_empty:
  1348. new_geometry.append(new_geo)
  1349. elif isinstance(geo_elem, MultiLineString):
  1350. for line_elem in geo_elem:
  1351. new_geo = line_elem.difference(sub_union)
  1352. if new_geo and not new_geo.is_empty:
  1353. new_geometry.append(new_geo)
  1354. except TypeError:
  1355. if isinstance(target_geo, Polygon):
  1356. for ring in self.poly2rings(target_geo):
  1357. new_geo = ring.difference(sub_union)
  1358. if new_geo:
  1359. if not new_geo.is_empty:
  1360. new_geometry.append(new_geo)
  1361. elif isinstance(target_geo, LineString):
  1362. new_geo = target_geo.difference(sub_union)
  1363. if new_geo and not new_geo.is_empty:
  1364. new_geometry.append(new_geo)
  1365. elif isinstance(target_geo, MultiLineString):
  1366. for line_elem in target_geo:
  1367. new_geo = line_elem.difference(sub_union)
  1368. if new_geo and not new_geo.is_empty:
  1369. new_geometry.append(new_geo)
  1370. return new_geometry
  1371. def on_plot_cb_click(self, *args):
  1372. if self.muted_ui:
  1373. return
  1374. self.read_form_item('plot')
  1375. self.plot()
  1376. def on_solid_cb_click(self, *args):
  1377. if self.muted_ui:
  1378. return
  1379. self.read_form_item('solid')
  1380. self.plot()
  1381. def on_multicolored_cb_click(self, *args):
  1382. if self.muted_ui:
  1383. return
  1384. self.read_form_item('multicolored')
  1385. self.plot()
  1386. def on_follow_cb_click(self):
  1387. if self.muted_ui:
  1388. return
  1389. self.plot()
  1390. def on_aperture_table_visibility_change(self):
  1391. if self.ui.aperture_table_visibility_cb.isChecked():
  1392. # add the shapes storage for marking apertures
  1393. if self.build_aperture_storage is False:
  1394. self.build_aperture_storage = True
  1395. if self.app.is_legacy is False:
  1396. for ap_code in self.apertures:
  1397. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  1398. else:
  1399. for ap_code in self.apertures:
  1400. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  1401. name=self.options['name'] + str(ap_code))
  1402. self.ui.apertures_table.setVisible(True)
  1403. for ap in self.mark_shapes:
  1404. self.mark_shapes[ap].enabled = True
  1405. self.ui.mark_all_cb.setVisible(True)
  1406. self.ui.mark_all_cb.setChecked(False)
  1407. self.build_ui()
  1408. else:
  1409. self.ui.apertures_table.setVisible(False)
  1410. self.ui.mark_all_cb.setVisible(False)
  1411. # on hide disable all mark plots
  1412. try:
  1413. for row in range(self.ui.apertures_table.rowCount()):
  1414. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  1415. self.clear_plot_apertures()
  1416. # for ap in list(self.mark_shapes.keys()):
  1417. # # self.mark_shapes[ap].enabled = False
  1418. # del self.mark_shapes[ap]
  1419. except Exception as e:
  1420. log.debug(" FlatCAMGerber.on_aperture_visibility_changed() --> %s" % str(e))
  1421. def convert_units(self, units):
  1422. """
  1423. Converts the units of the object by scaling dimensions in all geometry
  1424. and options.
  1425. :param units: Units to which to convert the object: "IN" or "MM".
  1426. :type units: str
  1427. :return: None
  1428. :rtype: None
  1429. """
  1430. # units conversion to get a conversion should be done only once even if we found multiple
  1431. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  1432. if self.conversion_done is True:
  1433. log.debug("Gerber units conversion cancelled. Already done.")
  1434. return
  1435. log.debug("FlatCAMObj.FlatCAMGerber.convert_units()")
  1436. factor = Gerber.convert_units(self, units)
  1437. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  1438. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  1439. def plot(self, **kwargs):
  1440. """
  1441. :param kwargs: color and face_color
  1442. :return:
  1443. """
  1444. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  1445. # Does all the required setup and returns False
  1446. # if the 'ptint' option is set to False.
  1447. if not FlatCAMObj.plot(self):
  1448. return
  1449. if 'color' in kwargs:
  1450. color = kwargs['color']
  1451. else:
  1452. color = self.outline_color
  1453. if 'face_color' in kwargs:
  1454. face_color = kwargs['face_color']
  1455. else:
  1456. face_color = self.fill_color
  1457. if 'visible' not in kwargs:
  1458. visible = self.options['plot']
  1459. else:
  1460. visible = kwargs['visible']
  1461. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  1462. if self.ui.follow_cb.get_value():
  1463. geometry = self.follow_geometry
  1464. else:
  1465. geometry = self.solid_geometry
  1466. # Make sure geometry is iterable.
  1467. try:
  1468. __ = iter(geometry)
  1469. except TypeError:
  1470. geometry = [geometry]
  1471. if self.app.is_legacy is False:
  1472. def random_color():
  1473. r_color = np.random.rand(4)
  1474. r_color[3] = 1
  1475. return r_color
  1476. else:
  1477. def random_color():
  1478. while True:
  1479. r_color = np.random.rand(4)
  1480. r_color[3] = 1
  1481. new_color = '#'
  1482. for idx in range(len(r_color)):
  1483. new_color += '%x' % int(r_color[idx] * 255)
  1484. # do it until a valid color is generated
  1485. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  1486. # for a total of 9 chars
  1487. if len(new_color) == 9:
  1488. break
  1489. return new_color
  1490. try:
  1491. if self.options["solid"]:
  1492. for g in geometry:
  1493. if type(g) == Polygon or type(g) == LineString:
  1494. self.add_shape(shape=g, color=color,
  1495. face_color=random_color() if self.options['multicolored']
  1496. else face_color, visible=visible)
  1497. elif type(g) == Point:
  1498. pass
  1499. else:
  1500. try:
  1501. for el in g:
  1502. self.add_shape(shape=el, color=color,
  1503. face_color=random_color() if self.options['multicolored']
  1504. else face_color, visible=visible)
  1505. except TypeError:
  1506. self.add_shape(shape=g, color=color,
  1507. face_color=random_color() if self.options['multicolored']
  1508. else face_color, visible=visible)
  1509. else:
  1510. for g in geometry:
  1511. if type(g) == Polygon or type(g) == LineString:
  1512. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  1513. visible=visible)
  1514. elif type(g) == Point:
  1515. pass
  1516. else:
  1517. for el in g:
  1518. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  1519. visible=visible)
  1520. self.shapes.redraw(
  1521. # update_colors=(self.fill_color, self.outline_color),
  1522. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  1523. )
  1524. except (ObjectDeleted, AttributeError):
  1525. self.shapes.clear(update=True)
  1526. except Exception as e:
  1527. log.debug("FlatCAMGerber.plot() --> %s" % str(e))
  1528. # experimental plot() when the solid_geometry is stored in the self.apertures
  1529. def plot_aperture(self, run_thread=True, **kwargs):
  1530. """
  1531. :param run_thread: if True run the aperture plot as a thread in a worker
  1532. :param kwargs: color and face_color
  1533. :return:
  1534. """
  1535. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  1536. # Does all the required setup and returns False
  1537. # if the 'ptint' option is set to False.
  1538. # if not FlatCAMObj.plot(self):
  1539. # return
  1540. # for marking apertures, line color and fill color are the same
  1541. if 'color' in kwargs:
  1542. color = kwargs['color']
  1543. else:
  1544. color = self.app.defaults['gerber_plot_fill']
  1545. if 'marked_aperture' not in kwargs:
  1546. return
  1547. else:
  1548. aperture_to_plot_mark = kwargs['marked_aperture']
  1549. if aperture_to_plot_mark is None:
  1550. return
  1551. if 'visible' not in kwargs:
  1552. visibility = True
  1553. else:
  1554. visibility = kwargs['visible']
  1555. with self.app.proc_container.new(_("Plotting Apertures")):
  1556. def job_thread(app_obj):
  1557. try:
  1558. if aperture_to_plot_mark in self.apertures:
  1559. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  1560. if 'solid' in elem:
  1561. geo = elem['solid']
  1562. if type(geo) == Polygon or type(geo) == LineString:
  1563. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  1564. face_color=color, visible=visibility)
  1565. else:
  1566. for el in geo:
  1567. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  1568. face_color=color, visible=visibility)
  1569. self.mark_shapes[aperture_to_plot_mark].redraw()
  1570. except (ObjectDeleted, AttributeError):
  1571. self.clear_plot_apertures()
  1572. except Exception as e:
  1573. log.debug("FlatCAMGerber.plot_aperture() --> %s" % str(e))
  1574. if run_thread:
  1575. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  1576. else:
  1577. job_thread(self)
  1578. def clear_plot_apertures(self, aperture='all'):
  1579. """
  1580. :param aperture: string; aperture for which to clear the mark shapes
  1581. :return:
  1582. """
  1583. if self.mark_shapes:
  1584. if aperture == 'all':
  1585. for apid in list(self.apertures.keys()):
  1586. try:
  1587. if self.app.is_legacy is True:
  1588. self.mark_shapes[apid].clear(update=False)
  1589. else:
  1590. self.mark_shapes[apid].clear(update=True)
  1591. except Exception as e:
  1592. log.debug("FlatCAMGerber.clear_plot_apertures() 'all' --> %s" % str(e))
  1593. else:
  1594. try:
  1595. if self.app.is_legacy is True:
  1596. self.mark_shapes[aperture].clear(update=False)
  1597. else:
  1598. self.mark_shapes[aperture].clear(update=True)
  1599. except Exception as e:
  1600. log.debug("FlatCAMGerber.clear_plot_apertures() 'aperture' --> %s" % str(e))
  1601. def clear_mark_all(self):
  1602. self.ui.mark_all_cb.set_value(False)
  1603. self.marked_rows[:] = []
  1604. def on_mark_cb_click_table(self):
  1605. """
  1606. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  1607. :return:
  1608. """
  1609. self.ui_disconnect()
  1610. cw = self.sender()
  1611. try:
  1612. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  1613. cw_row = cw_index.row()
  1614. except AttributeError:
  1615. cw_row = 0
  1616. except TypeError:
  1617. return
  1618. self.marked_rows[:] = []
  1619. try:
  1620. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  1621. except AttributeError:
  1622. return
  1623. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  1624. self.marked_rows.append(True)
  1625. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1626. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1627. marked_aperture=aperture, visible=True, run_thread=True)
  1628. # self.mark_shapes[aperture].redraw()
  1629. else:
  1630. self.marked_rows.append(False)
  1631. self.clear_plot_apertures(aperture=aperture)
  1632. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1633. # if all the row mark's are enabled also enable the Mark All checkbox
  1634. cb_cnt = 0
  1635. total_row = self.ui.apertures_table.rowCount()
  1636. for row in range(total_row):
  1637. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1638. cb_cnt += 1
  1639. else:
  1640. cb_cnt -= 1
  1641. if cb_cnt < total_row:
  1642. self.ui.mark_all_cb.setChecked(False)
  1643. else:
  1644. self.ui.mark_all_cb.setChecked(True)
  1645. self.ui_connect()
  1646. def on_mark_all_click(self, signal):
  1647. self.ui_disconnect()
  1648. mark_all = self.ui.mark_all_cb.isChecked()
  1649. for row in range(self.ui.apertures_table.rowCount()):
  1650. # update the mark_rows list
  1651. if mark_all:
  1652. self.marked_rows.append(True)
  1653. else:
  1654. self.marked_rows[:] = []
  1655. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1656. mark_cb.setChecked(mark_all)
  1657. if mark_all:
  1658. for aperture in self.apertures:
  1659. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1660. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1661. marked_aperture=aperture, visible=True)
  1662. # HACK: enable/disable the grid for a better look
  1663. self.app.ui.grid_snap_btn.trigger()
  1664. self.app.ui.grid_snap_btn.trigger()
  1665. else:
  1666. self.clear_plot_apertures()
  1667. self.marked_rows[:] = []
  1668. self.ui_connect()
  1669. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1670. """
  1671. Creates a Gerber file content to be exported to a file.
  1672. :param whole: how many digits in the whole part of coordinates
  1673. :param fract: how many decimals in coordinates
  1674. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  1675. :param factor: factor to be applied onto the Gerber coordinates
  1676. :return: Gerber_code
  1677. """
  1678. log.debug("FlatCAMGerber.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  1679. def tz_format(x, y, fac):
  1680. x_c = x * fac
  1681. y_c = y * fac
  1682. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1683. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1684. # extract whole part and decimal part
  1685. x_form = x_form.partition('.')
  1686. y_form = y_form.partition('.')
  1687. # left padd the 'whole' part with zeros
  1688. x_whole = x_form[0].rjust(whole, '0')
  1689. y_whole = y_form[0].rjust(whole, '0')
  1690. # restore the coordinate padded in the left with 0 and added the decimal part
  1691. # without the decinal dot
  1692. x_form = x_whole + x_form[2]
  1693. y_form = y_whole + y_form[2]
  1694. return x_form, y_form
  1695. def lz_format(x, y, fac):
  1696. x_c = x * fac
  1697. y_c = y * fac
  1698. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1699. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1700. # pad with rear zeros
  1701. x_form.ljust(length, '0')
  1702. y_form.ljust(length, '0')
  1703. return x_form, y_form
  1704. # Gerber code is stored here
  1705. gerber_code = ''
  1706. # apertures processing
  1707. try:
  1708. length = whole + fract
  1709. if '0' in self.apertures:
  1710. if 'geometry' in self.apertures['0']:
  1711. for geo_elem in self.apertures['0']['geometry']:
  1712. if 'solid' in geo_elem:
  1713. geo = geo_elem['solid']
  1714. if not geo.is_empty:
  1715. gerber_code += 'G36*\n'
  1716. geo_coords = list(geo.exterior.coords)
  1717. # first command is a move with pen-up D02 at the beginning of the geo
  1718. if g_zeros == 'T':
  1719. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1720. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1721. yform=y_formatted)
  1722. else:
  1723. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1724. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1725. yform=y_formatted)
  1726. for coord in geo_coords[1:]:
  1727. if g_zeros == 'T':
  1728. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1729. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1730. yform=y_formatted)
  1731. else:
  1732. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1733. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1734. yform=y_formatted)
  1735. gerber_code += 'D02*\n'
  1736. gerber_code += 'G37*\n'
  1737. clear_list = list(geo.interiors)
  1738. if clear_list:
  1739. gerber_code += '%LPC*%\n'
  1740. for clear_geo in clear_list:
  1741. gerber_code += 'G36*\n'
  1742. geo_coords = list(clear_geo.coords)
  1743. # first command is a move with pen-up D02 at the beginning of the geo
  1744. if g_zeros == 'T':
  1745. x_formatted, y_formatted = tz_format(
  1746. geo_coords[0][0], geo_coords[0][1], factor)
  1747. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1748. yform=y_formatted)
  1749. else:
  1750. x_formatted, y_formatted = lz_format(
  1751. geo_coords[0][0], geo_coords[0][1], factor)
  1752. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1753. yform=y_formatted)
  1754. prev_coord = geo_coords[0]
  1755. for coord in geo_coords[1:]:
  1756. if coord != prev_coord:
  1757. if g_zeros == 'T':
  1758. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1759. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1760. yform=y_formatted)
  1761. else:
  1762. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1763. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1764. yform=y_formatted)
  1765. prev_coord = coord
  1766. gerber_code += 'D02*\n'
  1767. gerber_code += 'G37*\n'
  1768. gerber_code += '%LPD*%\n'
  1769. if 'clear' in geo_elem:
  1770. geo = geo_elem['clear']
  1771. if not geo.is_empty:
  1772. gerber_code += '%LPC*%\n'
  1773. gerber_code += 'G36*\n'
  1774. geo_coords = list(geo.exterior.coords)
  1775. # first command is a move with pen-up D02 at the beginning of the geo
  1776. if g_zeros == 'T':
  1777. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1778. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1779. yform=y_formatted)
  1780. else:
  1781. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1782. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1783. yform=y_formatted)
  1784. prev_coord = geo_coords[0]
  1785. for coord in geo_coords[1:]:
  1786. if coord != prev_coord:
  1787. if g_zeros == 'T':
  1788. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1789. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1790. yform=y_formatted)
  1791. else:
  1792. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1793. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1794. yform=y_formatted)
  1795. prev_coord = coord
  1796. gerber_code += 'D02*\n'
  1797. gerber_code += 'G37*\n'
  1798. gerber_code += '%LPD*%\n'
  1799. for apid in self.apertures:
  1800. if apid == '0':
  1801. continue
  1802. else:
  1803. gerber_code += 'D%s*\n' % str(apid)
  1804. if 'geometry' in self.apertures[apid]:
  1805. for geo_elem in self.apertures[apid]['geometry']:
  1806. if 'follow' in geo_elem:
  1807. geo = geo_elem['follow']
  1808. if not geo.is_empty:
  1809. if isinstance(geo, Point):
  1810. if g_zeros == 'T':
  1811. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1812. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1813. yform=y_formatted)
  1814. else:
  1815. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1816. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1817. yform=y_formatted)
  1818. else:
  1819. geo_coords = list(geo.coords)
  1820. # first command is a move with pen-up D02 at the beginning of the geo
  1821. if g_zeros == 'T':
  1822. x_formatted, y_formatted = tz_format(
  1823. geo_coords[0][0], geo_coords[0][1], factor)
  1824. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1825. yform=y_formatted)
  1826. else:
  1827. x_formatted, y_formatted = lz_format(
  1828. geo_coords[0][0], geo_coords[0][1], factor)
  1829. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1830. yform=y_formatted)
  1831. prev_coord = geo_coords[0]
  1832. for coord in geo_coords[1:]:
  1833. if coord != prev_coord:
  1834. if g_zeros == 'T':
  1835. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1836. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1837. yform=y_formatted)
  1838. else:
  1839. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1840. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1841. yform=y_formatted)
  1842. prev_coord = coord
  1843. # gerber_code += "D02*\n"
  1844. if 'clear' in geo_elem:
  1845. gerber_code += '%LPC*%\n'
  1846. geo = geo_elem['clear']
  1847. if not geo.is_empty:
  1848. if isinstance(geo, Point):
  1849. if g_zeros == 'T':
  1850. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1851. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1852. yform=y_formatted)
  1853. else:
  1854. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1855. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1856. yform=y_formatted)
  1857. else:
  1858. geo_coords = list(geo.coords)
  1859. # first command is a move with pen-up D02 at the beginning of the geo
  1860. if g_zeros == 'T':
  1861. x_formatted, y_formatted = tz_format(
  1862. geo_coords[0][0], geo_coords[0][1], factor)
  1863. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1864. yform=y_formatted)
  1865. else:
  1866. x_formatted, y_formatted = lz_format(
  1867. geo_coords[0][0], geo_coords[0][1], factor)
  1868. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1869. yform=y_formatted)
  1870. prev_coord = geo_coords[0]
  1871. for coord in geo_coords[1:]:
  1872. if coord != prev_coord:
  1873. if g_zeros == 'T':
  1874. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1875. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1876. yform=y_formatted)
  1877. else:
  1878. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1879. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1880. yform=y_formatted)
  1881. prev_coord = coord
  1882. # gerber_code += "D02*\n"
  1883. gerber_code += '%LPD*%\n'
  1884. except Exception as e:
  1885. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> %s" % str(e))
  1886. if not self.apertures:
  1887. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> Gerber Object is empty: no apertures.")
  1888. return 'fail'
  1889. return gerber_code
  1890. def mirror(self, axis, point):
  1891. Gerber.mirror(self, axis=axis, point=point)
  1892. self.replotApertures.emit()
  1893. def offset(self, vect):
  1894. Gerber.offset(self, vect=vect)
  1895. self.replotApertures.emit()
  1896. def rotate(self, angle, point):
  1897. Gerber.rotate(self, angle=angle, point=point)
  1898. self.replotApertures.emit()
  1899. def scale(self, xfactor, yfactor=None, point=None):
  1900. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1901. self.replotApertures.emit()
  1902. def skew(self, angle_x, angle_y, point):
  1903. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1904. self.replotApertures.emit()
  1905. def buffer(self, distance, join, factor=None):
  1906. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1907. self.replotApertures.emit()
  1908. def serialize(self):
  1909. return {
  1910. "options": self.options,
  1911. "kind": self.kind
  1912. }
  1913. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1914. """
  1915. Represents Excellon/Drill code.
  1916. """
  1917. ui_type = ExcellonObjectUI
  1918. optionChanged = QtCore.pyqtSignal(str)
  1919. def __init__(self, name):
  1920. self.decimals = self.app.decimals
  1921. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  1922. Excellon.__init__(self, geo_steps_per_circle=self.circle_steps)
  1923. FlatCAMObj.__init__(self, name)
  1924. self.kind = "excellon"
  1925. self.options.update({
  1926. "plot": True,
  1927. "solid": False,
  1928. "drillz": -0.1,
  1929. "multidepth": False,
  1930. "depthperpass": 0.7,
  1931. "travelz": 0.1,
  1932. "feedrate": 5.0,
  1933. "feedrate_rapid": 5.0,
  1934. "tooldia": 0.1,
  1935. "slot_tooldia": 0.1,
  1936. "toolchange": False,
  1937. "toolchangez": 1.0,
  1938. "toolchangexy": "0.0, 0.0",
  1939. "endz": 2.0,
  1940. "startz": None,
  1941. "spindlespeed": 0,
  1942. "dwell": True,
  1943. "dwelltime": 1000,
  1944. "ppname_e": 'defaults',
  1945. "z_pdepth": -0.02,
  1946. "feedrate_probe": 3.0,
  1947. "optimization_type": "R",
  1948. "gcode_type": "drills"
  1949. })
  1950. # TODO: Document this.
  1951. self.tool_cbs = dict()
  1952. # dict to hold the tool number as key and tool offset as value
  1953. self.tool_offset = dict()
  1954. # default set of data to be added to each tool in self.tools as self.tools[tool]['data'] = self.default_data
  1955. self.default_data = dict()
  1956. # fill in self.default_data values from self.options
  1957. for opt_key, opt_val in self.app.options.items():
  1958. if opt_key.find('excellon_') == 0:
  1959. self.default_data[opt_key] = deepcopy(opt_val)
  1960. for opt_key, opt_val in self.app.options.items():
  1961. if opt_key.find('geometry_') == 0:
  1962. self.default_data[opt_key] = deepcopy(opt_val)
  1963. # variable to store the total amount of drills per job
  1964. self.tot_drill_cnt = 0
  1965. self.tool_row = 0
  1966. # variable to store the total amount of slots per job
  1967. self.tot_slot_cnt = 0
  1968. self.tool_row_slots = 0
  1969. # variable to store the distance travelled
  1970. self.travel_distance = 0.0
  1971. # store the source file here
  1972. self.source_file = ""
  1973. self.multigeo = False
  1974. self.units_found = self.app.defaults['units']
  1975. self.fill_color = self.app.defaults['excellon_plot_fill']
  1976. self.outline_color = self.app.defaults['excellon_plot_line']
  1977. self.alpha_level = 'bf'
  1978. # Attributes to be included in serialization
  1979. # Always append to it because it carries contents
  1980. # from predecessors.
  1981. self.ser_attrs += ['options', 'kind']
  1982. def merge(self, exc_list, exc_final):
  1983. """
  1984. Merge Excellon objects found in exc_list parameter into exc_final object.
  1985. Options are always copied from source .
  1986. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1987. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1988. tool_name to be used in the final Excellon object, exc_final.
  1989. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1990. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1991. :param exc_final: Destination FlatCAMExcellon object.
  1992. :return: None
  1993. """
  1994. try:
  1995. decimals_exc = self.decimals
  1996. except AttributeError:
  1997. decimals_exc = 4
  1998. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1999. flag_order = False
  2000. try:
  2001. flattened_list = list(itertools.chain(*exc_list))
  2002. except TypeError:
  2003. flattened_list = exc_list
  2004. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  2005. # values will be list of Shapely Points; for drills
  2006. custom_dict_drills = {}
  2007. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  2008. # values will be list of Shapely Points; for slots
  2009. custom_dict_slots = {}
  2010. for exc in flattened_list:
  2011. # copy options of the current excellon obj to the final excellon obj
  2012. for option in exc.options:
  2013. if option is not 'name':
  2014. try:
  2015. exc_final.options[option] = exc.options[option]
  2016. except Exception:
  2017. exc.app.log.warning("Failed to copy option.", option)
  2018. for drill in exc.drills:
  2019. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[drill['tool']]['C']))
  2020. if exc_tool_dia not in custom_dict_drills:
  2021. custom_dict_drills[exc_tool_dia] = [drill['point']]
  2022. else:
  2023. custom_dict_drills[exc_tool_dia].append(drill['point'])
  2024. for slot in exc.slots:
  2025. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[slot['tool']]['C']))
  2026. if exc_tool_dia not in custom_dict_slots:
  2027. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  2028. else:
  2029. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  2030. # add the zeros and units to the exc_final object
  2031. exc_final.zeros = exc.zeros
  2032. exc_final.units = exc.units
  2033. # ##########################################
  2034. # Here we add data to the exc_final object #
  2035. # ##########################################
  2036. # variable to make tool_name for the tools
  2037. current_tool = 0
  2038. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  2039. # drills
  2040. for tool_dia in custom_dict_drills:
  2041. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  2042. current_tool += 1
  2043. tool_name = str(current_tool)
  2044. spec = {"C": float(tool_dia)}
  2045. exc_final.tools[tool_name] = spec
  2046. # rebuild the drills list of dict's that belong to the exc_final object
  2047. for point in custom_dict_drills[tool_dia]:
  2048. exc_final.drills.append(
  2049. {
  2050. "point": point,
  2051. "tool": str(current_tool)
  2052. }
  2053. )
  2054. # The tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  2055. # of two Shapely Points in case of slots
  2056. for tool_dia in custom_dict_slots:
  2057. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  2058. # but only if there are no drills
  2059. if not exc_final.tools:
  2060. current_tool += 1
  2061. tool_name = str(current_tool)
  2062. spec = {"C": float(tool_dia)}
  2063. exc_final.tools[tool_name] = spec
  2064. else:
  2065. dia_list = []
  2066. for v in exc_final.tools.values():
  2067. dia_list.append(float(v["C"]))
  2068. if tool_dia not in dia_list:
  2069. flag_order = True
  2070. current_tool = len(dia_list) + 1
  2071. tool_name = str(current_tool)
  2072. spec = {"C": float(tool_dia)}
  2073. exc_final.tools[tool_name] = spec
  2074. else:
  2075. for k, v in exc_final.tools.items():
  2076. if v["C"] == tool_dia:
  2077. current_tool = int(k)
  2078. break
  2079. # rebuild the slots list of dict's that belong to the exc_final object
  2080. for point in custom_dict_slots[tool_dia]:
  2081. exc_final.slots.append(
  2082. {
  2083. "start": point[0],
  2084. "stop": point[1],
  2085. "tool": str(current_tool)
  2086. }
  2087. )
  2088. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  2089. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  2090. current_tool = 0
  2091. if flag_order is True:
  2092. dia_list = []
  2093. temp_drills = []
  2094. temp_slots = []
  2095. temp_tools = {}
  2096. for v in exc_final.tools.values():
  2097. dia_list.append(float(v["C"]))
  2098. dia_list.sort()
  2099. for ordered_dia in dia_list:
  2100. current_tool += 1
  2101. tool_name_temp = str(current_tool)
  2102. spec_temp = {"C": float(ordered_dia)}
  2103. temp_tools[tool_name_temp] = spec_temp
  2104. for drill in exc_final.drills:
  2105. exc_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[drill['tool']]['C']))
  2106. if exc_tool_dia == ordered_dia:
  2107. temp_drills.append(
  2108. {
  2109. "point": drill["point"],
  2110. "tool": str(current_tool)
  2111. }
  2112. )
  2113. for slot in exc_final.slots:
  2114. slot_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[slot['tool']]['C']))
  2115. if slot_tool_dia == ordered_dia:
  2116. temp_slots.append(
  2117. {
  2118. "start": slot["start"],
  2119. "stop": slot["stop"],
  2120. "tool": str(current_tool)
  2121. }
  2122. )
  2123. # delete the exc_final tools, drills and slots
  2124. exc_final.tools = dict()
  2125. exc_final.drills[:] = []
  2126. exc_final.slots[:] = []
  2127. # update the exc_final tools, drills and slots with the ordered values
  2128. exc_final.tools = temp_tools
  2129. exc_final.drills[:] = temp_drills
  2130. exc_final.slots[:] = temp_slots
  2131. # create the geometry for the exc_final object
  2132. exc_final.create_geometry()
  2133. def build_ui(self):
  2134. FlatCAMObj.build_ui(self)
  2135. self.units = self.app.defaults['units'].upper()
  2136. for row in range(self.ui.tools_table.rowCount()):
  2137. try:
  2138. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2139. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2140. offset_spin_widget.valueChanged.disconnect()
  2141. except (TypeError, AttributeError):
  2142. pass
  2143. n = len(self.tools)
  2144. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  2145. self.ui.tools_table.setRowCount(n + 2)
  2146. self.tot_drill_cnt = 0
  2147. self.tot_slot_cnt = 0
  2148. self.tool_row = 0
  2149. sort = []
  2150. for k, v in list(self.tools.items()):
  2151. sort.append((k, v.get('C')))
  2152. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2153. tools = [i[0] for i in sorted_tools]
  2154. for tool_no in tools:
  2155. drill_cnt = 0 # variable to store the nr of drills per tool
  2156. slot_cnt = 0 # variable to store the nr of slots per tool
  2157. # Find no of drills for the current tool
  2158. for drill in self.drills:
  2159. if drill['tool'] == tool_no:
  2160. drill_cnt += 1
  2161. self.tot_drill_cnt += drill_cnt
  2162. # Find no of slots for the current tool
  2163. for slot in self.slots:
  2164. if slot['tool'] == tool_no:
  2165. slot_cnt += 1
  2166. self.tot_slot_cnt += slot_cnt
  2167. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  2168. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2169. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.tools[tool_no]['C']))
  2170. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2171. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  2172. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2173. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  2174. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  2175. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  2176. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2177. try:
  2178. t_offset = self.tool_offset[float('%.*f' % (self.decimals, float(self.tools[tool_no]['C'])))]
  2179. except KeyError:
  2180. t_offset = self.app.defaults['excellon_offset']
  2181. tool_offset_item = FCDoubleSpinner()
  2182. tool_offset_item.set_precision(self.decimals)
  2183. tool_offset_item.set_range(-9999.9999, 9999.9999)
  2184. tool_offset_item.setWrapping(True)
  2185. tool_offset_item.setSingleStep(0.1) if self.units == 'MM' else tool_offset_item.setSingleStep(0.01)
  2186. tool_offset_item.set_value(t_offset)
  2187. plot_item = FCCheckBox()
  2188. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2189. if self.ui.plot_cb.isChecked():
  2190. plot_item.setChecked(True)
  2191. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item) # Tool name/id
  2192. self.ui.tools_table.setItem(self.tool_row, 1, dia_item) # Diameter
  2193. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item) # Number of drills per tool
  2194. self.ui.tools_table.setItem(self.tool_row, 3, slot_count_item) # Number of drills per tool
  2195. self.ui.tools_table.setCellWidget(self.tool_row, 4, tool_offset_item) # Tool offset
  2196. empty_plot_item = QtWidgets.QTableWidgetItem('')
  2197. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2198. self.ui.tools_table.setItem(self.tool_row, 5, empty_plot_item)
  2199. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  2200. self.tool_row += 1
  2201. # add a last row with the Total number of drills
  2202. empty_1 = QtWidgets.QTableWidgetItem('')
  2203. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2204. empty_1_1 = QtWidgets.QTableWidgetItem('')
  2205. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2206. empty_1_2 = QtWidgets.QTableWidgetItem('')
  2207. empty_1_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2208. empty_1_3 = QtWidgets.QTableWidgetItem('')
  2209. empty_1_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2210. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  2211. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  2212. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2213. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2214. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  2215. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  2216. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  2217. self.ui.tools_table.setItem(self.tool_row, 3, empty_1_1)
  2218. self.ui.tools_table.setItem(self.tool_row, 4, empty_1_2)
  2219. self.ui.tools_table.setItem(self.tool_row, 5, empty_1_3)
  2220. font = QtGui.QFont()
  2221. font.setBold(True)
  2222. font.setWeight(75)
  2223. for k in [1, 2]:
  2224. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  2225. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  2226. self.tool_row += 1
  2227. # add a last row with the Total number of slots
  2228. empty_2 = QtWidgets.QTableWidgetItem('')
  2229. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2230. empty_2_1 = QtWidgets.QTableWidgetItem('')
  2231. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2232. empty_2_2 = QtWidgets.QTableWidgetItem('')
  2233. empty_2_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2234. empty_2_3 = QtWidgets.QTableWidgetItem('')
  2235. empty_2_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2236. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  2237. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  2238. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2239. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2240. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  2241. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  2242. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  2243. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  2244. self.ui.tools_table.setItem(self.tool_row, 4, empty_2_2)
  2245. self.ui.tools_table.setItem(self.tool_row, 5, empty_2_3)
  2246. for kl in [1, 2, 3]:
  2247. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  2248. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  2249. # sort the tool diameter column
  2250. # self.ui.tools_table.sortItems(1)
  2251. # all the tools are selected by default
  2252. self.ui.tools_table.selectColumn(0)
  2253. self.ui.tools_table.resizeColumnsToContents()
  2254. self.ui.tools_table.resizeRowsToContents()
  2255. vertical_header = self.ui.tools_table.verticalHeader()
  2256. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2257. vertical_header.hide()
  2258. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2259. horizontal_header = self.ui.tools_table.horizontalHeader()
  2260. horizontal_header.setMinimumSectionSize(10)
  2261. horizontal_header.setDefaultSectionSize(70)
  2262. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2263. horizontal_header.resizeSection(0, 20)
  2264. if self.app.defaults["global_app_level"] == 'b':
  2265. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2266. else:
  2267. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  2268. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  2269. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2270. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  2271. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  2272. horizontal_header.resizeSection(5, 17)
  2273. self.ui.tools_table.setColumnWidth(5, 17)
  2274. # horizontal_header.setStretchLastSection(True)
  2275. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2276. # horizontal_header.setStretchLastSection(True)
  2277. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2278. self.ui.tools_table.setSortingEnabled(False)
  2279. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  2280. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  2281. if not self.drills:
  2282. self.ui.tooldia_entry.hide()
  2283. self.ui.generate_milling_button.hide()
  2284. else:
  2285. self.ui.tooldia_entry.show()
  2286. self.ui.generate_milling_button.show()
  2287. if not self.slots:
  2288. self.ui.slot_tooldia_entry.hide()
  2289. self.ui.generate_milling_slots_button.hide()
  2290. else:
  2291. self.ui.slot_tooldia_entry.show()
  2292. self.ui.generate_milling_slots_button.show()
  2293. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  2294. for row in range(self.ui.tools_table.rowCount()):
  2295. try:
  2296. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2297. offset_spin_widget.valueChanged.connect(self.on_tool_offset_edit)
  2298. except (TypeError, AttributeError):
  2299. pass
  2300. # set the text on tool_data_label after loading the object
  2301. sel_rows = list()
  2302. sel_items = self.ui.tools_table.selectedItems()
  2303. for it in sel_items:
  2304. sel_rows.append(it.row())
  2305. if len(sel_rows) > 1:
  2306. self.ui.tool_data_label.setText(
  2307. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  2308. )
  2309. self.ui_connect()
  2310. def set_ui(self, ui):
  2311. """
  2312. Configures the user interface for this object.
  2313. Connects options to form fields.
  2314. :param ui: User interface object.
  2315. :type ui: ExcellonObjectUI
  2316. :return: None
  2317. """
  2318. FlatCAMObj.set_ui(self, ui)
  2319. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  2320. self.units = self.app.defaults['units'].upper()
  2321. self.form_fields.update({
  2322. "plot": self.ui.plot_cb,
  2323. "solid": self.ui.solid_cb,
  2324. "drillz": self.ui.cutz_entry,
  2325. "multidepth": self.ui.mpass_cb,
  2326. "depthperpass": self.ui.maxdepth_entry,
  2327. "travelz": self.ui.travelz_entry,
  2328. "feedrate": self.ui.feedrate_z_entry,
  2329. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  2330. "tooldia": self.ui.tooldia_entry,
  2331. "slot_tooldia": self.ui.slot_tooldia_entry,
  2332. "toolchange": self.ui.toolchange_cb,
  2333. "toolchangez": self.ui.toolchangez_entry,
  2334. "spindlespeed": self.ui.spindlespeed_entry,
  2335. "dwell": self.ui.dwell_cb,
  2336. "dwelltime": self.ui.dwelltime_entry,
  2337. "startz": self.ui.estartz_entry,
  2338. "endz": self.ui.endz_entry,
  2339. "ppname_e": self.ui.pp_excellon_name_cb,
  2340. "z_pdepth": self.ui.pdepth_entry,
  2341. "feedrate_probe": self.ui.feedrate_probe_entry,
  2342. "gcode_type": self.ui.excellon_gcode_type_radio
  2343. })
  2344. for name in list(self.app.preprocessors.keys()):
  2345. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  2346. if name == 'hpgl':
  2347. continue
  2348. self.ui.pp_excellon_name_cb.addItem(name)
  2349. # Fill form fields
  2350. self.to_form()
  2351. # update the changes in UI depending on the selected preprocessor in Preferences
  2352. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  2353. # self.ui.pp_excellon_name_cb combobox
  2354. self.on_pp_changed()
  2355. # initialize the dict that holds the tools offset
  2356. t_default_offset = self.app.defaults["excellon_offset"]
  2357. if not self.tool_offset:
  2358. for value in self.tools.values():
  2359. dia = float('%.*f' % (self.decimals, float(value['C'])))
  2360. self.tool_offset[dia] = t_default_offset
  2361. # Show/Hide Advanced Options
  2362. if self.app.defaults["global_app_level"] == 'b':
  2363. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  2364. self.ui.tools_table.setColumnHidden(4, True)
  2365. self.ui.tools_table.setColumnHidden(5, True)
  2366. self.ui.estartz_label.hide()
  2367. self.ui.estartz_entry.hide()
  2368. self.ui.feedrate_rapid_label.hide()
  2369. self.ui.feedrate_rapid_entry.hide()
  2370. self.ui.pdepth_label.hide()
  2371. self.ui.pdepth_entry.hide()
  2372. self.ui.feedrate_probe_label.hide()
  2373. self.ui.feedrate_probe_entry.hide()
  2374. else:
  2375. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  2376. assert isinstance(self.ui, ExcellonObjectUI), \
  2377. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  2378. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2379. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  2380. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  2381. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  2382. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  2383. self.on_operation_type(val='drill')
  2384. self.ui.operation_radio.activated_custom.connect(self.on_operation_type)
  2385. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  2386. self.units_found = self.app.defaults['units']
  2387. def ui_connect(self):
  2388. # selective plotting
  2389. for row in range(self.ui.tools_table.rowCount() - 2):
  2390. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  2391. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2392. # rows selected
  2393. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2394. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  2395. def ui_disconnect(self):
  2396. # selective plotting
  2397. for row in range(self.ui.tools_table.rowCount()):
  2398. try:
  2399. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  2400. except (TypeError, AttributeError):
  2401. pass
  2402. try:
  2403. self.ui.plot_cb.stateChanged.disconnect()
  2404. except (TypeError, AttributeError):
  2405. pass
  2406. # rows selected
  2407. try:
  2408. self.ui.tools_table.clicked.disconnect()
  2409. except (TypeError, AttributeError):
  2410. pass
  2411. try:
  2412. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2413. except (TypeError, AttributeError):
  2414. pass
  2415. def on_row_selection_change(self):
  2416. self.update_ui()
  2417. def update_ui(self, row=None):
  2418. self.ui_disconnect()
  2419. if row is None:
  2420. sel_rows = list()
  2421. sel_items = self.ui.tools_table.selectedItems()
  2422. for it in sel_items:
  2423. sel_rows.append(it.row())
  2424. else:
  2425. sel_rows = row if type(row) == list else [row]
  2426. if not sel_rows:
  2427. self.ui.tool_data_label.setText(
  2428. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  2429. )
  2430. self.ui.generate_cnc_button.setDisabled(True)
  2431. self.ui.generate_milling_button.setDisabled(True)
  2432. self.ui.generate_milling_slots_button.setDisabled(True)
  2433. self.ui_connect()
  2434. return
  2435. else:
  2436. self.ui.generate_cnc_button.setDisabled(False)
  2437. self.ui.generate_milling_button.setDisabled(False)
  2438. self.ui.generate_milling_slots_button.setDisabled(False)
  2439. if len(sel_rows) == 1:
  2440. # update the QLabel that shows for which Tool we have the parameters in the UI form
  2441. tooluid = int(self.ui.tools_table.item(sel_rows[0], 0).text())
  2442. self.ui.tool_data_label.setText(
  2443. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  2444. )
  2445. else:
  2446. self.ui.tool_data_label.setText(
  2447. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  2448. )
  2449. for c_row in sel_rows:
  2450. # populate the form with the data from the tool associated with the row parameter
  2451. try:
  2452. item = self.ui.tools_table.item(c_row, 0)
  2453. if type(item) is not None:
  2454. tooluid = int(item.text())
  2455. else:
  2456. self.ui_connect()
  2457. return
  2458. except Exception as e:
  2459. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2460. self.ui_connect()
  2461. return
  2462. # try:
  2463. # # set the form with data from the newly selected tool
  2464. # for tooluid_key, tooluid_value in list(self.tools.items()):
  2465. # if int(tooluid_key) == tooluid:
  2466. # for key, value in tooluid_value.items():
  2467. # if key == 'data':
  2468. # form_value_storage = tooluid_value[key]
  2469. # self.update_form(form_value_storage)
  2470. # except Exception as e:
  2471. # log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2472. self.ui_connect()
  2473. def on_operation_type(self, val):
  2474. if val == 'mill':
  2475. self.ui.mill_type_label.show()
  2476. self.ui.mill_type_radio.show()
  2477. self.ui.mill_dia_label.show()
  2478. self.ui.mill_dia_entry.show()
  2479. self.ui.frxylabel.show()
  2480. self.ui.xyfeedrate_entry.show()
  2481. self.ui.extracut_cb.show()
  2482. self.ui.e_cut_entry.show()
  2483. # if 'laser' not in self.ui.pp_excellon_name_cb.get_value().lower():
  2484. # self.ui.mpass_cb.show()
  2485. # self.ui.maxdepth_entry.show()
  2486. else:
  2487. self.ui.mill_type_label.hide()
  2488. self.ui.mill_type_radio.hide()
  2489. self.ui.mill_dia_label.hide()
  2490. self.ui.mill_dia_entry.hide()
  2491. # self.ui.mpass_cb.hide()
  2492. # self.ui.maxdepth_entry.hide()
  2493. self.ui.frxylabel.hide()
  2494. self.ui.xyfeedrate_entry.hide()
  2495. self.ui.extracut_cb.hide()
  2496. self.ui.e_cut_entry.hide()
  2497. def on_tool_offset_edit(self):
  2498. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2499. for row in range(self.ui.tools_table.rowCount()):
  2500. try:
  2501. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2502. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2503. offset_spin_widget.valueChanged.disconnect()
  2504. except (TypeError, AttributeError):
  2505. pass
  2506. self.units = self.app.defaults['units'].upper()
  2507. self.is_modified = True
  2508. row_of_item_changed = self.ui.tools_table.currentRow()
  2509. dia = float('%.*f' % (self.decimals, float(self.ui.tools_table.item(row_of_item_changed, 1).text())))
  2510. self.tool_offset[dia] = self.sender().get_value()
  2511. # we reactivate the signals after the after the tool editing
  2512. for row in range(self.ui.tools_table.rowCount()):
  2513. try:
  2514. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2515. offset_spin_widget.valueChanged.connect(self.on_tool_offset_edit)
  2516. except (TypeError, AttributeError):
  2517. pass
  2518. def get_selected_tools_list(self):
  2519. """
  2520. Returns the keys to the self.tools dictionary corresponding
  2521. to the selections on the tool list in the GUI.
  2522. :return: List of tools.
  2523. :rtype: list
  2524. """
  2525. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  2526. def get_selected_tools_table_items(self):
  2527. """
  2528. Returns a list of lists, each list in the list is made out of row elements
  2529. :return: List of table_tools items.
  2530. :rtype: list
  2531. """
  2532. table_tools_items = []
  2533. for x in self.ui.tools_table.selectedItems():
  2534. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  2535. # which does not have text
  2536. txt = ''
  2537. elem = list()
  2538. for column in range(0, self.ui.tools_table.columnCount() - 1):
  2539. try:
  2540. txt = self.ui.tools_table.item(x.row(), column).text()
  2541. except AttributeError:
  2542. try:
  2543. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  2544. except AttributeError:
  2545. pass
  2546. elem.append(txt)
  2547. table_tools_items.append(deepcopy(elem))
  2548. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  2549. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  2550. for item in table_tools_items:
  2551. item[0] = str(item[0])
  2552. return table_tools_items
  2553. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1, slot_type='routing'):
  2554. """
  2555. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  2556. :return: has_slots and Excellon_code
  2557. """
  2558. excellon_code = ''
  2559. # store here if the file has slots, return 1 if any slots, 0 if only drills
  2560. has_slots = 0
  2561. # drills processing
  2562. try:
  2563. if self.drills:
  2564. length = whole + fract
  2565. for tool in self.tools:
  2566. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  2567. for drill in self.drills:
  2568. if form == 'dec' and tool == drill['tool']:
  2569. drill_x = drill['point'].x * factor
  2570. drill_y = drill['point'].y * factor
  2571. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  2572. elif e_zeros == 'LZ' and tool == drill['tool']:
  2573. drill_x = drill['point'].x * factor
  2574. drill_y = drill['point'].y * factor
  2575. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  2576. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  2577. # extract whole part and decimal part
  2578. exc_x_formatted = exc_x_formatted.partition('.')
  2579. exc_y_formatted = exc_y_formatted.partition('.')
  2580. # left padd the 'whole' part with zeros
  2581. x_whole = exc_x_formatted[0].rjust(whole, '0')
  2582. y_whole = exc_y_formatted[0].rjust(whole, '0')
  2583. # restore the coordinate padded in the left with 0 and added the decimal part
  2584. # without the decinal dot
  2585. exc_x_formatted = x_whole + exc_x_formatted[2]
  2586. exc_y_formatted = y_whole + exc_y_formatted[2]
  2587. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2588. yform=exc_y_formatted)
  2589. elif tool == drill['tool']:
  2590. drill_x = drill['point'].x * factor
  2591. drill_y = drill['point'].y * factor
  2592. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  2593. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  2594. # pad with rear zeros
  2595. exc_x_formatted.ljust(length, '0')
  2596. exc_y_formatted.ljust(length, '0')
  2597. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2598. yform=exc_y_formatted)
  2599. except Exception as e:
  2600. log.debug(str(e))
  2601. # slots processing
  2602. try:
  2603. if self.slots:
  2604. has_slots = 1
  2605. for tool in self.tools:
  2606. excellon_code += 'G05\n'
  2607. if int(tool) < 10:
  2608. excellon_code += 'T0' + str(tool) + '\n'
  2609. else:
  2610. excellon_code += 'T' + str(tool) + '\n'
  2611. for slot in self.slots:
  2612. if form == 'dec' and tool == slot['tool']:
  2613. start_slot_x = slot['start'].x * factor
  2614. start_slot_y = slot['start'].y * factor
  2615. stop_slot_x = slot['stop'].x * factor
  2616. stop_slot_y = slot['stop'].y * factor
  2617. if slot_type == 'routing':
  2618. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  2619. start_slot_y,
  2620. dec=fract)
  2621. excellon_code += "G01X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  2622. stop_slot_y,
  2623. dec=fract)
  2624. elif slot_type == 'drilling':
  2625. excellon_code += "X{:.{dec}f}Y{:.{dec}f}G85X{:.{dec}f}Y{:.{dec}f}\nG05\n".format(
  2626. start_slot_x, start_slot_y, stop_slot_x, stop_slot_y, dec=fract
  2627. )
  2628. elif e_zeros == 'LZ' and tool == slot['tool']:
  2629. start_slot_x = slot['start'].x * factor
  2630. start_slot_y = slot['start'].y * factor
  2631. stop_slot_x = slot['stop'].x * factor
  2632. stop_slot_y = slot['stop'].y * factor
  2633. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2634. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2635. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2636. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2637. # extract whole part and decimal part
  2638. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  2639. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  2640. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  2641. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  2642. # left padd the 'whole' part with zeros
  2643. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  2644. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  2645. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  2646. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  2647. # restore the coordinate padded in the left with 0 and added the decimal part
  2648. # without the decinal dot
  2649. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  2650. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  2651. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  2652. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  2653. if slot_type == 'routing':
  2654. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2655. ystart=start_slot_y_formatted)
  2656. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2657. ystop=stop_slot_y_formatted)
  2658. elif slot_type == 'drilling':
  2659. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2660. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2661. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2662. )
  2663. elif tool == slot['tool']:
  2664. start_slot_x = slot['start'].x * factor
  2665. start_slot_y = slot['start'].y * factor
  2666. stop_slot_x = slot['stop'].x * factor
  2667. stop_slot_y = slot['stop'].y * factor
  2668. length = whole + fract
  2669. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2670. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2671. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2672. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2673. # pad with rear zeros
  2674. start_slot_x_formatted.ljust(length, '0')
  2675. start_slot_y_formatted.ljust(length, '0')
  2676. stop_slot_x_formatted.ljust(length, '0')
  2677. stop_slot_y_formatted.ljust(length, '0')
  2678. if slot_type == 'routing':
  2679. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2680. ystart=start_slot_y_formatted)
  2681. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2682. ystop=stop_slot_y_formatted)
  2683. elif slot_type == 'drilling':
  2684. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2685. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2686. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2687. )
  2688. except Exception as e:
  2689. log.debug(str(e))
  2690. if not self.drills and not self.slots:
  2691. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  2692. return 'fail'
  2693. return has_slots, excellon_code
  2694. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  2695. """
  2696. Note: This method is a good template for generic operations as
  2697. it takes it's options from parameters or otherwise from the
  2698. object's options and returns a (success, msg) tuple as feedback
  2699. for shell operations.
  2700. :return: Success/failure condition tuple (bool, str).
  2701. :rtype: tuple
  2702. """
  2703. # Get the tools from the list. These are keys
  2704. # to self.tools
  2705. if tools is None:
  2706. tools = self.get_selected_tools_list()
  2707. if outname is None:
  2708. outname = self.options["name"] + "_mill"
  2709. if tooldia is None:
  2710. tooldia = float(self.options["tooldia"])
  2711. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2712. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2713. sort = []
  2714. for k, v in self.tools.items():
  2715. sort.append((k, v.get('C')))
  2716. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2717. if tools == "all":
  2718. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2719. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2720. if len(tools) == 0:
  2721. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2722. _("Please select one or more tools from the list and try again."))
  2723. return False, "Error: No tools."
  2724. for tool in tools:
  2725. if tooldia > self.tools[tool]["C"]:
  2726. self.app.inform.emit(
  2727. '[ERROR_NOTCL] %s %s: %s' % (
  2728. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  2729. _("Tool"),
  2730. str(tool)
  2731. )
  2732. )
  2733. return False, "Error: Milling tool is larger than hole."
  2734. def geo_init(geo_obj, app_obj):
  2735. assert isinstance(geo_obj, FlatCAMGeometry), \
  2736. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2737. # ## Add properties to the object
  2738. # get the tool_table items in a list of row items
  2739. tool_table_items = self.get_selected_tools_table_items()
  2740. # insert an information only element in the front
  2741. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2742. geo_obj.options['Tools_in_use'] = tool_table_items
  2743. geo_obj.options['type'] = 'Excellon Geometry'
  2744. geo_obj.options["cnctooldia"] = str(tooldia)
  2745. geo_obj.solid_geometry = []
  2746. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2747. # for FlatCAM is 6 decimals,
  2748. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2749. for hole in self.drills:
  2750. if hole['tool'] in tools:
  2751. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  2752. if buffer_value == 0:
  2753. geo_obj.solid_geometry.append(
  2754. Point(hole['point']).buffer(0.0000001).exterior)
  2755. else:
  2756. geo_obj.solid_geometry.append(
  2757. Point(hole['point']).buffer(buffer_value).exterior)
  2758. if use_thread:
  2759. def geo_thread(app_obj):
  2760. app_obj.new_object("geometry", outname, geo_init, plot=plot)
  2761. # Create a promise with the new name
  2762. self.app.collection.promise(outname)
  2763. # Send to worker
  2764. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2765. else:
  2766. self.app.new_object("geometry", outname, geo_init, plot=plot)
  2767. return True, ""
  2768. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=True, use_thread=False):
  2769. """
  2770. Note: This method is a good template for generic operations as
  2771. it takes it's options from parameters or otherwise from the
  2772. object's options and returns a (success, msg) tuple as feedback
  2773. for shell operations.
  2774. :return: Success/failure condition tuple (bool, str).
  2775. :rtype: tuple
  2776. """
  2777. # Get the tools from the list. These are keys
  2778. # to self.tools
  2779. if tools is None:
  2780. tools = self.get_selected_tools_list()
  2781. if outname is None:
  2782. outname = self.options["name"] + "_mill"
  2783. if tooldia is None:
  2784. tooldia = float(self.options["slot_tooldia"])
  2785. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2786. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2787. sort = []
  2788. for k, v in self.tools.items():
  2789. sort.append((k, v.get('C')))
  2790. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2791. if tools == "all":
  2792. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2793. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2794. if len(tools) == 0:
  2795. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2796. _("Please select one or more tools from the list and try again."))
  2797. return False, "Error: No tools."
  2798. for tool in tools:
  2799. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2800. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  2801. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2802. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  2803. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2804. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  2805. return False, "Error: Milling tool is larger than hole."
  2806. def geo_init(geo_obj, app_obj):
  2807. assert isinstance(geo_obj, FlatCAMGeometry), \
  2808. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2809. # ## Add properties to the object
  2810. # get the tool_table items in a list of row items
  2811. tool_table_items = self.get_selected_tools_table_items()
  2812. # insert an information only element in the front
  2813. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2814. geo_obj.options['Tools_in_use'] = tool_table_items
  2815. geo_obj.options['type'] = 'Excellon Geometry'
  2816. geo_obj.options["cnctooldia"] = str(tooldia)
  2817. geo_obj.solid_geometry = []
  2818. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2819. # for FlatCAM is 6 decimals,
  2820. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2821. for slot in self.slots:
  2822. if slot['tool'] in tools:
  2823. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  2824. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2825. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2826. # for the file_tool (tooldia actually)
  2827. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  2828. if buffer_value == 0:
  2829. start = slot['start']
  2830. stop = slot['stop']
  2831. lines_string = LineString([start, stop])
  2832. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  2833. geo_obj.solid_geometry.append(poly)
  2834. else:
  2835. start = slot['start']
  2836. stop = slot['stop']
  2837. lines_string = LineString([start, stop])
  2838. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  2839. geo_obj.solid_geometry.append(poly)
  2840. if use_thread:
  2841. def geo_thread(app_obj):
  2842. app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2843. # Create a promise with the new name
  2844. self.app.collection.promise(outname)
  2845. # Send to worker
  2846. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2847. else:
  2848. self.app.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2849. return True, ""
  2850. def on_generate_milling_button_click(self, *args):
  2851. self.app.report_usage("excellon_on_create_milling_drills button")
  2852. self.read_form()
  2853. self.generate_milling_drills(use_thread=False)
  2854. def on_generate_milling_slots_button_click(self, *args):
  2855. self.app.report_usage("excellon_on_create_milling_slots_button")
  2856. self.read_form()
  2857. self.generate_milling_slots(use_thread=False)
  2858. def on_pp_changed(self):
  2859. current_pp = self.ui.pp_excellon_name_cb.get_value()
  2860. if "toolchange_probe" in current_pp.lower():
  2861. self.ui.pdepth_entry.setVisible(True)
  2862. self.ui.pdepth_label.show()
  2863. self.ui.feedrate_probe_entry.setVisible(True)
  2864. self.ui.feedrate_probe_label.show()
  2865. else:
  2866. self.ui.pdepth_entry.setVisible(False)
  2867. self.ui.pdepth_label.hide()
  2868. self.ui.feedrate_probe_entry.setVisible(False)
  2869. self.ui.feedrate_probe_label.hide()
  2870. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  2871. self.ui.feedrate_rapid_label.show()
  2872. self.ui.feedrate_rapid_entry.show()
  2873. else:
  2874. self.ui.feedrate_rapid_label.hide()
  2875. self.ui.feedrate_rapid_entry.hide()
  2876. if 'laser' in current_pp.lower():
  2877. self.ui.cutzlabel.hide()
  2878. self.ui.cutz_entry.hide()
  2879. try:
  2880. self.ui.mpass_cb.hide()
  2881. self.ui.maxdepth_entry.hide()
  2882. except AttributeError:
  2883. pass
  2884. if 'marlin' in current_pp.lower():
  2885. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  2886. self.ui.endz_label.show()
  2887. self.ui.endz_entry.show()
  2888. else:
  2889. self.ui.travelzlabel.hide()
  2890. self.ui.travelz_entry.hide()
  2891. self.ui.endz_label.hide()
  2892. self.ui.endz_entry.hide()
  2893. try:
  2894. self.ui.frzlabel.hide()
  2895. self.ui.feedrate_z_entry.hide()
  2896. except AttributeError:
  2897. pass
  2898. self.ui.dwell_cb.hide()
  2899. self.ui.dwelltime_entry.hide()
  2900. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  2901. try:
  2902. self.ui.tool_offset_label.hide()
  2903. self.ui.offset_entry.hide()
  2904. except AttributeError:
  2905. pass
  2906. else:
  2907. self.ui.cutzlabel.show()
  2908. self.ui.cutz_entry.show()
  2909. try:
  2910. self.ui.mpass_cb.show()
  2911. self.ui.maxdepth_entry.show()
  2912. except AttributeError:
  2913. pass
  2914. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  2915. self.ui.travelzlabel.show()
  2916. self.ui.travelz_entry.show()
  2917. self.ui.endz_label.show()
  2918. self.ui.endz_entry.show()
  2919. try:
  2920. self.ui.frzlabel.show()
  2921. self.ui.feedrate_z_entry.show()
  2922. except AttributeError:
  2923. pass
  2924. self.ui.dwell_cb.show()
  2925. self.ui.dwelltime_entry.show()
  2926. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  2927. try:
  2928. self.ui.tool_offset_lbl.show()
  2929. self.ui.offset_entry.show()
  2930. except AttributeError:
  2931. pass
  2932. def on_create_cncjob_button_click(self, *args):
  2933. self.app.report_usage("excellon_on_create_cncjob_button")
  2934. self.read_form()
  2935. # Get the tools from the list
  2936. tools = self.get_selected_tools_list()
  2937. if len(tools) == 0:
  2938. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  2939. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  2940. # in this case regardless of the selection status of that tool, use it.
  2941. if self.ui.tools_table.rowCount() == 3:
  2942. tools.append(self.ui.tools_table.item(0, 0).text())
  2943. else:
  2944. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2945. _("Please select one or more tools from the list and try again."))
  2946. return
  2947. xmin = self.options['xmin']
  2948. ymin = self.options['ymin']
  2949. xmax = self.options['xmax']
  2950. ymax = self.options['ymax']
  2951. job_name = self.options["name"] + "_cnc"
  2952. pp_excellon_name = self.options["ppname_e"]
  2953. # Object initialization function for app.new_object()
  2954. def job_init(job_obj, app_obj):
  2955. assert isinstance(job_obj, FlatCAMCNCjob), \
  2956. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2957. # get the tool_table items in a list of row items
  2958. tool_table_items = self.get_selected_tools_table_items()
  2959. # insert an information only element in the front
  2960. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2961. # ## Add properties to the object
  2962. job_obj.origin_kind = 'excellon'
  2963. job_obj.options['Tools_in_use'] = tool_table_items
  2964. job_obj.options['type'] = 'Excellon'
  2965. job_obj.options['ppname_e'] = pp_excellon_name
  2966. job_obj.z_cut = float(self.options["drillz"])
  2967. job_obj.multidepth = self.options["multidepth"]
  2968. job_obj.z_depthpercut = self.options["depthperpass"]
  2969. job_obj.tool_offset = self.tool_offset
  2970. job_obj.z_move = float(self.options["travelz"])
  2971. job_obj.feedrate = float(self.options["feedrate"])
  2972. job_obj.z_feedrate = float(self.options["feedrate"])
  2973. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  2974. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] != 0 else None
  2975. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  2976. job_obj.dwell = self.options["dwell"]
  2977. job_obj.dwelltime = float(self.options["dwelltime"])
  2978. job_obj.pp_excellon_name = pp_excellon_name
  2979. job_obj.toolchange_xy_type = "excellon"
  2980. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  2981. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  2982. job_obj.options['xmin'] = xmin
  2983. job_obj.options['ymin'] = ymin
  2984. job_obj.options['xmax'] = xmax
  2985. job_obj.options['ymax'] = ymax
  2986. job_obj.z_pdepth = float(self.options["z_pdepth"])
  2987. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  2988. # There could be more than one drill size...
  2989. # job_obj.tooldia = # TODO: duplicate variable!
  2990. # job_obj.options["tooldia"] =
  2991. tools_csv = ','.join(tools)
  2992. ret_val = job_obj.generate_from_excellon_by_tool(
  2993. self, tools_csv,
  2994. drillz=float(self.options['drillz']),
  2995. toolchange=self.options["toolchange"],
  2996. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  2997. toolchangez=float(self.options["toolchangez"]),
  2998. startz=float(self.options["startz"]) if self.options["startz"] else None,
  2999. endz=float(self.options["endz"]),
  3000. excellon_optimization_type=self.app.defaults["excellon_optimization_type"])
  3001. if ret_val == 'fail':
  3002. return 'fail'
  3003. job_obj.gcode_parse()
  3004. job_obj.create_geometry()
  3005. # To be run in separate thread
  3006. def job_thread(app_obj):
  3007. with self.app.proc_container.new(_("Generating CNC Code")):
  3008. app_obj.new_object("cncjob", job_name, job_init)
  3009. # Create promise for the new name.
  3010. self.app.collection.promise(job_name)
  3011. # Send to worker
  3012. # self.app.worker.add_task(job_thread, [self.app])
  3013. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3014. def convert_units(self, units):
  3015. log.debug("FlatCAMObj.FlatCAMExcellon.convert_units()")
  3016. Excellon.convert_units(self, units)
  3017. # factor = Excellon.convert_units(self, units)
  3018. # self.options['drillz'] = float(self.options['drillz']) * factor
  3019. # self.options['travelz'] = float(self.options['travelz']) * factor
  3020. # self.options['feedrate'] = float(self.options['feedrate']) * factor
  3021. # self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3022. # self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  3023. #
  3024. # if self.app.defaults["excellon_toolchangexy"] == '':
  3025. # self.options['toolchangexy'] = "0.0, 0.0"
  3026. # else:
  3027. # coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  3028. # if len(coords_xy) < 2:
  3029. # self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  3030. # "in the format (x, y) \n"
  3031. # "but now there is only one value, not two. "))
  3032. # return 'fail'
  3033. # coords_xy[0] *= factor
  3034. # coords_xy[1] *= factor
  3035. # self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3036. #
  3037. # if self.options['startz'] is not None:
  3038. # self.options['startz'] = float(self.options['startz']) * factor
  3039. # self.options['endz'] = float(self.options['endz']) * factor
  3040. def on_solid_cb_click(self, *args):
  3041. if self.muted_ui:
  3042. return
  3043. self.read_form_item('solid')
  3044. self.plot()
  3045. def on_plot_cb_click(self, *args):
  3046. if self.muted_ui:
  3047. return
  3048. self.plot()
  3049. self.read_form_item('plot')
  3050. self.ui_disconnect()
  3051. cb_flag = self.ui.plot_cb.isChecked()
  3052. for row in range(self.ui.tools_table.rowCount() - 2):
  3053. table_cb = self.ui.tools_table.cellWidget(row, 5)
  3054. if cb_flag:
  3055. table_cb.setChecked(True)
  3056. else:
  3057. table_cb.setChecked(False)
  3058. self.ui_connect()
  3059. def on_plot_cb_click_table(self):
  3060. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3061. self.ui_disconnect()
  3062. # cw = self.sender()
  3063. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  3064. # cw_row = cw_index.row()
  3065. check_row = 0
  3066. self.shapes.clear(update=True)
  3067. for tool_key in self.tools:
  3068. solid_geometry = self.tools[tool_key]['solid_geometry']
  3069. # find the geo_tool_table row associated with the tool_key
  3070. for row in range(self.ui.tools_table.rowCount()):
  3071. tool_item = int(self.ui.tools_table.item(row, 0).text())
  3072. if tool_item == int(tool_key):
  3073. check_row = row
  3074. break
  3075. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  3076. self.options['plot'] = True
  3077. # self.plot_element(element=solid_geometry, visible=True)
  3078. # Plot excellon (All polygons?)
  3079. if self.options["solid"]:
  3080. for geo in solid_geometry:
  3081. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  3082. visible=self.options['plot'],
  3083. layer=2)
  3084. else:
  3085. for geo in solid_geometry:
  3086. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  3087. for ints in geo.interiors:
  3088. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  3089. self.shapes.redraw()
  3090. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3091. # if all the row plot's are enabled also enable the general plot checkbox
  3092. cb_cnt = 0
  3093. total_row = self.ui.tools_table.rowCount()
  3094. for row in range(total_row - 2):
  3095. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  3096. cb_cnt += 1
  3097. else:
  3098. cb_cnt -= 1
  3099. if cb_cnt < total_row - 2:
  3100. self.ui.plot_cb.setChecked(False)
  3101. else:
  3102. self.ui.plot_cb.setChecked(True)
  3103. self.ui_connect()
  3104. # def plot_element(self, element, color='red', visible=None, layer=None):
  3105. #
  3106. # visible = visible if visible else self.options['plot']
  3107. #
  3108. # try:
  3109. # for sub_el in element:
  3110. # self.plot_element(sub_el)
  3111. #
  3112. # except TypeError: # Element is not iterable...
  3113. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  3114. def plot(self, visible=None, kind=None):
  3115. # Does all the required setup and returns False
  3116. # if the 'ptint' option is set to False.
  3117. if not FlatCAMObj.plot(self):
  3118. return
  3119. # try:
  3120. # # Plot Excellon (All polygons?)
  3121. # if self.options["solid"]:
  3122. # for tool in self.tools:
  3123. # for geo in self.tools[tool]['solid_geometry']:
  3124. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  3125. # visible=self.options['plot'],
  3126. # layer=2)
  3127. # else:
  3128. # for tool in self.tools:
  3129. # for geo in self.tools[tool]['solid_geometry']:
  3130. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  3131. # for ints in geo.interiors:
  3132. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  3133. #
  3134. # self.shapes.redraw()
  3135. # return
  3136. # except (ObjectDeleted, AttributeError, KeyError):
  3137. # self.shapes.clear(update=True)
  3138. # this stays for compatibility reasons, in case we try to open old projects
  3139. try:
  3140. __ = iter(self.solid_geometry)
  3141. except TypeError:
  3142. self.solid_geometry = [self.solid_geometry]
  3143. visible = visible if visible else self.options['plot']
  3144. try:
  3145. # Plot Excellon (All polygons?)
  3146. if self.options["solid"]:
  3147. for geo in self.solid_geometry:
  3148. self.add_shape(shape=geo,
  3149. color=self.outline_color,
  3150. face_color=self.fill_color,
  3151. visible=visible,
  3152. layer=2)
  3153. else:
  3154. for geo in self.solid_geometry:
  3155. self.add_shape(shape=geo.exterior, color='red', visible=visible)
  3156. for ints in geo.interiors:
  3157. self.add_shape(shape=ints, color='orange', visible=visible)
  3158. self.shapes.redraw()
  3159. except (ObjectDeleted, AttributeError):
  3160. self.shapes.clear(update=True)
  3161. class FlatCAMGeometry(FlatCAMObj, Geometry):
  3162. """
  3163. Geometric object not associated with a specific
  3164. format.
  3165. """
  3166. optionChanged = QtCore.pyqtSignal(str)
  3167. ui_type = GeometryObjectUI
  3168. def __init__(self, name):
  3169. self.decimals = self.app.decimals
  3170. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  3171. FlatCAMObj.__init__(self, name)
  3172. Geometry.__init__(self, geo_steps_per_circle=self.circle_steps)
  3173. self.kind = "geometry"
  3174. self.options.update({
  3175. "plot": True,
  3176. "cutz": -0.002,
  3177. "vtipdia": 0.1,
  3178. "vtipangle": 30,
  3179. "travelz": 0.1,
  3180. "feedrate": 5.0,
  3181. "feedrate_z": 5.0,
  3182. "feedrate_rapid": 5.0,
  3183. "spindlespeed": 0,
  3184. "dwell": True,
  3185. "dwelltime": 1000,
  3186. "multidepth": False,
  3187. "depthperpass": 0.002,
  3188. "extracut": False,
  3189. "extracut_length": 0.1,
  3190. "endz": 2.0,
  3191. "startz": None,
  3192. "toolchange": False,
  3193. "toolchangez": 1.0,
  3194. "toolchangexy": "0.0, 0.0",
  3195. "ppname_g": 'default',
  3196. "z_pdepth": -0.02,
  3197. "feedrate_probe": 3.0,
  3198. })
  3199. if "cnctooldia" not in self.options:
  3200. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  3201. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  3202. else:
  3203. try:
  3204. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  3205. tools_diameters = [eval(a) for a in tools_string if a != '']
  3206. self.options["cnctooldia"] = tools_diameters[0] if tools_diameters else 0.0
  3207. except Exception as e:
  3208. log.debug("FlatCAMObj.FlatCAMGeometry.init() --> %s" % str(e))
  3209. self.options["startz"] = self.app.defaults["geometry_startz"]
  3210. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  3211. self.tooluid = 0
  3212. '''
  3213. self.tools = {}
  3214. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  3215. tool_id of the tools and the value is another dict that will hold the data under the following form:
  3216. {tooluid: {
  3217. 'tooldia': 1,
  3218. 'offset': 'Path',
  3219. 'offset_value': 0.0
  3220. 'type': 'Rough',
  3221. 'tool_type': 'C1',
  3222. 'data': self.default_tool_data
  3223. 'solid_geometry': []
  3224. }
  3225. }
  3226. '''
  3227. self.tools = {}
  3228. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  3229. # those elements are the ones used for generating GCode
  3230. self.sel_tools = {}
  3231. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  3232. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  3233. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  3234. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  3235. self.v_tool_type = None
  3236. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  3237. # the default value is False
  3238. self.multigeo = False
  3239. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  3240. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  3241. self.special_group = None
  3242. self.old_pp_state = self.app.defaults["geometry_multidepth"]
  3243. self.old_toolchangeg_state = self.app.defaults["geometry_toolchange"]
  3244. self.units_found = self.app.defaults['units']
  3245. # this variable can be updated by the Object that generates the geometry
  3246. self.tool_type = 'C1'
  3247. # save here the old value for the Cut Z before it is changed by selecting a V-shape type tool in the tool table
  3248. self.old_cutz = self.app.defaults["geometry_cutz"]
  3249. self.fill_color = self.app.defaults['geometry_plot_line']
  3250. self.outline_color = self.app.defaults['geometry_plot_line']
  3251. self.alpha_level = 'FF'
  3252. # Attributes to be included in serialization
  3253. # Always append to it because it carries contents
  3254. # from predecessors.
  3255. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  3256. def build_ui(self):
  3257. self.ui_disconnect()
  3258. FlatCAMObj.build_ui(self)
  3259. self.units = self.app.defaults['units']
  3260. tool_idx = 0
  3261. n = len(self.tools)
  3262. self.ui.geo_tools_table.setRowCount(n)
  3263. for tooluid_key, tooluid_value in self.tools.items():
  3264. tool_idx += 1
  3265. row_no = tool_idx - 1
  3266. tool_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3267. tool_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3268. self.ui.geo_tools_table.setItem(row_no, 0, tool_id) # Tool name/id
  3269. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3270. # There are no tool bits in MM with more than 3 decimals diameter.
  3271. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  3272. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooluid_value['tooldia'])))
  3273. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3274. offset_item = QtWidgets.QComboBox()
  3275. for item in self.offset_item_options:
  3276. offset_item.addItem(item)
  3277. # offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  3278. idx = offset_item.findText(tooluid_value['offset'])
  3279. offset_item.setCurrentIndex(idx)
  3280. type_item = QtWidgets.QComboBox()
  3281. for item in self.type_item_options:
  3282. type_item.addItem(item)
  3283. # type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3284. idx = type_item.findText(tooluid_value['type'])
  3285. type_item.setCurrentIndex(idx)
  3286. tool_type_item = QtWidgets.QComboBox()
  3287. for item in self.tool_type_item_options:
  3288. tool_type_item.addItem(item)
  3289. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3290. idx = tool_type_item.findText(tooluid_value['tool_type'])
  3291. tool_type_item.setCurrentIndex(idx)
  3292. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  3293. plot_item = FCCheckBox()
  3294. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3295. if self.ui.plot_cb.isChecked():
  3296. plot_item.setChecked(True)
  3297. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3298. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  3299. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  3300. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  3301. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3302. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  3303. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  3304. try:
  3305. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3306. except Exception as e:
  3307. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools. Error: %s" % str(e))
  3308. # make the diameter column editable
  3309. for row in range(tool_idx):
  3310. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3311. QtCore.Qt.ItemIsEditable |
  3312. QtCore.Qt.ItemIsEnabled)
  3313. # sort the tool diameter column
  3314. # self.ui.geo_tools_table.sortItems(1)
  3315. # all the tools are selected by default
  3316. # self.ui.geo_tools_table.selectColumn(0)
  3317. self.ui.geo_tools_table.resizeColumnsToContents()
  3318. self.ui.geo_tools_table.resizeRowsToContents()
  3319. vertical_header = self.ui.geo_tools_table.verticalHeader()
  3320. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3321. vertical_header.hide()
  3322. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3323. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  3324. horizontal_header.setMinimumSectionSize(10)
  3325. horizontal_header.setDefaultSectionSize(70)
  3326. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3327. horizontal_header.resizeSection(0, 20)
  3328. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3329. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  3330. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3331. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3332. horizontal_header.resizeSection(4, 40)
  3333. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3334. horizontal_header.resizeSection(4, 17)
  3335. # horizontal_header.setStretchLastSection(True)
  3336. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3337. self.ui.geo_tools_table.setColumnWidth(0, 20)
  3338. self.ui.geo_tools_table.setColumnWidth(4, 40)
  3339. self.ui.geo_tools_table.setColumnWidth(6, 17)
  3340. # self.ui.geo_tools_table.setSortingEnabled(True)
  3341. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  3342. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  3343. # update UI for all rows - useful after units conversion but only if there is at least one row
  3344. row_cnt = self.ui.geo_tools_table.rowCount()
  3345. if row_cnt > 0:
  3346. for r in range(row_cnt):
  3347. self.update_ui(r)
  3348. # select only the first tool / row
  3349. selected_row = 0
  3350. try:
  3351. self.select_tools_table_row(selected_row, clearsel=True)
  3352. # update the Geometry UI
  3353. self.update_ui()
  3354. except Exception as e:
  3355. # when the tools table is empty there will be this error but once the table is populated it will go away
  3356. log.debug(str(e))
  3357. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  3358. # and can create some problems
  3359. if self.multigeo is False:
  3360. self.ui.geo_tools_table.setColumnHidden(6, True)
  3361. else:
  3362. self.ui.geo_tools_table.setColumnHidden(6, False)
  3363. self.set_tool_offset_visibility(selected_row)
  3364. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  3365. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  3366. self.ui.name_entry.set_value(self.options['name'])
  3367. self.ui_connect()
  3368. self.ui.e_cut_entry.setDisabled(False) if self.ui.extracut_cb.get_value() else \
  3369. self.ui.e_cut_entry.setDisabled(True)
  3370. # set the text on tool_data_label after loading the object
  3371. sel_rows = list()
  3372. sel_items = self.ui.geo_tools_table.selectedItems()
  3373. for it in sel_items:
  3374. sel_rows.append(it.row())
  3375. if len(sel_rows) > 1:
  3376. self.ui.tool_data_label.setText(
  3377. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  3378. )
  3379. def set_ui(self, ui):
  3380. FlatCAMObj.set_ui(self, ui)
  3381. log.debug("FlatCAMGeometry.set_ui()")
  3382. assert isinstance(self.ui, GeometryObjectUI), \
  3383. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  3384. self.units = self.app.defaults['units'].upper()
  3385. self.units_found = self.app.defaults['units']
  3386. # populate preprocessor names in the combobox
  3387. for name in list(self.app.preprocessors.keys()):
  3388. self.ui.pp_geometry_name_cb.addItem(name)
  3389. self.form_fields.update({
  3390. "plot": self.ui.plot_cb,
  3391. "cutz": self.ui.cutz_entry,
  3392. "vtipdia": self.ui.tipdia_entry,
  3393. "vtipangle": self.ui.tipangle_entry,
  3394. "travelz": self.ui.travelz_entry,
  3395. "feedrate": self.ui.cncfeedrate_entry,
  3396. "feedrate_z": self.ui.feedrate_z_entry,
  3397. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  3398. "spindlespeed": self.ui.cncspindlespeed_entry,
  3399. "dwell": self.ui.dwell_cb,
  3400. "dwelltime": self.ui.dwelltime_entry,
  3401. "multidepth": self.ui.mpass_cb,
  3402. "ppname_g": self.ui.pp_geometry_name_cb,
  3403. "z_pdepth": self.ui.pdepth_entry,
  3404. "feedrate_probe": self.ui.feedrate_probe_entry,
  3405. "depthperpass": self.ui.maxdepth_entry,
  3406. "extracut": self.ui.extracut_cb,
  3407. "extracut_length": self.ui.e_cut_entry,
  3408. "toolchange": self.ui.toolchangeg_cb,
  3409. "toolchangez": self.ui.toolchangez_entry,
  3410. "endz": self.ui.endz_entry,
  3411. "cnctooldia": self.ui.addtool_entry
  3412. })
  3413. # Fill form fields only on object create
  3414. self.to_form()
  3415. # update the changes in UI depending on the selected preprocessor in Preferences
  3416. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  3417. # self.ui.pp_geometry_name_cb combobox
  3418. self.on_pp_changed()
  3419. self.ui.tipdialabel.hide()
  3420. self.ui.tipdia_entry.hide()
  3421. self.ui.tipanglelabel.hide()
  3422. self.ui.tipangle_entry.hide()
  3423. self.ui.cutz_entry.setDisabled(False)
  3424. # store here the default data for Geometry Data
  3425. self.default_data = dict()
  3426. self.default_data.update({
  3427. "name": None,
  3428. "plot": None,
  3429. "cutz": None,
  3430. "vtipdia": None,
  3431. "vtipangle": None,
  3432. "travelz": None,
  3433. "feedrate": None,
  3434. "feedrate_z": None,
  3435. "feedrate_rapid": None,
  3436. "dwell": None,
  3437. "dwelltime": None,
  3438. "multidepth": None,
  3439. "ppname_g": None,
  3440. "depthperpass": None,
  3441. "extracut": None,
  3442. "extracut_length": None,
  3443. "toolchange": None,
  3444. "toolchangez": None,
  3445. "endz": None,
  3446. "spindlespeed": 0,
  3447. "toolchangexy": None,
  3448. "startz": None
  3449. })
  3450. # fill in self.default_data values from self.options
  3451. for def_key in self.default_data:
  3452. for opt_key, opt_val in self.options.items():
  3453. if def_key == opt_key:
  3454. self.default_data[def_key] = deepcopy(opt_val)
  3455. if type(self.options["cnctooldia"]) == float:
  3456. tools_list = [self.options["cnctooldia"]]
  3457. else:
  3458. try:
  3459. temp_tools = self.options["cnctooldia"].split(",")
  3460. tools_list = [
  3461. float(eval(dia)) for dia in temp_tools if dia != ''
  3462. ]
  3463. except Exception as e:
  3464. log.error("FlatCAMGeometry.set_ui() -> At least one tool diameter needed. "
  3465. "Verify in Edit -> Preferences -> Geometry General -> Tool dia. %s" % str(e))
  3466. return
  3467. self.tooluid += 1
  3468. if not self.tools:
  3469. for toold in tools_list:
  3470. new_data = deepcopy(self.default_data)
  3471. self.tools.update({
  3472. self.tooluid: {
  3473. 'tooldia': float('%.*f' % (self.decimals, float(toold))),
  3474. 'offset': 'Path',
  3475. 'offset_value': 0.0,
  3476. 'type': _('Rough'),
  3477. 'tool_type': self.tool_type,
  3478. 'data': new_data,
  3479. 'solid_geometry': self.solid_geometry
  3480. }
  3481. })
  3482. self.tooluid += 1
  3483. else:
  3484. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  3485. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  3486. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  3487. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  3488. # following convoluted way of changing the keys from string to float type
  3489. temp_tools = {}
  3490. for tooluid_key in self.tools:
  3491. val = deepcopy(self.tools[tooluid_key])
  3492. new_key = deepcopy(int(tooluid_key))
  3493. temp_tools[new_key] = val
  3494. self.tools.clear()
  3495. self.tools = deepcopy(temp_tools)
  3496. self.ui.tool_offset_entry.hide()
  3497. self.ui.tool_offset_lbl.hide()
  3498. # used to store the state of the mpass_cb if the selected preprocessor for geometry is hpgl
  3499. self.old_pp_state = self.default_data['multidepth']
  3500. self.old_toolchangeg_state = self.default_data['toolchange']
  3501. if not isinstance(self.ui, GeometryObjectUI):
  3502. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  3503. return
  3504. self.ui.geo_tools_table.setupContextMenu()
  3505. self.ui.geo_tools_table.addContextMenu(
  3506. _("Add from Tool DB"), self.on_tool_add_from_db_clicked,
  3507. icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  3508. self.ui.geo_tools_table.addContextMenu(
  3509. _("Copy"), self.on_tool_copy,
  3510. icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  3511. self.ui.geo_tools_table.addContextMenu(
  3512. _("Delete"), lambda: self.on_tool_delete(all=None),
  3513. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  3514. # Show/Hide Advanced Options
  3515. if self.app.defaults["global_app_level"] == 'b':
  3516. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  3517. self.ui.geo_tools_table.setColumnHidden(2, True)
  3518. self.ui.geo_tools_table.setColumnHidden(3, True)
  3519. # self.ui.geo_tools_table.setColumnHidden(4, True)
  3520. self.ui.addtool_entry_lbl.hide()
  3521. self.ui.addtool_entry.hide()
  3522. self.ui.addtool_btn.hide()
  3523. self.ui.copytool_btn.hide()
  3524. self.ui.deltool_btn.hide()
  3525. # self.ui.endz_label.hide()
  3526. # self.ui.endz_entry.hide()
  3527. self.ui.fr_rapidlabel.hide()
  3528. self.ui.feedrate_rapid_entry.hide()
  3529. self.ui.extracut_cb.hide()
  3530. self.ui.e_cut_entry.hide()
  3531. self.ui.pdepth_label.hide()
  3532. self.ui.pdepth_entry.hide()
  3533. self.ui.feedrate_probe_label.hide()
  3534. self.ui.feedrate_probe_entry.hide()
  3535. else:
  3536. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  3537. self.ui.e_cut_entry.setDisabled(False) if self.app.defaults['geometry_extracut'] else \
  3538. self.ui.e_cut_entry.setDisabled(True)
  3539. self.ui.extracut_cb.toggled.connect(lambda state: self.ui.e_cut_entry.setDisabled(not state))
  3540. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3541. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  3542. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  3543. self.ui.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  3544. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  3545. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  3546. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  3547. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  3548. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  3549. self.ui.cutz_entry.returnPressed.connect(self.on_cut_z_changed)
  3550. def on_cut_z_changed(self):
  3551. self.old_cutz = self.ui.cutz_entry.get_value()
  3552. def set_tool_offset_visibility(self, current_row):
  3553. if current_row is None:
  3554. return
  3555. try:
  3556. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  3557. if tool_offset is not None:
  3558. tool_offset_txt = tool_offset.currentText()
  3559. if tool_offset_txt == 'Custom':
  3560. self.ui.tool_offset_entry.show()
  3561. self.ui.tool_offset_lbl.show()
  3562. else:
  3563. self.ui.tool_offset_entry.hide()
  3564. self.ui.tool_offset_lbl.hide()
  3565. except Exception as e:
  3566. log.debug("set_tool_offset_visibility() --> " + str(e))
  3567. return
  3568. def on_offset_value_edited(self):
  3569. """
  3570. This will save the offset_value into self.tools storage whenever the offset value is edited
  3571. :return:
  3572. """
  3573. for current_row in self.ui.geo_tools_table.selectedItems():
  3574. # sometime the header get selected and it has row number -1
  3575. # we don't want to do anything with the header :)
  3576. if current_row.row() < 0:
  3577. continue
  3578. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3579. self.set_tool_offset_visibility(current_row.row())
  3580. for tooluid_key, tooluid_value in self.tools.items():
  3581. if int(tooluid_key) == tool_uid:
  3582. try:
  3583. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  3584. except ValueError:
  3585. # try to convert comma to decimal point. if it's still not working error message and return
  3586. try:
  3587. tooluid_value['offset_value'] = float(
  3588. self.ui.tool_offset_entry.get_value().replace(',', '.')
  3589. )
  3590. except ValueError:
  3591. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3592. _("Wrong value format entered, use a number."))
  3593. return
  3594. def ui_connect(self):
  3595. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3596. # changes in geometry UI
  3597. for i in range(self.ui.grid3.count()):
  3598. current_widget = self.ui.grid3.itemAt(i).widget()
  3599. if isinstance(current_widget, FCCheckBox):
  3600. current_widget.stateChanged.connect(self.gui_form_to_storage)
  3601. elif isinstance(current_widget, FCComboBox):
  3602. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  3603. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  3604. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  3605. current_widget.editingFinished.connect(self.gui_form_to_storage)
  3606. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3607. current_widget.returnPressed.connect(self.gui_form_to_storage)
  3608. for row in range(self.ui.geo_tools_table.rowCount()):
  3609. for col in [2, 3, 4]:
  3610. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  3611. self.on_tooltable_cellwidget_change)
  3612. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  3613. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  3614. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  3615. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  3616. # self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  3617. self.ui.geo_tools_table.clicked.connect(self.on_row_selection_change)
  3618. self.ui.geo_tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  3619. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  3620. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  3621. for row in range(self.ui.geo_tools_table.rowCount()):
  3622. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3623. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3624. # common parameters update
  3625. self.ui.pp_geometry_name_cb.currentIndexChanged.connect(self.update_common_param_in_storage)
  3626. def ui_disconnect(self):
  3627. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3628. # changes in geometry UI
  3629. for i in range(self.ui.grid3.count()):
  3630. current_widget = self.ui.grid3.itemAt(i).widget()
  3631. if isinstance(current_widget, FCCheckBox):
  3632. try:
  3633. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect(self.gui_form_to_storage)
  3634. except (TypeError, AttributeError):
  3635. pass
  3636. elif isinstance(current_widget, FCComboBox):
  3637. try:
  3638. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect(self.gui_form_to_storage)
  3639. except (TypeError, AttributeError):
  3640. pass
  3641. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  3642. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  3643. try:
  3644. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect(self.gui_form_to_storage)
  3645. except (TypeError, AttributeError):
  3646. pass
  3647. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3648. try:
  3649. self.ui.grid3.itemAt(i).widget().returnPressed.disconnect(self.gui_form_to_storage)
  3650. except TypeError:
  3651. pass
  3652. for row in range(self.ui.geo_tools_table.rowCount()):
  3653. for col in [2, 3, 4]:
  3654. try:
  3655. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3656. except (TypeError, AttributeError):
  3657. pass
  3658. try:
  3659. self.ui.addtool_btn.clicked.disconnect()
  3660. except (TypeError, AttributeError):
  3661. pass
  3662. try:
  3663. self.ui.copytool_btn.clicked.disconnect()
  3664. except (TypeError, AttributeError):
  3665. pass
  3666. try:
  3667. self.ui.deltool_btn.clicked.disconnect()
  3668. except (TypeError, AttributeError):
  3669. pass
  3670. try:
  3671. self.ui.geo_tools_table.clicked.disconnect()
  3672. except (TypeError, AttributeError):
  3673. pass
  3674. try:
  3675. self.ui.geo_tools_table.horizontalHeader().sectionClicked.disconnect()
  3676. except (TypeError, AttributeError):
  3677. pass
  3678. try:
  3679. self.ui.geo_tools_table.itemChanged.disconnect()
  3680. except (TypeError, AttributeError):
  3681. pass
  3682. try:
  3683. self.ui.tool_offset_entry.returnPressed.disconnect()
  3684. except (TypeError, AttributeError):
  3685. pass
  3686. for row in range(self.ui.geo_tools_table.rowCount()):
  3687. try:
  3688. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  3689. except (TypeError, AttributeError):
  3690. pass
  3691. try:
  3692. self.ui.plot_cb.stateChanged.disconnect()
  3693. except (TypeError, AttributeError):
  3694. pass
  3695. def on_row_selection_change(self):
  3696. self.update_ui()
  3697. def update_ui(self, row=None):
  3698. self.ui_disconnect()
  3699. if row is None:
  3700. sel_rows = list()
  3701. sel_items = self.ui.geo_tools_table.selectedItems()
  3702. for it in sel_items:
  3703. sel_rows.append(it.row())
  3704. else:
  3705. sel_rows = row if type(row) == list else [row]
  3706. if not sel_rows:
  3707. sel_rows = [0]
  3708. for current_row in sel_rows:
  3709. self.set_tool_offset_visibility(current_row)
  3710. # populate the form with the data from the tool associated with the row parameter
  3711. try:
  3712. item = self.ui.geo_tools_table.item(current_row, 5)
  3713. if type(item) is not None:
  3714. tooluid = int(item.text())
  3715. else:
  3716. self.ui_connect()
  3717. return
  3718. except Exception as e:
  3719. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3720. self.ui_connect()
  3721. return
  3722. # update the QLabel that shows for which Tool we have the parameters in the UI form
  3723. if len(sel_rows) == 1:
  3724. self.ui.tool_data_label.setText(
  3725. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  3726. )
  3727. else:
  3728. self.ui.tool_data_label.setText(
  3729. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  3730. )
  3731. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3732. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3733. try:
  3734. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  3735. if item is not None:
  3736. tool_type_txt = item.currentText()
  3737. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3738. else:
  3739. self.ui_connect()
  3740. return
  3741. except Exception as e:
  3742. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  3743. return
  3744. try:
  3745. # set the form with data from the newly selected tool
  3746. for tooluid_key, tooluid_value in self.tools.items():
  3747. if int(tooluid_key) == tooluid:
  3748. for key, value in tooluid_value.items():
  3749. if key == 'data':
  3750. form_value_storage = tooluid_value['data']
  3751. self.update_form(form_value_storage)
  3752. if key == 'offset_value':
  3753. # update the offset value in the entry even if the entry is hidden
  3754. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3755. if key == 'tool_type' and value == 'V':
  3756. self.update_cutz()
  3757. except Exception as e:
  3758. log.debug("FlatCAMGeometry.update_ui() -> %s " % str(e))
  3759. self.ui_connect()
  3760. def on_tool_add(self, dia=None):
  3761. self.ui_disconnect()
  3762. self.units = self.app.defaults['units'].upper()
  3763. if dia is not None:
  3764. tooldia = dia
  3765. else:
  3766. tooldia = float(self.ui.addtool_entry.get_value())
  3767. # construct a list of all 'tooluid' in the self.tools
  3768. # tool_uid_list = list()
  3769. # for tooluid_key in self.tools:
  3770. # tool_uid_list.append(int(tooluid_key))
  3771. tool_uid_list = [int(tooluid_key) for tooluid_key in self.tools]
  3772. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3773. max_uid = max(tool_uid_list) if tool_uid_list else 0
  3774. self.tooluid = max_uid + 1
  3775. tooldia = float('%.*f' % (self.decimals, tooldia))
  3776. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  3777. # otherwise we add a tool with data copied from last tool
  3778. if self.tools:
  3779. last_data = self.tools[max_uid]['data']
  3780. last_offset = self.tools[max_uid]['offset']
  3781. last_offset_value = self.tools[max_uid]['offset_value']
  3782. last_type = self.tools[max_uid]['type']
  3783. last_tool_type = self.tools[max_uid]['tool_type']
  3784. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  3785. # if previous geometry was empty (it may happen for the first tool added)
  3786. # then copy the object.solid_geometry
  3787. if not last_solid_geometry:
  3788. last_solid_geometry = self.solid_geometry
  3789. self.tools.update({
  3790. self.tooluid: {
  3791. 'tooldia': tooldia,
  3792. 'offset': last_offset,
  3793. 'offset_value': last_offset_value,
  3794. 'type': last_type,
  3795. 'tool_type': last_tool_type,
  3796. 'data': deepcopy(last_data),
  3797. 'solid_geometry': deepcopy(last_solid_geometry)
  3798. }
  3799. })
  3800. else:
  3801. self.tools.update({
  3802. self.tooluid: {
  3803. 'tooldia': tooldia,
  3804. 'offset': 'Path',
  3805. 'offset_value': 0.0,
  3806. 'type': _('Rough'),
  3807. 'tool_type': 'C1',
  3808. 'data': deepcopy(self.default_data),
  3809. 'solid_geometry': self.solid_geometry
  3810. }
  3811. })
  3812. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3813. self.ui.tool_offset_entry.hide()
  3814. self.ui.tool_offset_lbl.hide()
  3815. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3816. try:
  3817. self.ser_attrs.remove('tools')
  3818. except TypeError:
  3819. pass
  3820. self.ser_attrs.append('tools')
  3821. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  3822. self.ui_connect()
  3823. self.build_ui()
  3824. # if there is no tool left in the Tools Table, enable the parameters GUI
  3825. if self.ui.geo_tools_table.rowCount() != 0:
  3826. self.ui.geo_param_frame.setDisabled(False)
  3827. def on_tool_add_from_db_clicked(self):
  3828. """
  3829. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3830. and display the Tools Database tab in the form needed for the Tool adding
  3831. :return: None
  3832. """
  3833. # if the Tools Database is already opened focus on it
  3834. for idx in range(self.app.ui.plot_tab_area.count()):
  3835. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3836. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3837. break
  3838. self.app.on_tools_database()
  3839. self.app.tools_db_tab.buttons_frame.hide()
  3840. self.app.tools_db_tab.add_tool_from_db.show()
  3841. self.app.tools_db_tab.cancel_tool_from_db.show()
  3842. def on_tool_from_db_inserted(self, tool):
  3843. """
  3844. Called from the Tools DB object through a App method when adding a tool from Tools Database
  3845. :param tool: a dict with the tool data
  3846. :return: None
  3847. """
  3848. self.ui_disconnect()
  3849. self.units = self.app.defaults['units'].upper()
  3850. tooldia = float(tool['tooldia'])
  3851. # construct a list of all 'tooluid' in the self.tools
  3852. tool_uid_list = []
  3853. for tooluid_key in self.tools:
  3854. tool_uid_item = int(tooluid_key)
  3855. tool_uid_list.append(tool_uid_item)
  3856. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3857. if not tool_uid_list:
  3858. max_uid = 0
  3859. else:
  3860. max_uid = max(tool_uid_list)
  3861. self.tooluid = max_uid + 1
  3862. tooldia = float('%.*f' % (self.decimals, tooldia))
  3863. self.tools.update({
  3864. self.tooluid: {
  3865. 'tooldia': tooldia,
  3866. 'offset': tool['offset'],
  3867. 'offset_value': float(tool['offset_value']),
  3868. 'type': tool['type'],
  3869. 'tool_type': tool['tool_type'],
  3870. 'data': deepcopy(tool['data']),
  3871. 'solid_geometry': self.solid_geometry
  3872. }
  3873. })
  3874. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3875. self.ui.tool_offset_entry.hide()
  3876. self.ui.tool_offset_lbl.hide()
  3877. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3878. try:
  3879. self.ser_attrs.remove('tools')
  3880. except TypeError:
  3881. pass
  3882. self.ser_attrs.append('tools')
  3883. self.ui_connect()
  3884. self.build_ui()
  3885. # if there is no tool left in the Tools Table, enable the parameters GUI
  3886. if self.ui.geo_tools_table.rowCount() != 0:
  3887. self.ui.geo_param_frame.setDisabled(False)
  3888. def on_tool_copy(self, all=None):
  3889. self.ui_disconnect()
  3890. # find the tool_uid maximum value in the self.tools
  3891. uid_list = []
  3892. for key in self.tools:
  3893. uid_list.append(int(key))
  3894. try:
  3895. max_uid = max(uid_list, key=int)
  3896. except ValueError:
  3897. max_uid = 0
  3898. if all is None:
  3899. if self.ui.geo_tools_table.selectedItems():
  3900. for current_row in self.ui.geo_tools_table.selectedItems():
  3901. # sometime the header get selected and it has row number -1
  3902. # we don't want to do anything with the header :)
  3903. if current_row.row() < 0:
  3904. continue
  3905. try:
  3906. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3907. self.set_tool_offset_visibility(current_row.row())
  3908. max_uid += 1
  3909. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  3910. except AttributeError:
  3911. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  3912. self.ui_connect()
  3913. self.build_ui()
  3914. return
  3915. except Exception as e:
  3916. log.debug("on_tool_copy() --> " + str(e))
  3917. # deselect the table
  3918. # self.ui.geo_tools_table.clearSelection()
  3919. else:
  3920. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  3921. self.ui_connect()
  3922. self.build_ui()
  3923. return
  3924. else:
  3925. # we copy all tools in geo_tools_table
  3926. try:
  3927. temp_tools = deepcopy(self.tools)
  3928. max_uid += 1
  3929. for tooluid in temp_tools:
  3930. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3931. temp_tools.clear()
  3932. except Exception as e:
  3933. log.debug("on_tool_copy() --> " + str(e))
  3934. # if there are no more tools in geo tools table then hide the tool offset
  3935. if not self.tools:
  3936. self.ui.tool_offset_entry.hide()
  3937. self.ui.tool_offset_lbl.hide()
  3938. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3939. try:
  3940. self.ser_attrs.remove('tools')
  3941. except ValueError:
  3942. pass
  3943. self.ser_attrs.append('tools')
  3944. self.ui_connect()
  3945. self.build_ui()
  3946. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  3947. def on_tool_edit(self, current_item):
  3948. self.ui_disconnect()
  3949. current_row = current_item.row()
  3950. try:
  3951. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3952. except ValueError:
  3953. # try to convert comma to decimal point. if it's still not working error message and return
  3954. try:
  3955. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3956. except ValueError:
  3957. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  3958. return
  3959. tool_dia = float('%.*f' % (self.decimals, d))
  3960. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3961. self.tools[tooluid]['tooldia'] = tool_dia
  3962. try:
  3963. self.ser_attrs.remove('tools')
  3964. self.ser_attrs.append('tools')
  3965. except (TypeError, ValueError):
  3966. pass
  3967. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  3968. self.ui_connect()
  3969. self.build_ui()
  3970. def on_tool_delete(self, all=None):
  3971. self.ui_disconnect()
  3972. if all is None:
  3973. if self.ui.geo_tools_table.selectedItems():
  3974. for current_row in self.ui.geo_tools_table.selectedItems():
  3975. # sometime the header get selected and it has row number -1
  3976. # we don't want to do anything with the header :)
  3977. if current_row.row() < 0:
  3978. continue
  3979. try:
  3980. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3981. self.set_tool_offset_visibility(current_row.row())
  3982. temp_tools = deepcopy(self.tools)
  3983. for tooluid_key in self.tools:
  3984. if int(tooluid_key) == tooluid_del:
  3985. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3986. # as a property of the object otherwise there will be nothing to hold it
  3987. if len(self.tools) == 1:
  3988. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3989. temp_tools.pop(tooluid_del, None)
  3990. self.tools = deepcopy(temp_tools)
  3991. temp_tools.clear()
  3992. except AttributeError:
  3993. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  3994. self.ui_connect()
  3995. self.build_ui()
  3996. return
  3997. except Exception as e:
  3998. log.debug("on_tool_delete() --> " + str(e))
  3999. # deselect the table
  4000. # self.ui.geo_tools_table.clearSelection()
  4001. else:
  4002. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  4003. self.ui_connect()
  4004. self.build_ui()
  4005. return
  4006. else:
  4007. # we delete all tools in geo_tools_table
  4008. self.tools.clear()
  4009. self.app.plot_all()
  4010. # if there are no more tools in geo tools table then hide the tool offset
  4011. if not self.tools:
  4012. self.ui.tool_offset_entry.hide()
  4013. self.ui.tool_offset_lbl.hide()
  4014. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  4015. try:
  4016. self.ser_attrs.remove('tools')
  4017. except TypeError:
  4018. pass
  4019. self.ser_attrs.append('tools')
  4020. self.ui_connect()
  4021. self.build_ui()
  4022. self.app.inform.emit('[success] %s' % _("Tool was deleted in Tool Table."))
  4023. obj_active = self.app.collection.get_active()
  4024. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  4025. # we make it back SingleGeo
  4026. if self.ui.geo_tools_table.rowCount() <= 0:
  4027. obj_active.multigeo = False
  4028. obj_active.options['xmin'] = 0
  4029. obj_active.options['ymin'] = 0
  4030. obj_active.options['xmax'] = 0
  4031. obj_active.options['ymax'] = 0
  4032. if obj_active.multigeo is True:
  4033. try:
  4034. xmin, ymin, xmax, ymax = obj_active.bounds()
  4035. obj_active.options['xmin'] = xmin
  4036. obj_active.options['ymin'] = ymin
  4037. obj_active.options['xmax'] = xmax
  4038. obj_active.options['ymax'] = ymax
  4039. except Exception:
  4040. obj_active.options['xmin'] = 0
  4041. obj_active.options['ymin'] = 0
  4042. obj_active.options['xmax'] = 0
  4043. obj_active.options['ymax'] = 0
  4044. # if there is no tool left in the Tools Table, disable the parameters GUI
  4045. if self.ui.geo_tools_table.rowCount() == 0:
  4046. self.ui.geo_param_frame.setDisabled(True)
  4047. def ui_update_v_shape(self, tool_type_txt):
  4048. if tool_type_txt == 'V':
  4049. self.ui.tipdialabel.show()
  4050. self.ui.tipdia_entry.show()
  4051. self.ui.tipanglelabel.show()
  4052. self.ui.tipangle_entry.show()
  4053. self.ui.cutz_entry.setDisabled(True)
  4054. self.update_cutz()
  4055. else:
  4056. self.ui.tipdialabel.hide()
  4057. self.ui.tipdia_entry.hide()
  4058. self.ui.tipanglelabel.hide()
  4059. self.ui.tipangle_entry.hide()
  4060. self.ui.cutz_entry.setDisabled(False)
  4061. def update_cutz(self):
  4062. vdia = float(self.ui.tipdia_entry.get_value())
  4063. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  4064. row = self.ui.geo_tools_table.currentRow()
  4065. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  4066. if tool_uid_item is None:
  4067. return
  4068. tool_uid = int(tool_uid_item.text())
  4069. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  4070. if tool_dia_item is None:
  4071. return
  4072. tooldia = float(tool_dia_item.text())
  4073. try:
  4074. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  4075. except ZeroDivisionError:
  4076. new_cutz = self.old_cutz
  4077. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  4078. self.ui.cutz_entry.set_value(new_cutz)
  4079. # store the new CutZ value into storage (self.tools)
  4080. for tooluid_key, tooluid_value in self.tools.items():
  4081. if int(tooluid_key) == tool_uid:
  4082. tooluid_value['data']['cutz'] = new_cutz
  4083. def on_tooltable_cellwidget_change(self):
  4084. cw = self.sender()
  4085. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4086. cw_row = cw_index.row()
  4087. cw_col = cw_index.column()
  4088. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  4089. # store the text of the cellWidget that changed it's index in the self.tools
  4090. for tooluid_key, tooluid_value in self.tools.items():
  4091. if int(tooluid_key) == current_uid:
  4092. cb_txt = cw.currentText()
  4093. if cw_col == 2:
  4094. tooluid_value['offset'] = cb_txt
  4095. if cb_txt == 'Custom':
  4096. self.ui.tool_offset_entry.show()
  4097. self.ui.tool_offset_lbl.show()
  4098. else:
  4099. self.ui.tool_offset_entry.hide()
  4100. self.ui.tool_offset_lbl.hide()
  4101. # reset the offset_value in storage self.tools
  4102. tooluid_value['offset_value'] = 0.0
  4103. elif cw_col == 3:
  4104. # force toolpath type as 'Iso' if the tool type is V-Shape
  4105. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  4106. tooluid_value['type'] = _('Iso')
  4107. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  4108. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  4109. else:
  4110. tooluid_value['type'] = cb_txt
  4111. elif cw_col == 4:
  4112. tooluid_value['tool_type'] = cb_txt
  4113. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  4114. if cb_txt == 'V':
  4115. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  4116. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  4117. else:
  4118. self.ui.cutz_entry.set_value(self.old_cutz)
  4119. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  4120. def update_form(self, dict_storage):
  4121. for form_key in self.form_fields:
  4122. for storage_key in dict_storage:
  4123. if form_key == storage_key:
  4124. try:
  4125. self.form_fields[form_key].set_value(dict_storage[form_key])
  4126. except Exception as e:
  4127. log.debug(str(e))
  4128. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  4129. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  4130. self.ui.ois_dwell_geo.on_cb_change()
  4131. self.ui.ois_mpass_geo.on_cb_change()
  4132. self.ui.ois_tcz_geo.on_cb_change()
  4133. def on_apply_param_to_all_clicked(self):
  4134. if self.ui.geo_tools_table.rowCount() == 0:
  4135. # there is no tool in tool table so we can't save the GUI elements values to storage
  4136. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  4137. return
  4138. self.ui_disconnect()
  4139. row = self.ui.geo_tools_table.currentRow()
  4140. if row < 0:
  4141. row = 0
  4142. # store all the data associated with the row parameter to the self.tools storage
  4143. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  4144. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  4145. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  4146. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  4147. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  4148. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  4149. temp_tools = {}
  4150. temp_dia = {}
  4151. temp_data = {}
  4152. for tooluid_key, tooluid_value in self.tools.items():
  4153. for key, value in tooluid_value.items():
  4154. if key == 'tooldia':
  4155. temp_dia[key] = tooldia_item
  4156. # update the 'offset', 'type' and 'tool_type' sections
  4157. if key == 'offset':
  4158. temp_dia[key] = offset_item
  4159. if key == 'type':
  4160. temp_dia[key] = type_item
  4161. if key == 'tool_type':
  4162. temp_dia[key] = tool_type_item
  4163. if key == 'offset_value':
  4164. temp_dia[key] = offset_value_item
  4165. if key == 'data':
  4166. # update the 'data' section
  4167. for data_key in tooluid_value[key].keys():
  4168. for form_key, form_value in self.form_fields.items():
  4169. if form_key == data_key:
  4170. temp_data[data_key] = form_value.get_value()
  4171. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  4172. # updated from self.app.defaults
  4173. if data_key not in self.form_fields:
  4174. temp_data[data_key] = value[data_key]
  4175. temp_dia[key] = deepcopy(temp_data)
  4176. temp_data.clear()
  4177. if key == 'solid_geometry':
  4178. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4179. temp_tools[tooluid_key] = deepcopy(temp_dia)
  4180. self.tools.clear()
  4181. self.tools = deepcopy(temp_tools)
  4182. temp_tools.clear()
  4183. self.ui_connect()
  4184. def gui_form_to_storage(self):
  4185. if self.ui.geo_tools_table.rowCount() == 0:
  4186. # there is no tool in tool table so we can't save the GUI elements values to storage
  4187. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  4188. return
  4189. self.ui_disconnect()
  4190. widget_changed = self.sender()
  4191. try:
  4192. widget_idx = self.ui.grid3.indexOf(widget_changed)
  4193. except Exception:
  4194. return
  4195. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  4196. if widget_idx == 1 or widget_idx == 3:
  4197. self.update_cutz()
  4198. # the original connect() function of the OptionalInputSelection is no longer working because of the
  4199. # ui_diconnect() so I use this 'hack'
  4200. if isinstance(widget_changed, FCCheckBox):
  4201. if widget_changed.text() == 'Multi-Depth:':
  4202. self.ui.ois_mpass_geo.on_cb_change()
  4203. if widget_changed.text() == 'Tool change':
  4204. self.ui.ois_tcz_geo.on_cb_change()
  4205. if widget_changed.text() == 'Dwell:':
  4206. self.ui.ois_dwell_geo.on_cb_change()
  4207. row = self.ui.geo_tools_table.currentRow()
  4208. if row < 0:
  4209. row = 0
  4210. # store all the data associated with the row parameter to the self.tools storage
  4211. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  4212. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  4213. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  4214. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  4215. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4216. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  4217. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  4218. temp_tools = {}
  4219. temp_dia = {}
  4220. temp_data = {}
  4221. for tooluid_key, tooluid_value in self.tools.items():
  4222. if int(tooluid_key) == tooluid_item:
  4223. for key, value in tooluid_value.items():
  4224. if key == 'tooldia':
  4225. temp_dia[key] = tooldia_item
  4226. # update the 'offset', 'type' and 'tool_type' sections
  4227. if key == 'offset':
  4228. temp_dia[key] = offset_item
  4229. if key == 'type':
  4230. temp_dia[key] = type_item
  4231. if key == 'tool_type':
  4232. temp_dia[key] = tool_type_item
  4233. if key == 'offset_value':
  4234. temp_dia[key] = offset_value_item
  4235. if key == 'data':
  4236. # update the 'data' section
  4237. for data_key in tooluid_value[key].keys():
  4238. for form_key, form_value in self.form_fields.items():
  4239. if form_key == data_key:
  4240. temp_data[data_key] = form_value.get_value()
  4241. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  4242. # updated from self.app.defaults
  4243. if data_key not in self.form_fields:
  4244. temp_data[data_key] = value[data_key]
  4245. temp_dia[key] = deepcopy(temp_data)
  4246. temp_data.clear()
  4247. if key == 'solid_geometry':
  4248. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  4249. temp_tools[tooluid_key] = deepcopy(temp_dia)
  4250. else:
  4251. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  4252. self.tools.clear()
  4253. self.tools = deepcopy(temp_tools)
  4254. temp_tools.clear()
  4255. self.ui_connect()
  4256. def update_common_param_in_storage(self):
  4257. for tooluid_value in self.tools.values():
  4258. tooluid_value['data']['ppname_g'] = self.ui.pp_geometry_name_cb.get_value()
  4259. def select_tools_table_row(self, row, clearsel=None):
  4260. if clearsel:
  4261. self.ui.geo_tools_table.clearSelection()
  4262. if self.ui.geo_tools_table.rowCount() > 0:
  4263. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  4264. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  4265. def export_dxf(self):
  4266. units = self.app.defaults['units'].upper()
  4267. dwg = None
  4268. try:
  4269. dwg = ezdxf.new('R2010')
  4270. msp = dwg.modelspace()
  4271. def g2dxf(dxf_space, geo):
  4272. if isinstance(geo, MultiPolygon):
  4273. for poly in geo:
  4274. ext_points = list(poly.exterior.coords)
  4275. dxf_space.add_lwpolyline(ext_points)
  4276. for interior in poly.interiors:
  4277. dxf_space.add_lwpolyline(list(interior.coords))
  4278. if isinstance(geo, Polygon):
  4279. ext_points = list(geo.exterior.coords)
  4280. dxf_space.add_lwpolyline(ext_points)
  4281. for interior in geo.interiors:
  4282. dxf_space.add_lwpolyline(list(interior.coords))
  4283. if isinstance(geo, MultiLineString):
  4284. for line in geo:
  4285. dxf_space.add_lwpolyline(list(line.coords))
  4286. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  4287. dxf_space.add_lwpolyline(list(geo.coords))
  4288. multigeo_solid_geometry = []
  4289. if self.multigeo:
  4290. for tool in self.tools:
  4291. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  4292. else:
  4293. multigeo_solid_geometry = self.solid_geometry
  4294. for geo in multigeo_solid_geometry:
  4295. if type(geo) == list:
  4296. for g in geo:
  4297. g2dxf(msp, g)
  4298. else:
  4299. g2dxf(msp, geo)
  4300. # points = FlatCAMGeometry.get_pts(geo)
  4301. # msp.add_lwpolyline(points)
  4302. except Exception as e:
  4303. log.debug(str(e))
  4304. return dwg
  4305. def get_selected_tools_table_items(self):
  4306. """
  4307. Returns a list of lists, each list in the list is made out of row elements
  4308. :return: List of table_tools items.
  4309. :rtype: list
  4310. """
  4311. table_tools_items = []
  4312. if self.multigeo:
  4313. for x in self.ui.geo_tools_table.selectedItems():
  4314. elem = list()
  4315. txt = ''
  4316. for column in range(0, self.ui.geo_tools_table.columnCount()):
  4317. try:
  4318. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4319. except AttributeError:
  4320. try:
  4321. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4322. except AttributeError:
  4323. pass
  4324. elem.append(txt)
  4325. table_tools_items.append(deepcopy(elem))
  4326. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  4327. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  4328. else:
  4329. for x in self.ui.geo_tools_table.selectedItems():
  4330. r = []
  4331. txt = ''
  4332. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  4333. # so we don't read them
  4334. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  4335. # the columns have items that have text but also have items that are widgets
  4336. # for which the text they hold has to be read differently
  4337. try:
  4338. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4339. except AttributeError:
  4340. try:
  4341. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4342. except AttributeError:
  4343. pass
  4344. r.append(txt)
  4345. table_tools_items.append(r)
  4346. for item in table_tools_items:
  4347. item[0] = str(item[0])
  4348. return table_tools_items
  4349. def on_pp_changed(self):
  4350. current_pp = self.ui.pp_geometry_name_cb.get_value()
  4351. if current_pp == 'hpgl':
  4352. self.old_pp_state = self.ui.mpass_cb.get_value()
  4353. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  4354. self.ui.mpass_cb.set_value(False)
  4355. self.ui.mpass_cb.setDisabled(True)
  4356. self.ui.toolchangeg_cb.set_value(True)
  4357. self.ui.toolchangeg_cb.setDisabled(True)
  4358. else:
  4359. self.ui.mpass_cb.set_value(self.old_pp_state)
  4360. self.ui.mpass_cb.setDisabled(False)
  4361. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  4362. self.ui.toolchangeg_cb.setDisabled(False)
  4363. if "toolchange_probe" in current_pp.lower():
  4364. self.ui.pdepth_entry.setVisible(True)
  4365. self.ui.pdepth_label.show()
  4366. self.ui.feedrate_probe_entry.setVisible(True)
  4367. self.ui.feedrate_probe_label.show()
  4368. else:
  4369. self.ui.pdepth_entry.setVisible(False)
  4370. self.ui.pdepth_label.hide()
  4371. self.ui.feedrate_probe_entry.setVisible(False)
  4372. self.ui.feedrate_probe_label.hide()
  4373. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  4374. self.ui.fr_rapidlabel.show()
  4375. self.ui.feedrate_rapid_entry.show()
  4376. else:
  4377. self.ui.fr_rapidlabel.hide()
  4378. self.ui.feedrate_rapid_entry.hide()
  4379. if 'laser' in current_pp.lower():
  4380. self.ui.cutzlabel.hide()
  4381. self.ui.cutz_entry.hide()
  4382. try:
  4383. self.ui.mpass_cb.hide()
  4384. self.ui.maxdepth_entry.hide()
  4385. except AttributeError:
  4386. pass
  4387. if 'marlin' in current_pp.lower():
  4388. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  4389. self.ui.endz_label.show()
  4390. self.ui.endz_entry.show()
  4391. else:
  4392. self.ui.travelzlabel.hide()
  4393. self.ui.travelz_entry.hide()
  4394. self.ui.endz_label.hide()
  4395. self.ui.endz_entry.hide()
  4396. try:
  4397. self.ui.frzlabel.hide()
  4398. self.ui.feedrate_z_entry.hide()
  4399. except AttributeError:
  4400. pass
  4401. self.ui.dwell_cb.hide()
  4402. self.ui.dwelltime_entry.hide()
  4403. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  4404. try:
  4405. self.ui.tool_offset_label.hide()
  4406. self.ui.offset_entry.hide()
  4407. except AttributeError:
  4408. pass
  4409. else:
  4410. self.ui.cutzlabel.show()
  4411. self.ui.cutz_entry.show()
  4412. try:
  4413. self.ui.mpass_cb.show()
  4414. self.ui.maxdepth_entry.show()
  4415. except AttributeError:
  4416. pass
  4417. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  4418. self.ui.travelzlabel.show()
  4419. self.ui.travelz_entry.show()
  4420. self.ui.endz_label.show()
  4421. self.ui.endz_entry.show()
  4422. try:
  4423. self.ui.frzlabel.show()
  4424. self.ui.feedrate_z_entry.show()
  4425. except AttributeError:
  4426. pass
  4427. self.ui.dwell_cb.show()
  4428. self.ui.dwelltime_entry.show()
  4429. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  4430. try:
  4431. self.ui.tool_offset_lbl.show()
  4432. self.ui.offset_entry.show()
  4433. except AttributeError:
  4434. pass
  4435. def on_generatecnc_button_click(self, *args):
  4436. log.debug("Generating CNCJob from Geometry ...")
  4437. self.app.report_usage("geometry_on_generatecnc_button")
  4438. # this reads the values in the UI form to the self.options dictionary
  4439. self.read_form()
  4440. self.sel_tools = dict()
  4441. try:
  4442. if self.special_group:
  4443. self.app.inform.emit(
  4444. '[WARNING_NOTCL] %s %s %s.' %
  4445. (_("This Geometry can't be processed because it is"), str(self.special_group), _("geometry"))
  4446. )
  4447. return
  4448. except AttributeError:
  4449. pass
  4450. # test to see if we have tools available in the tool table
  4451. if self.ui.geo_tools_table.selectedItems():
  4452. for x in self.ui.geo_tools_table.selectedItems():
  4453. # try:
  4454. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  4455. # except ValueError:
  4456. # # try to convert comma to decimal point. if it's still not working error message and return
  4457. # try:
  4458. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  4459. # except ValueError:
  4460. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  4461. # _("Wrong value format entered, use a number."))
  4462. # return
  4463. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  4464. for tooluid_key, tooluid_value in self.tools.items():
  4465. if int(tooluid_key) == tooluid:
  4466. self.sel_tools.update({
  4467. tooluid: deepcopy(tooluid_value)
  4468. })
  4469. self.mtool_gen_cncjob()
  4470. self.ui.geo_tools_table.clearSelection()
  4471. elif self.ui.geo_tools_table.rowCount() == 1:
  4472. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  4473. for tooluid_key, tooluid_value in self.tools.items():
  4474. if int(tooluid_key) == tooluid:
  4475. self.sel_tools.update({
  4476. tooluid: deepcopy(tooluid_value)
  4477. })
  4478. self.mtool_gen_cncjob()
  4479. self.ui.geo_tools_table.clearSelection()
  4480. else:
  4481. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No tool selected in the tool table ..."))
  4482. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  4483. plot=True, use_thread=True):
  4484. """
  4485. Creates a multi-tool CNCJob out of this Geometry object.
  4486. The actual work is done by the target FlatCAMCNCjob object's
  4487. `generate_from_geometry_2()` method.
  4488. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  4489. (including the solid_geometry)
  4490. :param tools_in_use: the tools that are used, needed by some preprocessors
  4491. :type list of lists, each list in the list is made out of row elements of tools table from GUI
  4492. :param segx: number of segments on the X axis, for auto-levelling
  4493. :param segy: number of segments on the Y axis, for auto-levelling
  4494. :param plot: if True the generated object will be plotted; if False will not be plotted
  4495. :param use_thread: if True use threading
  4496. :return: None
  4497. """
  4498. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  4499. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  4500. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  4501. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  4502. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4503. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4504. try:
  4505. xmin = self.options['xmin']
  4506. ymin = self.options['ymin']
  4507. xmax = self.options['xmax']
  4508. ymax = self.options['ymax']
  4509. except Exception as e:
  4510. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  4511. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  4512. msg += '%s %s' % ('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() -->', str(e))
  4513. msg += traceback.format_exc()
  4514. self.app.inform.emit(msg)
  4515. return
  4516. # Object initialization function for app.new_object()
  4517. # RUNNING ON SEPARATE THREAD!
  4518. def job_init_single_geometry(job_obj, app_obj):
  4519. log.debug("Creating a CNCJob out of a single-geometry")
  4520. assert isinstance(job_obj, FlatCAMCNCjob), \
  4521. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4522. job_obj.options['xmin'] = xmin
  4523. job_obj.options['ymin'] = ymin
  4524. job_obj.options['xmax'] = xmax
  4525. job_obj.options['ymax'] = ymax
  4526. # count the tools
  4527. tool_cnt = 0
  4528. dia_cnc_dict = dict()
  4529. # this turn on the FlatCAMCNCJob plot for multiple tools
  4530. job_obj.multitool = True
  4531. job_obj.multigeo = False
  4532. job_obj.cnc_tools.clear()
  4533. job_obj.options['Tools_in_use'] = tools_in_use
  4534. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4535. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4536. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4537. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4538. for tooluid_key in list(tools_dict.keys()):
  4539. tool_cnt += 1
  4540. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4541. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4542. dia_cnc_dict.update({
  4543. 'tooldia': tooldia_val
  4544. })
  4545. if dia_cnc_dict['offset'] == 'in':
  4546. tool_offset = -dia_cnc_dict['tooldia'] / 2
  4547. elif dia_cnc_dict['offset'].lower() == 'out':
  4548. tool_offset = dia_cnc_dict['tooldia'] / 2
  4549. elif dia_cnc_dict['offset'].lower() == 'custom':
  4550. try:
  4551. offset_value = float(self.ui.tool_offset_entry.get_value())
  4552. except ValueError:
  4553. # try to convert comma to decimal point. if it's still not working error message and return
  4554. try:
  4555. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4556. except ValueError:
  4557. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  4558. return
  4559. if offset_value:
  4560. tool_offset = float(offset_value)
  4561. else:
  4562. self.app.inform.emit(
  4563. '[WARNING] %s' % _("Tool Offset is selected in Tool Table but no value is provided.\n"
  4564. "Add a Tool Offset or change the Offset Type.")
  4565. )
  4566. return
  4567. else:
  4568. tool_offset = 0.0
  4569. dia_cnc_dict.update({
  4570. 'offset_value': tool_offset
  4571. })
  4572. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4573. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4574. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4575. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4576. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4577. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4578. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4579. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4580. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4581. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4582. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4583. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4584. startz = tools_dict[tooluid_key]['data']["startz"]
  4585. endz = tools_dict[tooluid_key]['data']["endz"]
  4586. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4587. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4588. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4589. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4590. spindledir = self.app.defaults['geometry_spindledir']
  4591. tool_solid_geometry = self.solid_geometry
  4592. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4593. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4594. # Propagate options
  4595. job_obj.options["tooldia"] = tooldia_val
  4596. job_obj.options['type'] = 'Geometry'
  4597. job_obj.options['tool_dia'] = tooldia_val
  4598. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4599. # to a value of 0.0005 which is 20 times less than 0.01
  4600. tol = float(self.app.defaults['global_tolerance']) / 20
  4601. res = job_obj.generate_from_geometry_2(
  4602. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  4603. z_cut=z_cut, z_move=z_move,
  4604. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4605. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4606. multidepth=multidepth, depthpercut=depthpercut,
  4607. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4608. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4609. pp_geometry_name=pp_geometry_name,
  4610. tool_no=tool_cnt)
  4611. if res == 'fail':
  4612. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4613. return 'fail'
  4614. else:
  4615. dia_cnc_dict['gcode'] = res
  4616. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4617. # object is the source of gcode
  4618. job_obj.toolchange_xy_type = "geometry"
  4619. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4620. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4621. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4622. # TODO this serve for bounding box creation only; should be optimized
  4623. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4624. # for bounding box values
  4625. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  4626. try:
  4627. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  4628. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  4629. except Exception as e:
  4630. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4631. job_obj.cnc_tools.update({
  4632. tooluid_key: deepcopy(dia_cnc_dict)
  4633. })
  4634. dia_cnc_dict.clear()
  4635. # Object initialization function for app.new_object()
  4636. # RUNNING ON SEPARATE THREAD!
  4637. def job_init_multi_geometry(job_obj, app_obj):
  4638. log.debug("Creating a CNCJob out of a multi-geometry")
  4639. assert isinstance(job_obj, FlatCAMCNCjob), \
  4640. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4641. current_uid = int(1)
  4642. job_obj.options['xmin'] = xmin
  4643. job_obj.options['ymin'] = ymin
  4644. job_obj.options['xmax'] = xmax
  4645. job_obj.options['ymax'] = ymax
  4646. # count the tools
  4647. tool_cnt = 0
  4648. dia_cnc_dict = dict()
  4649. # this turn on the FlatCAMCNCJob plot for multiple tools
  4650. job_obj.multitool = True
  4651. job_obj.multigeo = True
  4652. job_obj.cnc_tools.clear()
  4653. job_obj.options['Tools_in_use'] = tools_in_use
  4654. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4655. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4656. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4657. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4658. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  4659. if not self.solid_geometry:
  4660. a = 0
  4661. for tooluid_key in self.tools:
  4662. if self.tools[tooluid_key]['solid_geometry'] is None:
  4663. a += 1
  4664. if a == len(self.tools):
  4665. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  4666. return 'fail'
  4667. for tooluid_key in list(tools_dict.keys()):
  4668. tool_cnt += 1
  4669. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4670. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4671. dia_cnc_dict.update({
  4672. 'tooldia': tooldia_val
  4673. })
  4674. # find the tool_dia associated with the tooluid_key
  4675. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  4676. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  4677. # for k, v in self.tools.items():
  4678. # if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  4679. # current_uid = int(k)
  4680. # break
  4681. if dia_cnc_dict['offset'] == 'in':
  4682. tool_offset = -tooldia_val / 2
  4683. elif dia_cnc_dict['offset'].lower() == 'out':
  4684. tool_offset = tooldia_val / 2
  4685. elif dia_cnc_dict['offset'].lower() == 'custom':
  4686. offset_value = float(self.ui.tool_offset_entry.get_value())
  4687. if offset_value:
  4688. tool_offset = float(offset_value)
  4689. else:
  4690. self.app.inform.emit('[WARNING] %s' %
  4691. _("Tool Offset is selected in Tool Table but "
  4692. "no value is provided.\n"
  4693. "Add a Tool Offset or change the Offset Type."))
  4694. return
  4695. else:
  4696. tool_offset = 0.0
  4697. dia_cnc_dict.update({
  4698. 'offset_value': tool_offset
  4699. })
  4700. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4701. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4702. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4703. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4704. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4705. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4706. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4707. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4708. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4709. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4710. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4711. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4712. startz = tools_dict[tooluid_key]['data']["startz"]
  4713. endz = tools_dict[tooluid_key]['data']["endz"]
  4714. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4715. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4716. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4717. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4718. spindledir = self.app.defaults['geometry_spindledir']
  4719. tool_solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4720. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4721. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4722. # Propagate options
  4723. job_obj.options["tooldia"] = tooldia_val
  4724. job_obj.options['type'] = 'Geometry'
  4725. job_obj.options['tool_dia'] = tooldia_val
  4726. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4727. # to a value of 0.0005 which is 20 times less than 0.01
  4728. tol = float(self.app.defaults['global_tolerance']) / 20
  4729. res = job_obj.generate_from_multitool_geometry(
  4730. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  4731. tolerance=tol, z_cut=z_cut, z_move=z_move,
  4732. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4733. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4734. multidepth=multidepth, depthpercut=depthpercut,
  4735. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4736. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4737. pp_geometry_name=pp_geometry_name,
  4738. tool_no=tool_cnt)
  4739. if res == 'fail':
  4740. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4741. return 'fail'
  4742. else:
  4743. dia_cnc_dict['gcode'] = res
  4744. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4745. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4746. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4747. # TODO this serve for bounding box creation only; should be optimized
  4748. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4749. # for bounding box values
  4750. # geo_for_bound_values = cascaded_union([
  4751. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  4752. # ])
  4753. try:
  4754. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  4755. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4756. except Exception as e:
  4757. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4758. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4759. # object is the source of gcode
  4760. job_obj.toolchange_xy_type = "geometry"
  4761. job_obj.cnc_tools.update({
  4762. tooluid_key: deepcopy(dia_cnc_dict)
  4763. })
  4764. dia_cnc_dict.clear()
  4765. if use_thread:
  4766. # To be run in separate thread
  4767. def job_thread(app_obj):
  4768. if self.multigeo is False:
  4769. with self.app.proc_container.new(_("Generating CNC Code")):
  4770. if app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  4771. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4772. else:
  4773. with self.app.proc_container.new(_("Generating CNC Code")):
  4774. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  4775. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4776. # Create a promise with the name
  4777. self.app.collection.promise(outname)
  4778. # Send to worker
  4779. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4780. else:
  4781. if self.solid_geometry:
  4782. self.app.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  4783. else:
  4784. self.app.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  4785. def generatecncjob(
  4786. self, outname=None,
  4787. dia=None, offset=None,
  4788. z_cut=None, z_move=None,
  4789. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  4790. spindlespeed=None, dwell=None, dwelltime=None,
  4791. multidepth=None, depthperpass=None,
  4792. toolchange=None, toolchangez=None, toolchangexy=None,
  4793. extracut=None, extracut_length=None, startz=None, endz=None,
  4794. pp=None,
  4795. segx=None, segy=None,
  4796. use_thread=True,
  4797. plot=True):
  4798. """
  4799. Only used for TCL Command.
  4800. Creates a CNCJob out of this Geometry object. The actual
  4801. work is done by the target camlib.CNCjob
  4802. `generate_from_geometry_2()` method.
  4803. :param z_cut: Cut depth (negative)
  4804. :param z_move: Hight of the tool when travelling (not cutting)
  4805. :param feedrate: Feed rate while cutting on X - Y plane
  4806. :param feedrate_z: Feed rate while cutting on Z plane
  4807. :param feedrate_rapid: Feed rate while moving with rapids
  4808. :param dia: Tool diameter
  4809. :param outname: Name of the new object
  4810. :param spindlespeed: Spindle speed (RPM)
  4811. :param pp Name of the preprocessor
  4812. :return: None
  4813. """
  4814. tooldia = dia if dia else float(self.options["cnctooldia"])
  4815. outname = outname if outname is not None else self.options["name"]
  4816. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  4817. z_move = z_move if z_move is not None else float(self.options["travelz"])
  4818. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  4819. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  4820. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  4821. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  4822. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  4823. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4824. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4825. extracut = extracut if extracut is not None else float(self.options["extracut"])
  4826. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  4827. startz = startz if startz is not None else self.options["startz"]
  4828. endz = endz if endz is not None else float(self.options["endz"])
  4829. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4830. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4831. toolchange = toolchange if toolchange else self.options["toolchange"]
  4832. offset = offset if offset else 0.0
  4833. # int or None.
  4834. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  4835. dwell = dwell if dwell else self.options["dwell"]
  4836. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  4837. ppname_g = pp if pp else self.options["ppname_g"]
  4838. # Object initialization function for app.new_object()
  4839. # RUNNING ON SEPARATE THREAD!
  4840. def job_init(job_obj, app_obj):
  4841. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4842. # Propagate options
  4843. job_obj.options["tooldia"] = tooldia
  4844. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4845. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4846. job_obj.options['type'] = 'Geometry'
  4847. job_obj.options['tool_dia'] = tooldia
  4848. job_obj.segx = segx
  4849. job_obj.segy = segy
  4850. job_obj.z_pdepth = float(self.options["z_pdepth"])
  4851. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4852. job_obj.options['xmin'] = self.options['xmin']
  4853. job_obj.options['ymin'] = self.options['ymin']
  4854. job_obj.options['xmax'] = self.options['xmax']
  4855. job_obj.options['ymax'] = self.options['ymax']
  4856. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4857. # to a value of 0.0005 which is 20 times less than 0.01
  4858. tol = float(self.app.defaults['global_tolerance']) / 20
  4859. job_obj.generate_from_geometry_2(
  4860. self, tooldia=tooldia, offset=offset, tolerance=tol,
  4861. z_cut=z_cut, z_move=z_move,
  4862. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4863. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4864. multidepth=multidepth, depthpercut=depthperpass,
  4865. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4866. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4867. pp_geometry_name=ppname_g
  4868. )
  4869. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4870. # source of gcode
  4871. job_obj.toolchange_xy_type = "geometry"
  4872. job_obj.gcode_parse()
  4873. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4874. if use_thread:
  4875. # To be run in separate thread
  4876. def job_thread(app_obj):
  4877. with self.app.proc_container.new(_("Generating CNC Code")):
  4878. app_obj.new_object("cncjob", outname, job_init, plot=plot)
  4879. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created")), outname)
  4880. # Create a promise with the name
  4881. self.app.collection.promise(outname)
  4882. # Send to worker
  4883. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4884. else:
  4885. self.app.new_object("cncjob", outname, job_init, plot=plot)
  4886. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4887. # if self.muted_ui:
  4888. # return
  4889. # self.read_form_item('plot')
  4890. def scale(self, xfactor, yfactor=None, point=None):
  4891. """
  4892. Scales all geometry by a given factor.
  4893. :param xfactor: Factor by which to scale the object's geometry/
  4894. :type xfactor: float
  4895. :param yfactor: Factor by which to scale the object's geometry/
  4896. :type yfactor: float
  4897. :return: None
  4898. :rtype: None
  4899. """
  4900. log.debug("FlatCAMObj.FlatCAMGeometry.scale()")
  4901. try:
  4902. xfactor = float(xfactor)
  4903. except Exception:
  4904. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4905. return
  4906. if yfactor is None:
  4907. yfactor = xfactor
  4908. else:
  4909. try:
  4910. yfactor = float(yfactor)
  4911. except Exception:
  4912. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4913. return
  4914. if xfactor == 1 and yfactor == 1:
  4915. return
  4916. if point is None:
  4917. px = 0
  4918. py = 0
  4919. else:
  4920. px, py = point
  4921. self.geo_len = 0
  4922. self.old_disp_number = 0
  4923. self.el_count = 0
  4924. def scale_recursion(geom):
  4925. if type(geom) is list:
  4926. geoms = list()
  4927. for local_geom in geom:
  4928. geoms.append(scale_recursion(local_geom))
  4929. return geoms
  4930. else:
  4931. try:
  4932. self.el_count += 1
  4933. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4934. if self.old_disp_number < disp_number <= 100:
  4935. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4936. self.old_disp_number = disp_number
  4937. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4938. except AttributeError:
  4939. return geom
  4940. if self.multigeo is True:
  4941. for tool in self.tools:
  4942. # variables to display the percentage of work done
  4943. self.geo_len = 0
  4944. try:
  4945. for g in self.tools[tool]['solid_geometry']:
  4946. self.geo_len += 1
  4947. except TypeError:
  4948. self.geo_len = 1
  4949. self.old_disp_number = 0
  4950. self.el_count = 0
  4951. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4952. try:
  4953. # variables to display the percentage of work done
  4954. self.geo_len = 0
  4955. try:
  4956. self.geo_len = len(self.solid_geometry)
  4957. except TypeError:
  4958. self.geo_len = 1
  4959. self.old_disp_number = 0
  4960. self.el_count = 0
  4961. self.solid_geometry = scale_recursion(self.solid_geometry)
  4962. except AttributeError:
  4963. self.solid_geometry = []
  4964. return
  4965. self.app.proc_container.new_text = ''
  4966. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  4967. def offset(self, vect):
  4968. """
  4969. Offsets all geometry by a given vector/
  4970. :param vect: (x, y) vector by which to offset the object's geometry.
  4971. :type vect: tuple
  4972. :return: None
  4973. :rtype: None
  4974. """
  4975. log.debug("FlatCAMObj.FlatCAMGeometry.offset()")
  4976. try:
  4977. dx, dy = vect
  4978. except TypeError:
  4979. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4980. _("An (x,y) pair of values are needed. "
  4981. "Probable you entered only one value in the Offset field.")
  4982. )
  4983. return
  4984. if dx == 0 and dy == 0:
  4985. return
  4986. self.geo_len = 0
  4987. self.old_disp_number = 0
  4988. self.el_count = 0
  4989. def translate_recursion(geom):
  4990. if type(geom) is list:
  4991. geoms = list()
  4992. for local_geom in geom:
  4993. geoms.append(translate_recursion(local_geom))
  4994. return geoms
  4995. else:
  4996. try:
  4997. self.el_count += 1
  4998. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4999. if self.old_disp_number < disp_number <= 100:
  5000. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5001. self.old_disp_number = disp_number
  5002. return affinity.translate(geom, xoff=dx, yoff=dy)
  5003. except AttributeError:
  5004. return geom
  5005. if self.multigeo is True:
  5006. for tool in self.tools:
  5007. # variables to display the percentage of work done
  5008. self.geo_len = 0
  5009. try:
  5010. for g in self.tools[tool]['solid_geometry']:
  5011. self.geo_len += 1
  5012. except TypeError:
  5013. self.geo_len = 1
  5014. self.old_disp_number = 0
  5015. self.el_count = 0
  5016. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  5017. # variables to display the percentage of work done
  5018. self.geo_len = 0
  5019. try:
  5020. for g in self.solid_geometry:
  5021. self.geo_len += 1
  5022. except TypeError:
  5023. self.geo_len = 1
  5024. self.old_disp_number = 0
  5025. self.el_count = 0
  5026. self.solid_geometry = translate_recursion(self.solid_geometry)
  5027. self.app.proc_container.new_text = ''
  5028. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  5029. def convert_units(self, units):
  5030. log.debug("FlatCAMObj.FlatCAMGeometry.convert_units()")
  5031. self.ui_disconnect()
  5032. factor = Geometry.convert_units(self, units)
  5033. self.options['cutz'] = float(self.options['cutz']) * factor
  5034. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  5035. self.options['travelz'] = float(self.options['travelz']) * factor
  5036. self.options['feedrate'] = float(self.options['feedrate']) * factor
  5037. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  5038. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  5039. self.options['endz'] = float(self.options['endz']) * factor
  5040. # self.options['cnctooldia'] *= factor
  5041. # self.options['painttooldia'] *= factor
  5042. # self.options['paintmargin'] *= factor
  5043. # self.options['paintoverlap'] *= factor
  5044. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  5045. if self.app.defaults["geometry_toolchangexy"] == '':
  5046. self.options['toolchangexy'] = "0.0, 0.0"
  5047. else:
  5048. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  5049. if len(coords_xy) < 2:
  5050. self.app.inform.emit('[ERROR] %s' %
  5051. _("The Toolchange X,Y field in Edit -> Preferences "
  5052. "has to be in the format (x, y)\n"
  5053. "but now there is only one value, not two.")
  5054. )
  5055. return 'fail'
  5056. coords_xy[0] *= factor
  5057. coords_xy[1] *= factor
  5058. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  5059. if self.options['startz'] is not None:
  5060. self.options['startz'] = float(self.options['startz']) * factor
  5061. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  5062. 'endz', 'toolchangez']
  5063. if isinstance(self, FlatCAMGeometry):
  5064. temp_tools_dict = {}
  5065. tool_dia_copy = {}
  5066. data_copy = {}
  5067. for tooluid_key, tooluid_value in self.tools.items():
  5068. for dia_key, dia_value in tooluid_value.items():
  5069. if dia_key == 'tooldia':
  5070. dia_value *= factor
  5071. dia_value = float('%.*f' % (self.decimals, dia_value))
  5072. tool_dia_copy[dia_key] = dia_value
  5073. if dia_key == 'offset':
  5074. tool_dia_copy[dia_key] = dia_value
  5075. if dia_key == 'offset_value':
  5076. dia_value *= factor
  5077. tool_dia_copy[dia_key] = dia_value
  5078. # convert the value in the Custom Tool Offset entry in UI
  5079. custom_offset = None
  5080. try:
  5081. custom_offset = float(self.ui.tool_offset_entry.get_value())
  5082. except ValueError:
  5083. # try to convert comma to decimal point. if it's still not working error message and return
  5084. try:
  5085. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  5086. except ValueError:
  5087. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5088. _("Wrong value format entered, use a number."))
  5089. return
  5090. except TypeError:
  5091. pass
  5092. if custom_offset:
  5093. custom_offset *= factor
  5094. self.ui.tool_offset_entry.set_value(custom_offset)
  5095. if dia_key == 'type':
  5096. tool_dia_copy[dia_key] = dia_value
  5097. if dia_key == 'tool_type':
  5098. tool_dia_copy[dia_key] = dia_value
  5099. if dia_key == 'data':
  5100. for data_key, data_value in dia_value.items():
  5101. # convert the form fields that are convertible
  5102. for param in param_list:
  5103. if data_key == param and data_value is not None:
  5104. data_copy[data_key] = data_value * factor
  5105. # copy the other dict entries that are not convertible
  5106. if data_key not in param_list:
  5107. data_copy[data_key] = data_value
  5108. tool_dia_copy[dia_key] = deepcopy(data_copy)
  5109. data_copy.clear()
  5110. temp_tools_dict.update({
  5111. tooluid_key: deepcopy(tool_dia_copy)
  5112. })
  5113. tool_dia_copy.clear()
  5114. self.tools.clear()
  5115. self.tools = deepcopy(temp_tools_dict)
  5116. # if there is a value in the new tool field then convert that one too
  5117. try:
  5118. self.ui.addtool_entry.returnPressed.disconnect()
  5119. except TypeError:
  5120. pass
  5121. tooldia = self.ui.addtool_entry.get_value()
  5122. if tooldia:
  5123. tooldia *= factor
  5124. tooldia = float('%.*f' % (self.decimals, tooldia))
  5125. self.ui.addtool_entry.set_value(tooldia)
  5126. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  5127. return factor
  5128. def plot_element(self, element, color=None, visible=None):
  5129. if color is None:
  5130. color = '#FF0000FF'
  5131. visible = visible if visible else self.options['plot']
  5132. try:
  5133. for sub_el in element:
  5134. self.plot_element(sub_el, color=color)
  5135. except TypeError: # Element is not iterable...
  5136. # if self.app.is_legacy is False:
  5137. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  5138. def plot(self, visible=None, kind=None):
  5139. """
  5140. Plot the object.
  5141. :param visible: Controls if the added shape is visible of not
  5142. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  5143. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  5144. :return:
  5145. """
  5146. # Does all the required setup and returns False
  5147. # if the 'ptint' option is set to False.
  5148. if not FlatCAMObj.plot(self):
  5149. return
  5150. try:
  5151. # plot solid geometries found as members of self.tools attribute dict
  5152. # for MultiGeo
  5153. if self.multigeo is True: # geo multi tool usage
  5154. for tooluid_key in self.tools:
  5155. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  5156. self.plot_element(solid_geometry, visible=visible,
  5157. color=self.app.defaults["geometry_plot_line"])
  5158. else:
  5159. # plot solid geometry that may be an direct attribute of the geometry object
  5160. # for SingleGeo
  5161. if self.solid_geometry:
  5162. self.plot_element(self.solid_geometry, visible=visible,
  5163. color=self.app.defaults["geometry_plot_line"])
  5164. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  5165. self.shapes.redraw()
  5166. except (ObjectDeleted, AttributeError):
  5167. self.shapes.clear(update=True)
  5168. def on_plot_cb_click(self, *args):
  5169. if self.muted_ui:
  5170. return
  5171. self.read_form_item('plot')
  5172. self.plot()
  5173. self.ui_disconnect()
  5174. cb_flag = self.ui.plot_cb.isChecked()
  5175. for row in range(self.ui.geo_tools_table.rowCount()):
  5176. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  5177. if cb_flag:
  5178. table_cb.setChecked(True)
  5179. else:
  5180. table_cb.setChecked(False)
  5181. self.ui_connect()
  5182. def on_plot_cb_click_table(self):
  5183. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  5184. self.ui_disconnect()
  5185. # cw = self.sender()
  5186. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  5187. # cw_row = cw_index.row()
  5188. check_row = 0
  5189. self.shapes.clear(update=True)
  5190. for tooluid_key in self.tools:
  5191. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  5192. # find the geo_tool_table row associated with the tooluid_key
  5193. for row in range(self.ui.geo_tools_table.rowCount()):
  5194. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  5195. if tooluid_item == int(tooluid_key):
  5196. check_row = row
  5197. break
  5198. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  5199. self.plot_element(element=solid_geometry, visible=True)
  5200. self.shapes.redraw()
  5201. # make sure that the general plot is disabled if one of the row plot's are disabled and
  5202. # if all the row plot's are enabled also enable the general plot checkbox
  5203. cb_cnt = 0
  5204. total_row = self.ui.geo_tools_table.rowCount()
  5205. for row in range(total_row):
  5206. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  5207. cb_cnt += 1
  5208. else:
  5209. cb_cnt -= 1
  5210. if cb_cnt < total_row:
  5211. self.ui.plot_cb.setChecked(False)
  5212. else:
  5213. self.ui.plot_cb.setChecked(True)
  5214. self.ui_connect()
  5215. def merge(self, geo_list, geo_final, multigeo=None):
  5216. """
  5217. Merges the geometry of objects in grb_list into
  5218. the geometry of geo_final.
  5219. :param geo_list: List of FlatCAMGerber Objects to join.
  5220. :param geo_final: Destination FlatCAMGerber object.
  5221. :param multigeo: if the merged geometry objects are of type MultiGeo
  5222. :return: None
  5223. """
  5224. if geo_final.solid_geometry is None:
  5225. geo_final.solid_geometry = list()
  5226. try:
  5227. __ = iter(geo_final.solid_geometry)
  5228. except TypeError:
  5229. geo_final.solid_geometry = [geo_final.solid_geometry]
  5230. new_solid_geometry = list()
  5231. new_options = dict()
  5232. new_tools = dict()
  5233. for geo_obj in geo_list:
  5234. for option in geo_obj.options:
  5235. if option is not 'name':
  5236. try:
  5237. new_options[option] = deepcopy(geo_obj.options[option])
  5238. except Exception as e:
  5239. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  5240. # Expand lists
  5241. if type(geo_obj) is list:
  5242. FlatCAMGeometry.merge(self, geo_list=geo_obj, geo_final=geo_final)
  5243. # If not list, just append
  5244. else:
  5245. if multigeo is None or multigeo is False:
  5246. geo_final.multigeo = False
  5247. else:
  5248. geo_final.multigeo = True
  5249. try:
  5250. new_solid_geometry += deepcopy(geo_obj.solid_geometry)
  5251. except Exception as e:
  5252. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  5253. # find the tool_uid maximum value in the geo_final
  5254. try:
  5255. max_uid = max([int(i) for i in new_tools.keys()])
  5256. except ValueError:
  5257. max_uid = 0
  5258. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  5259. # to merge the obj.tools as it is likely there is none to merge.
  5260. if not isinstance(geo_obj, FlatCAMGerber) and not isinstance(geo_obj, FlatCAMExcellon):
  5261. for tool_uid in geo_obj.tools:
  5262. max_uid += 1
  5263. new_tools[max_uid] = deepcopy(geo_obj.tools[tool_uid])
  5264. geo_final.options.update(new_options)
  5265. geo_final.solid_geometry = new_solid_geometry
  5266. geo_final.tools = new_tools
  5267. @staticmethod
  5268. def get_pts(o):
  5269. """
  5270. Returns a list of all points in the object, where
  5271. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  5272. of such. Search is done recursively.
  5273. :param: geometric object
  5274. :return: List of points
  5275. :rtype: list
  5276. """
  5277. pts = []
  5278. # Iterable: descend into each item.
  5279. try:
  5280. for subo in o:
  5281. pts += FlatCAMGeometry.get_pts(subo)
  5282. # Non-iterable
  5283. except TypeError:
  5284. if o is not None:
  5285. if type(o) == MultiPolygon:
  5286. for poly in o:
  5287. pts += FlatCAMGeometry.get_pts(poly)
  5288. # ## Descend into .exerior and .interiors
  5289. elif type(o) == Polygon:
  5290. pts += FlatCAMGeometry.get_pts(o.exterior)
  5291. for i in o.interiors:
  5292. pts += FlatCAMGeometry.get_pts(i)
  5293. elif type(o) == MultiLineString:
  5294. for line in o:
  5295. pts += FlatCAMGeometry.get_pts(line)
  5296. # ## Has .coords: list them.
  5297. else:
  5298. pts += list(o.coords)
  5299. else:
  5300. return
  5301. return pts
  5302. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  5303. """
  5304. Represents G-Code.
  5305. """
  5306. optionChanged = QtCore.pyqtSignal(str)
  5307. ui_type = CNCObjectUI
  5308. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  5309. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  5310. spindlespeed=None):
  5311. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  5312. self.decimals = self.app.decimals
  5313. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  5314. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  5315. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  5316. FlatCAMObj.__init__(self, name)
  5317. self.kind = "cncjob"
  5318. self.options.update({
  5319. "plot": True,
  5320. "tooldia": 0.03937, # 0.4mm in inches
  5321. "append": "",
  5322. "prepend": "",
  5323. "dwell": False,
  5324. "dwelltime": 1,
  5325. "type": 'Geometry',
  5326. "toolchange_macro": '',
  5327. "toolchange_macro_enable": False
  5328. })
  5329. '''
  5330. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5331. diameter of the tools and the value is another dict that will hold the data under the following form:
  5332. {tooldia: {
  5333. 'tooluid': 1,
  5334. 'offset': 'Path',
  5335. 'type_item': 'Rough',
  5336. 'tool_type': 'C1',
  5337. 'data': {} # a dict to hold the parameters
  5338. 'gcode': "" # a string with the actual GCODE
  5339. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  5340. (cut or move)
  5341. 'solid_geometry': []
  5342. },
  5343. ...
  5344. }
  5345. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  5346. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5347. '''
  5348. self.cnc_tools = dict()
  5349. '''
  5350. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5351. diameter of the tools and the value is another dict that will hold the data under the following form:
  5352. {tooldia: {
  5353. 'tool': int,
  5354. 'nr_drills': int,
  5355. 'nr_slots': int,
  5356. 'offset': float,
  5357. 'data': {} # a dict to hold the parameters
  5358. 'gcode': "" # a string with the actual GCODE
  5359. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  5360. 'solid_geometry': []
  5361. },
  5362. ...
  5363. }
  5364. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  5365. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  5366. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5367. '''
  5368. self.exc_cnc_tools = dict()
  5369. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  5370. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  5371. self.special_group = None
  5372. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  5373. # (like the one in the TCL Command), False
  5374. self.multitool = False
  5375. # determine if the GCode was generated out of a Excellon object or a Geometry object
  5376. self.origin_kind = None
  5377. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  5378. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  5379. self.g_x_re = re.compile(gcodex_re_string)
  5380. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  5381. self.g_y_re = re.compile(gcodey_re_string)
  5382. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  5383. self.g_z_re = re.compile(gcodez_re_string)
  5384. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  5385. self.g_f_re = re.compile(gcodef_re_string)
  5386. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  5387. self.g_t_re = re.compile(gcodet_re_string)
  5388. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  5389. self.g_nr_re = re.compile(gcodenr_re_string)
  5390. # Attributes to be included in serialization
  5391. # Always append to it because it carries contents
  5392. # from predecessors.
  5393. self.ser_attrs += ['options', 'kind', 'origin_kind', 'cnc_tools', 'exc_cnc_tools', 'multitool']
  5394. if self.app.is_legacy is False:
  5395. self.text_col = self.app.plotcanvas.new_text_collection()
  5396. self.text_col.enabled = True
  5397. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  5398. self.gcode_editor_tab = None
  5399. self.units_found = self.app.defaults['units']
  5400. def build_ui(self):
  5401. self.ui_disconnect()
  5402. FlatCAMObj.build_ui(self)
  5403. self.units = self.app.defaults['units'].upper()
  5404. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  5405. self.ui.cnc_tools_table.hide()
  5406. if self.cnc_tools:
  5407. self.ui.cnc_tools_table.show()
  5408. self.build_cnc_tools_table()
  5409. self.ui.exc_cnc_tools_table.hide()
  5410. if self.exc_cnc_tools:
  5411. self.ui.exc_cnc_tools_table.show()
  5412. self.build_excellon_cnc_tools()
  5413. #
  5414. self.ui_connect()
  5415. def build_cnc_tools_table(self):
  5416. tool_idx = 0
  5417. n = len(self.cnc_tools)
  5418. self.ui.cnc_tools_table.setRowCount(n)
  5419. for dia_key, dia_value in self.cnc_tools.items():
  5420. tool_idx += 1
  5421. row_no = tool_idx - 1
  5422. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5423. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  5424. self.ui.cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  5425. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  5426. # There are no tool bits in MM with more than 2 decimals diameter.
  5427. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  5428. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  5429. offset_txt = list(str(dia_value['offset']))
  5430. offset_txt[0] = offset_txt[0].upper()
  5431. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  5432. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  5433. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  5434. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  5435. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5436. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5437. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5438. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5439. # hack so the checkbox stay centered in the table cell
  5440. # used this:
  5441. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5442. # plot_item = QtWidgets.QWidget()
  5443. # checkbox = FCCheckBox()
  5444. # checkbox.setCheckState(QtCore.Qt.Checked)
  5445. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5446. # qhboxlayout.addWidget(checkbox)
  5447. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5448. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5449. plot_item = FCCheckBox()
  5450. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5451. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  5452. if self.ui.plot_cb.isChecked():
  5453. plot_item.setChecked(True)
  5454. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5455. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  5456. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  5457. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  5458. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5459. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  5460. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5461. # make the diameter column editable
  5462. # for row in range(tool_idx):
  5463. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  5464. # QtCore.Qt.ItemIsEnabled)
  5465. for row in range(tool_idx):
  5466. self.ui.cnc_tools_table.item(row, 0).setFlags(
  5467. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5468. self.ui.cnc_tools_table.resizeColumnsToContents()
  5469. self.ui.cnc_tools_table.resizeRowsToContents()
  5470. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  5471. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  5472. vertical_header.hide()
  5473. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5474. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  5475. horizontal_header.setMinimumSectionSize(10)
  5476. horizontal_header.setDefaultSectionSize(70)
  5477. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5478. horizontal_header.resizeSection(0, 20)
  5479. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5480. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5481. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  5482. horizontal_header.resizeSection(4, 40)
  5483. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5484. horizontal_header.resizeSection(4, 17)
  5485. # horizontal_header.setStretchLastSection(True)
  5486. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5487. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  5488. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  5489. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  5490. # self.ui.geo_tools_table.setSortingEnabled(True)
  5491. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  5492. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  5493. def build_excellon_cnc_tools(self):
  5494. tool_idx = 0
  5495. n = len(self.exc_cnc_tools)
  5496. self.ui.exc_cnc_tools_table.setRowCount(n)
  5497. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  5498. tool_idx += 1
  5499. row_no = tool_idx - 1
  5500. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5501. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  5502. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  5503. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  5504. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset_z']) + self.z_cut))
  5505. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  5506. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5507. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5508. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5509. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5510. # hack so the checkbox stay centered in the table cell
  5511. # used this:
  5512. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5513. # plot_item = QtWidgets.QWidget()
  5514. # checkbox = FCCheckBox()
  5515. # checkbox.setCheckState(QtCore.Qt.Checked)
  5516. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5517. # qhboxlayout.addWidget(checkbox)
  5518. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5519. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5520. plot_item = FCCheckBox()
  5521. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5522. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  5523. if self.ui.plot_cb.isChecked():
  5524. plot_item.setChecked(True)
  5525. # TODO until the feature of individual plot for an Excellon tool is implemented
  5526. plot_item.setDisabled(True)
  5527. self.ui.exc_cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  5528. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5529. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  5530. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  5531. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5532. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  5533. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  5534. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5535. for row in range(tool_idx):
  5536. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  5537. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5538. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  5539. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  5540. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  5541. vertical_header.hide()
  5542. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5543. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  5544. horizontal_header.setMinimumSectionSize(10)
  5545. horizontal_header.setDefaultSectionSize(70)
  5546. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5547. horizontal_header.resizeSection(0, 20)
  5548. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5549. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  5550. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5551. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  5552. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5553. # horizontal_header.setStretchLastSection(True)
  5554. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5555. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  5556. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  5557. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5558. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5559. def set_ui(self, ui):
  5560. FlatCAMObj.set_ui(self, ui)
  5561. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  5562. assert isinstance(self.ui, CNCObjectUI), \
  5563. "Expected a CNCObjectUI, got %s" % type(self.ui)
  5564. self.units = self.app.defaults['units'].upper()
  5565. self.units_found = self.app.defaults['units']
  5566. # this signal has to be connected to it's slot before the defaults are populated
  5567. # the decision done in the slot has to override the default value set bellow
  5568. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  5569. self.form_fields.update({
  5570. "plot": self.ui.plot_cb,
  5571. "tooldia": self.ui.tooldia_entry,
  5572. "append": self.ui.append_text,
  5573. "prepend": self.ui.prepend_text,
  5574. "toolchange_macro": self.ui.toolchange_text,
  5575. "toolchange_macro_enable": self.ui.toolchange_cb
  5576. })
  5577. # Fill form fields only on object create
  5578. self.to_form()
  5579. # this means that the object that created this CNCJob was an Excellon or Geometry
  5580. try:
  5581. if self.travel_distance:
  5582. self.ui.t_distance_label.show()
  5583. self.ui.t_distance_entry.setVisible(True)
  5584. self.ui.t_distance_entry.setDisabled(True)
  5585. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  5586. self.ui.units_label.setText(str(self.units).lower())
  5587. self.ui.units_label.setDisabled(True)
  5588. self.ui.t_time_label.show()
  5589. self.ui.t_time_entry.setVisible(True)
  5590. self.ui.t_time_entry.setDisabled(True)
  5591. # if time is more than 1 then we have minutes, else we have seconds
  5592. if self.routing_time > 1:
  5593. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  5594. self.ui.units_time_label.setText('min')
  5595. else:
  5596. time_r = self.routing_time * 60
  5597. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  5598. self.ui.units_time_label.setText('sec')
  5599. self.ui.units_time_label.setDisabled(True)
  5600. except AttributeError:
  5601. pass
  5602. if self.multitool is False:
  5603. self.ui.tooldia_entry.show()
  5604. self.ui.updateplot_button.show()
  5605. else:
  5606. self.ui.tooldia_entry.hide()
  5607. self.ui.updateplot_button.hide()
  5608. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  5609. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  5610. try:
  5611. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  5612. except (TypeError, AttributeError):
  5613. pass
  5614. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  5615. # set if to display text annotations
  5616. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  5617. # Show/Hide Advanced Options
  5618. if self.app.defaults["global_app_level"] == 'b':
  5619. self.ui.level.setText(_(
  5620. '<span style="color:green;"><b>Basic</b></span>'
  5621. ))
  5622. self.ui.cnc_frame.hide()
  5623. else:
  5624. self.ui.level.setText(_(
  5625. '<span style="color:red;"><b>Advanced</b></span>'
  5626. ))
  5627. self.ui.cnc_frame.show()
  5628. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  5629. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  5630. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  5631. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  5632. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  5633. def on_cnc_custom_parameters(self, signal_text):
  5634. if signal_text == 'Parameters':
  5635. return
  5636. else:
  5637. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5638. def ui_connect(self):
  5639. for row in range(self.ui.cnc_tools_table.rowCount()):
  5640. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  5641. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  5642. def ui_disconnect(self):
  5643. for row in range(self.ui.cnc_tools_table.rowCount()):
  5644. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  5645. try:
  5646. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  5647. except (TypeError, AttributeError):
  5648. pass
  5649. def on_updateplot_button_click(self, *args):
  5650. """
  5651. Callback for the "Updata Plot" button. Reads the form for updates
  5652. and plots the object.
  5653. """
  5654. self.read_form()
  5655. self.on_plot_kind_change()
  5656. def on_plot_kind_change(self):
  5657. kind = self.ui.cncplot_method_combo.get_value()
  5658. def worker_task():
  5659. with self.app.proc_container.new(_("Plotting...")):
  5660. self.plot(kind=kind)
  5661. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  5662. def on_exportgcode_button_click(self, *args):
  5663. self.app.report_usage("cncjob_on_exportgcode_button")
  5664. self.read_form()
  5665. name = self.app.collection.get_active().options['name']
  5666. save_gcode = False
  5667. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5668. _filter_ = "RML1 Files (*.rol);;All Files (*.*)"
  5669. elif 'hpgl' in self.pp_geometry_name:
  5670. _filter_ = "HPGL Files (*.plt);;All Files (*.*)"
  5671. else:
  5672. save_gcode = True
  5673. _filter_ = self.app.defaults['cncjob_save_filters']
  5674. try:
  5675. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  5676. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5677. caption=_("Export Machine Code ..."),
  5678. directory=dir_file_to_save,
  5679. filter=_filter_
  5680. )
  5681. except TypeError:
  5682. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  5683. filename = str(filename)
  5684. if filename == '':
  5685. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Machine Code cancelled ..."))
  5686. return
  5687. else:
  5688. if save_gcode is True:
  5689. used_extension = filename.rpartition('.')[2]
  5690. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  5691. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  5692. self.ui.name_entry.set_value(new_name)
  5693. self.on_name_activate(silent=True)
  5694. preamble = str(self.ui.prepend_text.get_value())
  5695. postamble = str(self.ui.append_text.get_value())
  5696. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  5697. if gc == 'fail':
  5698. return
  5699. if self.app.defaults["global_open_style"] is False:
  5700. self.app.file_opened.emit("gcode", filename)
  5701. self.app.file_saved.emit("gcode", filename)
  5702. self.app.inform.emit('[success] %s: %s' %
  5703. (_("Machine Code file saved to"), filename))
  5704. def on_edit_code_click(self, *args):
  5705. self.app.proc_container.view.set_busy(_("Loading..."))
  5706. preamble = str(self.ui.prepend_text.get_value())
  5707. postamble = str(self.ui.append_text.get_value())
  5708. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  5709. if gco == 'fail':
  5710. return
  5711. else:
  5712. self.app.gcode_edited = gco
  5713. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  5714. # add the tab if it was closed
  5715. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Editor"))
  5716. self.gcode_editor_tab.setObjectName('code_editor_tab')
  5717. # delete the absolute and relative position and messages in the infobar
  5718. self.app.ui.position_label.setText("")
  5719. self.app.ui.rel_position_label.setText("")
  5720. # first clear previous text in text editor (if any)
  5721. self.gcode_editor_tab.code_editor.clear()
  5722. self.gcode_editor_tab.code_editor.setReadOnly(False)
  5723. self.gcode_editor_tab.code_editor.completer_enable = False
  5724. self.gcode_editor_tab.buttonRun.hide()
  5725. # Switch plot_area to CNCJob tab
  5726. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  5727. self.gcode_editor_tab.t_frame.hide()
  5728. # then append the text from GCode to the text editor
  5729. try:
  5730. self.gcode_editor_tab.code_editor.setPlainText(self.app.gcode_edited.getvalue())
  5731. # for line in self.app.gcode_edited:
  5732. # QtWidgets.QApplication.processEvents()
  5733. #
  5734. # proc_line = str(line).strip('\n')
  5735. # self.gcode_editor_tab.code_editor.append(proc_line)
  5736. except Exception as e:
  5737. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  5738. self.app.inform.emit('[ERROR] %s %s' % ('FlatCAMCNNJob.on_edit_code_click() -->', str(e)))
  5739. return
  5740. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5741. self.gcode_editor_tab.handleTextChanged()
  5742. self.gcode_editor_tab.t_frame.show()
  5743. self.app.proc_container.view.set_idle()
  5744. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  5745. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  5746. """
  5747. Will create a header to be added to all GCode files generated by FlatCAM
  5748. :param comment_start_symbol: a symbol to be used as the first symbol in a comment
  5749. :param comment_stop_symbol: a symbol to be used as the last symbol in a comment
  5750. :return: a string with a GCode header
  5751. """
  5752. log.debug("FlatCAMCNCJob.gcode_header()")
  5753. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5754. marlin = False
  5755. hpgl = False
  5756. probe_pp = False
  5757. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  5758. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  5759. try:
  5760. for key in self.cnc_tools:
  5761. ppg = self.cnc_tools[key]['data']['ppname_g']
  5762. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  5763. marlin = True
  5764. break
  5765. if ppg == 'hpgl':
  5766. hpgl = True
  5767. break
  5768. if "toolchange_probe" in ppg.lower():
  5769. probe_pp = True
  5770. break
  5771. except KeyError:
  5772. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  5773. pass
  5774. try:
  5775. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  5776. marlin = True
  5777. except KeyError:
  5778. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5779. pass
  5780. try:
  5781. if "toolchange_probe" in self.options['ppname_e'].lower():
  5782. probe_pp = True
  5783. except KeyError:
  5784. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5785. pass
  5786. if marlin is True:
  5787. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5788. (str(self.app.version), str(self.app.version_date)) + '\n'
  5789. gcode += ';Name: ' + str(self.options['name']) + '\n'
  5790. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  5791. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5792. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5793. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  5794. gcode += ';Created on ' + time_str + '\n' + '\n'
  5795. elif hpgl is True:
  5796. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  5797. (str(self.app.version), str(self.app.version_date)) + '";\n'
  5798. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  5799. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  5800. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5801. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5802. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  5803. gcode += 'CO "Created on ' + time_str + '";\n'
  5804. elif probe_pp is True:
  5805. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  5806. (str(self.app.version), str(self.app.version_date)) + '\n'
  5807. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  5808. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  5809. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  5810. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  5811. 'Then zero the Z axis.)\n' + '\n'
  5812. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  5813. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  5814. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5815. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5816. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  5817. gcode += '(Created on ' + time_str + ')\n' + '\n'
  5818. else:
  5819. gcode = '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  5820. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  5821. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  5822. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  5823. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5824. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5825. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  5826. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  5827. return gcode
  5828. def gcode_footer(self, end_command=None):
  5829. """
  5830. :param end_command: 'M02' or 'M30' - String
  5831. :return:
  5832. """
  5833. if end_command:
  5834. return end_command
  5835. else:
  5836. return 'M02'
  5837. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  5838. """
  5839. This will save the GCode from the Gcode object to a file on the OS filesystem
  5840. :param filename: filename for the GCode file
  5841. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  5842. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  5843. :param to_file: if False then no actual file is saved but the app will know that a file was created
  5844. :return: None
  5845. """
  5846. # gcode = ''
  5847. # roland = False
  5848. # hpgl = False
  5849. # isel_icp = False
  5850. include_header = True
  5851. try:
  5852. if self.special_group:
  5853. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  5854. (_("This CNCJob object can't be processed because it is a"),
  5855. str(self.special_group),
  5856. _("CNCJob object")))
  5857. return 'fail'
  5858. except AttributeError:
  5859. pass
  5860. # if this dict is not empty then the object is a Geometry object
  5861. if self.cnc_tools:
  5862. first_key = next(iter(self.cnc_tools))
  5863. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  5864. # if this dict is not empty then the object is an Excellon object
  5865. if self.exc_cnc_tools:
  5866. first_key = next(iter(self.exc_cnc_tools))
  5867. include_header = self.app.preprocessors[self.exc_cnc_tools[first_key]['data']['ppname_e']].include_header
  5868. # # detect if using Roland preprocessor
  5869. # try:
  5870. # for key in self.cnc_tools:
  5871. # if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  5872. # roland = True
  5873. # break
  5874. # except Exception:
  5875. # try:
  5876. # for key in self.cnc_tools:
  5877. # if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  5878. # roland = True
  5879. # break
  5880. # except Exception:
  5881. # pass
  5882. #
  5883. # # detect if using HPGL preprocessor
  5884. # try:
  5885. # for key in self.cnc_tools:
  5886. # if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  5887. # hpgl = True
  5888. # break
  5889. # except Exception:
  5890. # try:
  5891. # for key in self.cnc_tools:
  5892. # if self.cnc_tools[key]['data']['ppname_e'] == 'hpgl':
  5893. # hpgl = True
  5894. # break
  5895. # except Exception:
  5896. # pass
  5897. #
  5898. # # detect if using ISEL_ICP_CNC preprocessor
  5899. # try:
  5900. # for key in self.cnc_tools:
  5901. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_g'].upper():
  5902. # isel_icp = True
  5903. # break
  5904. # except Exception:
  5905. # try:
  5906. # for key in self.cnc_tools:
  5907. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_e'].upper():
  5908. # isel_icp = True
  5909. # break
  5910. # except Exception:
  5911. # pass
  5912. # do not add gcode_header when using the Roland preprocessor, add it for every other preprocessor
  5913. # if roland is False and hpgl is False and isel_icp is False:
  5914. # gcode = self.gcode_header()
  5915. # do not add gcode_header when using the Roland, HPGL or ISEP_ICP_CNC preprocessor (or any other preprocessor
  5916. # that has the include_header attribute set as False, add it for every other preprocessor
  5917. # if include_header:
  5918. # gcode = self.gcode_header()
  5919. # else:
  5920. # gcode = ''
  5921. # # detect if using multi-tool and make the Gcode summation correctly for each case
  5922. # if self.multitool is True:
  5923. # for tooluid_key in self.cnc_tools:
  5924. # for key, value in self.cnc_tools[tooluid_key].items():
  5925. # if key == 'gcode':
  5926. # gcode += value
  5927. # break
  5928. # else:
  5929. # gcode += self.gcode
  5930. # if roland is True:
  5931. # g = preamble + gcode + postamble
  5932. # elif hpgl is True:
  5933. # g = self.gcode_header() + preamble + gcode + postamble
  5934. # else:
  5935. # # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5936. # g_idx = gcode.rfind('G20')
  5937. #
  5938. # # if it did not find 'G20' then search for 'G21'
  5939. # if g_idx == -1:
  5940. # g_idx = gcode.rfind('G21')
  5941. #
  5942. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5943. # # but only when the preprocessor is not ISEL_ICP who is allowed not to have the G20/G21 command
  5944. # if g_idx == -1 and isel_icp is False:
  5945. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5946. # return
  5947. #
  5948. # footer = self.app.defaults['cncjob_footer']
  5949. # end_gcode = self.gcode_footer() if footer is True else ''
  5950. # g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + end_gcode
  5951. gcode = ''
  5952. if include_header is False:
  5953. g = preamble
  5954. # detect if using multi-tool and make the Gcode summation correctly for each case
  5955. if self.multitool is True:
  5956. for tooluid_key in self.cnc_tools:
  5957. for key, value in self.cnc_tools[tooluid_key].items():
  5958. if key == 'gcode':
  5959. gcode += value
  5960. break
  5961. else:
  5962. gcode += self.gcode
  5963. g = g + gcode + postamble
  5964. else:
  5965. # search for the GCode beginning which is usually a G20 or G21
  5966. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5967. # g_idx = gcode.rfind('G20')
  5968. #
  5969. # # if it did not find 'G20' then search for 'G21'
  5970. # if g_idx == -1:
  5971. # g_idx = gcode.rfind('G21')
  5972. #
  5973. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5974. # if g_idx == -1:
  5975. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5976. # return
  5977. # detect if using multi-tool and make the Gcode summation correctly for each case
  5978. if self.multitool is True:
  5979. for tooluid_key in self.cnc_tools:
  5980. for key, value in self.cnc_tools[tooluid_key].items():
  5981. if key == 'gcode':
  5982. gcode += value
  5983. break
  5984. else:
  5985. gcode += self.gcode
  5986. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  5987. # detect if using a HPGL preprocessor
  5988. hpgl = False
  5989. if self.cnc_tools:
  5990. for key in self.cnc_tools:
  5991. if 'ppname_g' in self.cnc_tools[key]['data']:
  5992. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  5993. hpgl = True
  5994. break
  5995. elif self.exc_cnc_tools:
  5996. for key in self.cnc_tools:
  5997. if 'ppname_e' in self.cnc_tools[key]['data']:
  5998. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  5999. hpgl = True
  6000. break
  6001. if hpgl:
  6002. processed_gcode = ''
  6003. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  6004. for gline in gcode.splitlines():
  6005. match = pa_re.search(gline)
  6006. if match:
  6007. x_int = int(float(match.group(1)))
  6008. y_int = int(float(match.group(2)))
  6009. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  6010. processed_gcode += new_line
  6011. else:
  6012. processed_gcode += gline + '\n'
  6013. gcode = processed_gcode
  6014. g = self.gcode_header() + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  6015. else:
  6016. try:
  6017. g_idx = gcode.index('G94')
  6018. g = self.gcode_header() + gcode[:g_idx + 3] + '\n\n' + preamble + '\n' + \
  6019. gcode[(g_idx + 3):] + postamble + end_gcode
  6020. except ValueError:
  6021. self.app.inform.emit('[ERROR_NOTCL] %s' %
  6022. _("G-code does not have a G94 code and we will not include the code in the "
  6023. "'Prepend to GCode' text box"))
  6024. g = self.gcode_header() + '\n' + gcode + postamble + end_gcode
  6025. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  6026. if self.ui.toolchange_cb.get_value() is True:
  6027. # match = self.re_toolchange.search(g)
  6028. if 'M6' in g:
  6029. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  6030. if m6_code is None or m6_code == '':
  6031. self.app.inform.emit(
  6032. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  6033. )
  6034. return 'fail'
  6035. g = g.replace('M6', m6_code)
  6036. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  6037. lines = StringIO(g)
  6038. # Write
  6039. if filename is not None:
  6040. try:
  6041. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  6042. if force_windows_line_endings and sys.platform != 'win32':
  6043. with open(filename, 'w', newline='\r\n') as f:
  6044. for line in lines:
  6045. f.write(line)
  6046. else:
  6047. with open(filename, 'w') as f:
  6048. for line in lines:
  6049. f.write(line)
  6050. except FileNotFoundError:
  6051. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  6052. return
  6053. except PermissionError:
  6054. self.app.inform.emit(
  6055. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  6056. "Most likely another app is holding the file open and not accessible.")
  6057. )
  6058. return 'fail'
  6059. elif to_file is False:
  6060. # Just for adding it to the recent files list.
  6061. if self.app.defaults["global_open_style"] is False:
  6062. self.app.file_opened.emit("cncjob", filename)
  6063. self.app.file_saved.emit("cncjob", filename)
  6064. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  6065. else:
  6066. return lines
  6067. def on_toolchange_custom_clicked(self, signal):
  6068. try:
  6069. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  6070. if self.ui.toolchange_cb.get_value():
  6071. self.ui.toolchange_cb.set_value(False)
  6072. self.app.inform.emit('[WARNING_NOTCL] %s' %
  6073. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  6074. except KeyError:
  6075. try:
  6076. for key in self.cnc_tools:
  6077. ppg = self.cnc_tools[key]['data']['ppname_g']
  6078. if 'toolchange_custom' not in str(ppg).lower():
  6079. print(ppg)
  6080. if self.ui.toolchange_cb.get_value():
  6081. self.ui.toolchange_cb.set_value(False)
  6082. self.app.inform.emit('[WARNING_NOTCL] %s' %
  6083. _("The used preprocessor file has to have in it's name: "
  6084. "'toolchange_custom'"))
  6085. except KeyError:
  6086. self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  6087. def get_gcode(self, preamble='', postamble=''):
  6088. # we need this to be able get_gcode separatelly for shell command export_gcode
  6089. return preamble + '\n' + self.gcode + "\n" + postamble
  6090. def get_svg(self):
  6091. # we need this to be able get_svg separately for shell command export_svg
  6092. pass
  6093. def on_plot_cb_click(self, *args):
  6094. if self.muted_ui:
  6095. return
  6096. kind = self.ui.cncplot_method_combo.get_value()
  6097. self.plot(kind=kind)
  6098. self.read_form_item('plot')
  6099. self.ui_disconnect()
  6100. cb_flag = self.ui.plot_cb.isChecked()
  6101. for row in range(self.ui.cnc_tools_table.rowCount()):
  6102. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  6103. if cb_flag:
  6104. table_cb.setChecked(True)
  6105. else:
  6106. table_cb.setChecked(False)
  6107. self.ui_connect()
  6108. def on_plot_cb_click_table(self):
  6109. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  6110. self.ui_disconnect()
  6111. # cw = self.sender()
  6112. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  6113. # cw_row = cw_index.row()
  6114. kind = self.ui.cncplot_method_combo.get_value()
  6115. self.shapes.clear(update=True)
  6116. for tooluid_key in self.cnc_tools:
  6117. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  6118. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  6119. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  6120. for r in range(self.ui.cnc_tools_table.rowCount()):
  6121. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  6122. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  6123. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  6124. self.shapes.redraw()
  6125. # make sure that the general plot is disabled if one of the row plot's are disabled and
  6126. # if all the row plot's are enabled also enable the general plot checkbox
  6127. cb_cnt = 0
  6128. total_row = self.ui.cnc_tools_table.rowCount()
  6129. for row in range(total_row):
  6130. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  6131. cb_cnt += 1
  6132. else:
  6133. cb_cnt -= 1
  6134. if cb_cnt < total_row:
  6135. self.ui.plot_cb.setChecked(False)
  6136. else:
  6137. self.ui.plot_cb.setChecked(True)
  6138. self.ui_connect()
  6139. def plot(self, visible=None, kind='all'):
  6140. # Does all the required setup and returns False
  6141. # if the 'ptint' option is set to False.
  6142. if not FlatCAMObj.plot(self):
  6143. return
  6144. visible = visible if visible else self.options['plot']
  6145. if self.app.is_legacy is False:
  6146. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  6147. self.text_col.enabled = True
  6148. else:
  6149. self.text_col.enabled = False
  6150. self.annotation.redraw()
  6151. try:
  6152. if self.multitool is False: # single tool usage
  6153. try:
  6154. dia_plot = float(self.options["tooldia"])
  6155. except ValueError:
  6156. # we may have a tuple with only one element and a comma
  6157. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  6158. self.plot2(dia_plot, obj=self, visible=visible, kind=kind)
  6159. else:
  6160. # multiple tools usage
  6161. if self.cnc_tools:
  6162. for tooluid_key in self.cnc_tools:
  6163. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  6164. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  6165. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  6166. # TODO: until the gcode parsed will be stored on each Excellon tool this will not get executed
  6167. if self.exc_cnc_tools:
  6168. for tooldia_key in self.exc_cnc_tools:
  6169. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  6170. # gcode_parsed = self.cnc_tools[tooldia_key]['gcode_parsed']
  6171. gcode_parsed = self.gcode_parsed
  6172. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  6173. self.shapes.redraw()
  6174. except (ObjectDeleted, AttributeError):
  6175. self.shapes.clear(update=True)
  6176. if self.app.is_legacy is False:
  6177. self.annotation.clear(update=True)
  6178. def on_annotation_change(self):
  6179. if self.app.is_legacy is False:
  6180. if self.ui.annotation_cb.get_value():
  6181. self.text_col.enabled = True
  6182. else:
  6183. self.text_col.enabled = False
  6184. # kind = self.ui.cncplot_method_combo.get_value()
  6185. # self.plot(kind=kind)
  6186. self.annotation.redraw()
  6187. else:
  6188. kind = self.ui.cncplot_method_combo.get_value()
  6189. self.plot(kind=kind)
  6190. def convert_units(self, units):
  6191. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  6192. factor = CNCjob.convert_units(self, units)
  6193. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  6194. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  6195. 'endz', 'toolchangez']
  6196. temp_tools_dict = {}
  6197. tool_dia_copy = {}
  6198. data_copy = {}
  6199. for tooluid_key, tooluid_value in self.cnc_tools.items():
  6200. for dia_key, dia_value in tooluid_value.items():
  6201. if dia_key == 'tooldia':
  6202. dia_value *= factor
  6203. dia_value = float('%.*f' % (self.decimals, dia_value))
  6204. tool_dia_copy[dia_key] = dia_value
  6205. if dia_key == 'offset':
  6206. tool_dia_copy[dia_key] = dia_value
  6207. if dia_key == 'offset_value':
  6208. dia_value *= factor
  6209. tool_dia_copy[dia_key] = dia_value
  6210. if dia_key == 'type':
  6211. tool_dia_copy[dia_key] = dia_value
  6212. if dia_key == 'tool_type':
  6213. tool_dia_copy[dia_key] = dia_value
  6214. if dia_key == 'data':
  6215. for data_key, data_value in dia_value.items():
  6216. # convert the form fields that are convertible
  6217. for param in param_list:
  6218. if data_key == param and data_value is not None:
  6219. data_copy[data_key] = data_value * factor
  6220. # copy the other dict entries that are not convertible
  6221. if data_key not in param_list:
  6222. data_copy[data_key] = data_value
  6223. tool_dia_copy[dia_key] = deepcopy(data_copy)
  6224. data_copy.clear()
  6225. if dia_key == 'gcode':
  6226. tool_dia_copy[dia_key] = dia_value
  6227. if dia_key == 'gcode_parsed':
  6228. tool_dia_copy[dia_key] = dia_value
  6229. if dia_key == 'solid_geometry':
  6230. tool_dia_copy[dia_key] = dia_value
  6231. # if dia_key == 'solid_geometry':
  6232. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  6233. # if dia_key == 'gcode_parsed':
  6234. # for g in dia_value:
  6235. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  6236. #
  6237. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  6238. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  6239. temp_tools_dict.update({
  6240. tooluid_key: deepcopy(tool_dia_copy)
  6241. })
  6242. tool_dia_copy.clear()
  6243. self.cnc_tools.clear()
  6244. self.cnc_tools = deepcopy(temp_tools_dict)
  6245. class FlatCAMScript(FlatCAMObj):
  6246. """
  6247. Represents a TCL script object.
  6248. """
  6249. optionChanged = QtCore.pyqtSignal(str)
  6250. ui_type = ScriptObjectUI
  6251. def __init__(self, name):
  6252. self.decimals = self.app.decimals
  6253. FlatCAMApp.App.log.debug("Creating a FlatCAMScript object...")
  6254. FlatCAMObj.__init__(self, name)
  6255. self.kind = "script"
  6256. self.options.update({
  6257. "plot": True,
  6258. "type": 'Script',
  6259. "source_file": '',
  6260. })
  6261. self.units = ''
  6262. self.ser_attrs = ['options', 'kind', 'source_file']
  6263. self.source_file = ''
  6264. self.script_code = ''
  6265. self.units_found = self.app.defaults['units']
  6266. # self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  6267. self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  6268. def set_ui(self, ui):
  6269. FlatCAMObj.set_ui(self, ui)
  6270. FlatCAMApp.App.log.debug("FlatCAMScript.set_ui()")
  6271. assert isinstance(self.ui, ScriptObjectUI), \
  6272. "Expected a ScriptObjectUI, got %s" % type(self.ui)
  6273. self.units = self.app.defaults['units'].upper()
  6274. self.units_found = self.app.defaults['units']
  6275. # Fill form fields only on object create
  6276. self.to_form()
  6277. # Show/Hide Advanced Options
  6278. if self.app.defaults["global_app_level"] == 'b':
  6279. self.ui.level.setText(_(
  6280. '<span style="color:green;"><b>Basic</b></span>'
  6281. ))
  6282. else:
  6283. self.ui.level.setText(_(
  6284. '<span style="color:red;"><b>Advanced</b></span>'
  6285. ))
  6286. # tab_here = False
  6287. # # try to not add too many times a tab that it is already installed
  6288. # for idx in range(self.app.ui.plot_tab_area.count()):
  6289. # if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6290. # tab_here = True
  6291. # break
  6292. #
  6293. # # add the tab if it is not already added
  6294. # if tab_here is False:
  6295. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  6296. # self.script_editor_tab.setObjectName(self.options['name'])
  6297. self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  6298. self.script_editor_tab.setObjectName(self.options['name'])
  6299. # first clear previous text in text editor (if any)
  6300. # self.script_editor_tab.code_editor.clear()
  6301. # self.script_editor_tab.code_editor.setReadOnly(False)
  6302. self.ui.autocomplete_cb.set_value(self.app.defaults['script_autocompleter'])
  6303. self.on_autocomplete_changed(state=self.app.defaults['script_autocompleter'])
  6304. self.script_editor_tab.buttonRun.show()
  6305. # Switch plot_area to CNCJob tab
  6306. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  6307. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6308. self.script_editor_tab.buttonOpen.clicked.disconnect()
  6309. self.script_editor_tab.buttonOpen.clicked.connect(lambda: self.script_editor_tab.handleOpen(filt=flt))
  6310. self.script_editor_tab.buttonSave.clicked.disconnect()
  6311. self.script_editor_tab.buttonSave.clicked.connect(lambda: self.script_editor_tab.handleSaveGCode(filt=flt))
  6312. self.script_editor_tab.buttonRun.clicked.connect(self.handle_run_code)
  6313. self.script_editor_tab.handleTextChanged()
  6314. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6315. self.ser_attrs = ['options', 'kind', 'source_file']
  6316. # ---------------------------------------------------- #
  6317. # ----------- LOAD THE TEXT SOURCE FILE -------------- #
  6318. # ---------------------------------------------------- #
  6319. self.app.proc_container.view.set_busy(_("Loading..."))
  6320. self.script_editor_tab.t_frame.hide()
  6321. try:
  6322. self.script_editor_tab.code_editor.setPlainText(self.source_file)
  6323. # for line in self.source_file.splitlines():
  6324. # QtWidgets.QApplication.processEvents()
  6325. # self.script_editor_tab.code_editor.append(line)
  6326. except Exception as e:
  6327. log.debug("FlatCAMScript.set_ui() --> %s" % str(e))
  6328. self.script_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.End)
  6329. self.script_editor_tab.t_frame.show()
  6330. self.app.proc_container.view.set_idle()
  6331. self.build_ui()
  6332. def build_ui(self):
  6333. FlatCAMObj.build_ui(self)
  6334. def handle_run_code(self):
  6335. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  6336. # tries to print on a hidden widget, therefore show the dock if hidden
  6337. if self.app.ui.shell_dock.isHidden():
  6338. self.app.ui.shell_dock.show()
  6339. self.script_code = deepcopy(self.script_editor_tab.code_editor.toPlainText())
  6340. old_line = ''
  6341. for tcl_command_line in self.script_code.splitlines():
  6342. # do not process lines starting with '#' = comment and empty lines
  6343. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  6344. # id FlatCAM is run in Windows then replace all the slashes with
  6345. # the UNIX style slash that TCL understands
  6346. if sys.platform == 'win32':
  6347. if "open" in tcl_command_line:
  6348. tcl_command_line = tcl_command_line.replace('\\', '/')
  6349. if old_line != '':
  6350. new_command = old_line + tcl_command_line + '\n'
  6351. else:
  6352. new_command = tcl_command_line
  6353. # execute the actual Tcl command
  6354. try:
  6355. self.app.shell.open_processing() # Disables input box.
  6356. result = self.app.tcl.eval(str(new_command))
  6357. if result != 'None':
  6358. self.app.shell.append_output(result + '\n')
  6359. old_line = ''
  6360. except tk.TclError:
  6361. old_line = old_line + tcl_command_line + '\n'
  6362. except Exception as e:
  6363. log.debug("FlatCAMScript.handleRunCode() --> %s" % str(e))
  6364. if old_line != '':
  6365. # it means that the script finished with an error
  6366. result = self.app.tcl.eval("set errorInfo")
  6367. log.error("Exec command Exception: %s" % (result + '\n'))
  6368. self.app.shell.append_error('ERROR: ' + result + '\n')
  6369. self.app.shell.close_processing()
  6370. def on_autocomplete_changed(self, state):
  6371. if state:
  6372. self.script_editor_tab.code_editor.completer_enable = True
  6373. else:
  6374. self.script_editor_tab.code_editor.completer_enable = False
  6375. def to_dict(self):
  6376. """
  6377. Returns a representation of the object as a dictionary.
  6378. Attributes to include are listed in ``self.ser_attrs``.
  6379. :return: A dictionary-encoded copy of the object.
  6380. :rtype: dict
  6381. """
  6382. d = {}
  6383. for attr in self.ser_attrs:
  6384. d[attr] = getattr(self, attr)
  6385. return d
  6386. def from_dict(self, d):
  6387. """
  6388. Sets object's attributes from a dictionary.
  6389. Attributes to include are listed in ``self.ser_attrs``.
  6390. This method will look only for only and all the
  6391. attributes in ``self.ser_attrs``. They must all
  6392. be present. Use only for deserializing saved
  6393. objects.
  6394. :param d: Dictionary of attributes to set in the object.
  6395. :type d: dict
  6396. :return: None
  6397. """
  6398. for attr in self.ser_attrs:
  6399. setattr(self, attr, d[attr])
  6400. class FlatCAMDocument(FlatCAMObj):
  6401. """
  6402. Represents a Document object.
  6403. """
  6404. optionChanged = QtCore.pyqtSignal(str)
  6405. ui_type = DocumentObjectUI
  6406. def __init__(self, name):
  6407. self.decimals = self.app.decimals
  6408. FlatCAMApp.App.log.debug("Creating a Document object...")
  6409. FlatCAMObj.__init__(self, name)
  6410. self.kind = "document"
  6411. self.units = ''
  6412. self.ser_attrs = ['options', 'kind', 'source_file']
  6413. self.source_file = ''
  6414. self.doc_code = ''
  6415. self.font_name = None
  6416. self.font_italic = None
  6417. self.font_bold = None
  6418. self.font_underline = None
  6419. self.document_editor_tab = None
  6420. self._read_only = False
  6421. self.units_found = self.app.defaults['units']
  6422. def set_ui(self, ui):
  6423. FlatCAMObj.set_ui(self, ui)
  6424. FlatCAMApp.App.log.debug("FlatCAMDocument.set_ui()")
  6425. assert isinstance(self.ui, DocumentObjectUI), \
  6426. "Expected a DocumentObjectUI, got %s" % type(self.ui)
  6427. self.units = self.app.defaults['units'].upper()
  6428. self.units_found = self.app.defaults['units']
  6429. # Fill form fields only on object create
  6430. self.to_form()
  6431. # Show/Hide Advanced Options
  6432. if self.app.defaults["global_app_level"] == 'b':
  6433. self.ui.level.setText(_(
  6434. '<span style="color:green;"><b>Basic</b></span>'
  6435. ))
  6436. else:
  6437. self.ui.level.setText(_(
  6438. '<span style="color:red;"><b>Advanced</b></span>'
  6439. ))
  6440. self.document_editor_tab = TextEditor(app=self.app)
  6441. stylesheet = """
  6442. QTextEdit {selection-background-color:%s;
  6443. selection-color:white;
  6444. }
  6445. """ % self.app.defaults["document_sel_color"]
  6446. self.document_editor_tab.code_editor.setStyleSheet(stylesheet)
  6447. # first clear previous text in text editor (if any)
  6448. self.document_editor_tab.code_editor.clear()
  6449. self.document_editor_tab.code_editor.setReadOnly(self._read_only)
  6450. self.document_editor_tab.buttonRun.hide()
  6451. self.ui.autocomplete_cb.set_value(self.app.defaults['document_autocompleter'])
  6452. self.on_autocomplete_changed(state=self.app.defaults['document_autocompleter'])
  6453. self.on_tab_size_change(val=self.app.defaults['document_tab_size'])
  6454. flt = "FlatCAM Docs (*.FlatDoc);;All Files (*.*)"
  6455. # ######################################################################
  6456. # ######################## SIGNALS #####################################
  6457. # ######################################################################
  6458. self.document_editor_tab.buttonOpen.clicked.disconnect()
  6459. self.document_editor_tab.buttonOpen.clicked.connect(lambda: self.document_editor_tab.handleOpen(filt=flt))
  6460. self.document_editor_tab.buttonSave.clicked.disconnect()
  6461. self.document_editor_tab.buttonSave.clicked.connect(lambda: self.document_editor_tab.handleSaveGCode(filt=flt))
  6462. self.document_editor_tab.code_editor.textChanged.connect(self.on_text_changed)
  6463. self.ui.font_type_cb.currentFontChanged.connect(self.font_family)
  6464. self.ui.font_size_cb.activated.connect(self.font_size)
  6465. self.ui.font_bold_tb.clicked.connect(self.on_bold_button)
  6466. self.ui.font_italic_tb.clicked.connect(self.on_italic_button)
  6467. self.ui.font_under_tb.clicked.connect(self.on_underline_button)
  6468. self.ui.font_color_entry.editingFinished.connect(self.on_font_color_entry)
  6469. self.ui.font_color_button.clicked.connect(self.on_font_color_button)
  6470. self.ui.sel_color_entry.editingFinished.connect(self.on_selection_color_entry)
  6471. self.ui.sel_color_button.clicked.connect(self.on_selection_color_button)
  6472. self.ui.al_left_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignLeft))
  6473. self.ui.al_center_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignCenter))
  6474. self.ui.al_right_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignRight))
  6475. self.ui.al_justify_tb.clicked.connect(
  6476. lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignJustify)
  6477. )
  6478. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6479. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6480. # #######################################################################
  6481. self.ui.font_color_entry.set_value(self.app.defaults['document_font_color'])
  6482. self.ui.font_color_button.setStyleSheet(
  6483. "background-color:%s" % str(self.app.defaults['document_font_color']))
  6484. self.ui.sel_color_entry.set_value(self.app.defaults['document_sel_color'])
  6485. self.ui.sel_color_button.setStyleSheet(
  6486. "background-color:%s" % self.app.defaults['document_sel_color'])
  6487. self.ui.font_size_cb.setCurrentIndex(int(self.app.defaults['document_font_size']))
  6488. self.document_editor_tab.handleTextChanged()
  6489. self.ser_attrs = ['options', 'kind', 'source_file']
  6490. if Qt.mightBeRichText(self.source_file):
  6491. self.document_editor_tab.code_editor.setHtml(self.source_file)
  6492. else:
  6493. for line in self.source_file.splitlines():
  6494. self.document_editor_tab.code_editor.append(line)
  6495. self.build_ui()
  6496. @property
  6497. def read_only(self):
  6498. return self._read_only
  6499. @read_only.setter
  6500. def read_only(self, val):
  6501. if val:
  6502. self._read_only = True
  6503. else:
  6504. self._read_only = False
  6505. def build_ui(self):
  6506. FlatCAMObj.build_ui(self)
  6507. tab_here = False
  6508. # try to not add too many times a tab that it is already installed
  6509. for idx in range(self.app.ui.plot_tab_area.count()):
  6510. if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6511. tab_here = True
  6512. break
  6513. # add the tab if it is not already added
  6514. if tab_here is False:
  6515. self.app.ui.plot_tab_area.addTab(self.document_editor_tab, '%s' % _("Document Editor"))
  6516. self.document_editor_tab.setObjectName(self.options['name'])
  6517. # Switch plot_area to CNCJob tab
  6518. self.app.ui.plot_tab_area.setCurrentWidget(self.document_editor_tab)
  6519. def on_autocomplete_changed(self, state):
  6520. if state:
  6521. self.document_editor_tab.code_editor.completer_enable = True
  6522. else:
  6523. self.document_editor_tab.code_editor.completer_enable = False
  6524. def on_tab_size_change(self, val=None):
  6525. try:
  6526. self.ui.tab_size_spinner.returnPressed.disconnect(self.on_tab_size_change)
  6527. except TypeError:
  6528. pass
  6529. if val:
  6530. self.ui.tab_size_spinner.set_value(val)
  6531. tab_balue = int(self.ui.tab_size_spinner.get_value())
  6532. self.document_editor_tab.code_editor.setTabStopWidth(tab_balue)
  6533. self.app.defaults['document_tab_size'] = tab_balue
  6534. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6535. def on_text_changed(self):
  6536. self.source_file = self.document_editor_tab.code_editor.toHtml()
  6537. # print(self.source_file)
  6538. def font_family(self, font):
  6539. # self.document_editor_tab.code_editor.selectAll()
  6540. font.setPointSize(float(self.ui.font_size_cb.get_value()))
  6541. self.document_editor_tab.code_editor.setCurrentFont(font)
  6542. self.font_name = self.ui.font_type_cb.currentFont().family()
  6543. def font_size(self):
  6544. # self.document_editor_tab.code_editor.selectAll()
  6545. self.document_editor_tab.code_editor.setFontPointSize(float(self.ui.font_size_cb.get_value()))
  6546. def on_bold_button(self):
  6547. if self.ui.font_bold_tb.isChecked():
  6548. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Bold)
  6549. self.font_bold = True
  6550. else:
  6551. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Normal)
  6552. self.font_bold = False
  6553. def on_italic_button(self):
  6554. if self.ui.font_italic_tb.isChecked():
  6555. self.document_editor_tab.code_editor.setFontItalic(True)
  6556. self.font_italic = True
  6557. else:
  6558. self.document_editor_tab.code_editor.setFontItalic(False)
  6559. self.font_italic = False
  6560. def on_underline_button(self):
  6561. if self.ui.font_under_tb.isChecked():
  6562. self.document_editor_tab.code_editor.setFontUnderline(True)
  6563. self.font_underline = True
  6564. else:
  6565. self.document_editor_tab.code_editor.setFontUnderline(False)
  6566. self.font_underline = False
  6567. # Setting font colors handlers
  6568. def on_font_color_entry(self):
  6569. self.app.defaults['document_font_color'] = self.ui.font_color_entry.get_value()
  6570. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_font_color']))
  6571. def on_font_color_button(self):
  6572. current_color = QtGui.QColor(self.app.defaults['document_font_color'])
  6573. c_dialog = QtWidgets.QColorDialog()
  6574. font_color = c_dialog.getColor(initial=current_color)
  6575. if font_color.isValid() is False:
  6576. return
  6577. self.document_editor_tab.code_editor.setTextColor(font_color)
  6578. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(font_color.name()))
  6579. new_val = str(font_color.name())
  6580. self.ui.font_color_entry.set_value(new_val)
  6581. self.app.defaults['document_font_color'] = new_val
  6582. # Setting selection colors handlers
  6583. def on_selection_color_entry(self):
  6584. self.app.defaults['document_sel_color'] = self.ui.sel_color_entry.get_value()
  6585. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_sel_color']))
  6586. def on_selection_color_button(self):
  6587. current_color = QtGui.QColor(self.app.defaults['document_sel_color'])
  6588. c_dialog = QtWidgets.QColorDialog()
  6589. sel_color = c_dialog.getColor(initial=current_color)
  6590. if sel_color.isValid() is False:
  6591. return
  6592. p = QtGui.QPalette()
  6593. p.setColor(QtGui.QPalette.Highlight, sel_color)
  6594. p.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('white'))
  6595. self.document_editor_tab.code_editor.setPalette(p)
  6596. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(sel_color.name()))
  6597. new_val = str(sel_color.name())
  6598. self.ui.sel_color_entry.set_value(new_val)
  6599. self.app.defaults['document_sel_color'] = new_val
  6600. def to_dict(self):
  6601. """
  6602. Returns a representation of the object as a dictionary.
  6603. Attributes to include are listed in ``self.ser_attrs``.
  6604. :return: A dictionary-encoded copy of the object.
  6605. :rtype: dict
  6606. """
  6607. d = {}
  6608. for attr in self.ser_attrs:
  6609. d[attr] = getattr(self, attr)
  6610. return d
  6611. def from_dict(self, d):
  6612. """
  6613. Sets object's attributes from a dictionary.
  6614. Attributes to include are listed in ``self.ser_attrs``.
  6615. This method will look only for only and all the
  6616. attributes in ``self.ser_attrs``. They must all
  6617. be present. Use only for deserializing saved
  6618. objects.
  6619. :param d: Dictionary of attributes to set in the object.
  6620. :type d: dict
  6621. :return: None
  6622. """
  6623. for attr in self.ser_attrs:
  6624. setattr(self, attr, d[attr])
  6625. # end of file