FlatCAMObj.py 275 KB

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