FlatCAMObj.py 338 KB

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