FlatCAMObj.py 320 KB

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